Skip to main content

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod activity_hydration;
4mod cancellation_context;
5mod cancellation_replay_clock;
6mod cancellation_scope;
7mod cancellation_scope_history;
8mod cancellation_scope_replay;
9mod cooperative_cancellation;
10mod local_activity;
11mod runtime_payloads;
12mod runtime_uploads;
13mod sticky_worker;
14mod sticky_workflow_cache;
15mod worker_session;
16mod workflow_hydration;
17
18pub use cancellation_context::{
19    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
20};
21pub use cancellation_scope::CancellationScopeOpenReceipt;
22#[doc(hidden)]
23pub use cancellation_scope_history::{
24    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
25};
26#[doc(hidden)]
27pub use cancellation_scope_replay::CancellationScopeRequested;
28
29pub use cooperative_cancellation::{
30    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
31    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
32    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
33    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
34};
35
36use std::{
37    any::{type_name, Any, TypeId},
38    collections::{BTreeMap, BTreeSet, HashMap},
39    future::Future,
40    io::{self, Read},
41    pin::Pin,
42    sync::{
43        atomic::{AtomicBool, Ordering},
44        Arc, Mutex, OnceLock,
45    },
46    task::{Context as TaskContext, Poll},
47    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
48};
49
50use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
51use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
52use chrono::DateTime;
53use futures_util::{
54    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
55};
56pub use local_activity::LocalActivityOptions;
57use serde::{
58    de::DeserializeOwned,
59    ser::{SerializeMap, SerializeSeq},
60    Deserialize, Deserializer, Serialize, Serializer,
61};
62pub use serde_json::{json, Value};
63use sha2::{Digest, Sha256};
64pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
65use thiserror::Error;
66pub use uuid::Uuid;
67pub use worker_session::{WorkerSession, WorkerSessionOptions};
68
69pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
70pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
71
72/// Select the worker request protocol without enabling optional capabilities.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum WorkerProtocolVersion {
76    /// Compatibility with Servers that implement only worker protocol 1.19.
77    V119,
78    /// The default worker protocol.
79    #[default]
80    V120,
81}
82
83impl WorkerProtocolVersion {
84    fn as_str(self) -> &'static str {
85        match self {
86            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
87            Self::V120 => WORKER_PROTOCOL_VERSION,
88        }
89    }
90}
91const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
92/// First additive worker protocol that defines portable worker-affinity features.
93pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
94pub const CONTROL_PLANE_VERSION: &str = "2";
95pub const DEFAULT_CODEC: &str = "avro";
96pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
97/// Worker-registration capability for authored condition-wait occurrence identity.
98pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
99    "condition_wait_occurrence_identity";
100/// Worker-registration capability for portable memo upserts.
101pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
102/// Worker-registration capability for server-routed read-only queries.
103pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
104/// Worker-registration capability for canonical typed search attributes.
105pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
106/// Worker-registration capability for synchronous workflow updates.
107pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
108/// Worker-registration capability for durable named input streams.
109pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
110/// Worker-registration capability for persisted first-completion selection.
111pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
112pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
113pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
114pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
115pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
116pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
117/// First additive worker protocol that defines query-task transport.
118pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
119/// First additive worker protocol that defines typed search-attribute upserts.
120pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
121/// First additive worker protocol that defines portable memo upserts.
122pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
123/// First additive worker protocol that preserves declared search-attribute types.
124pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
125/// First additive worker protocol that defines external durable condition waits.
126pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
127/// First additive worker protocol that preserves authored condition-wait occurrences.
128pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
129/// First additive worker protocol that defines durable selection groups.
130pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
131
132pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
133    let Some((major, minor)) = version.split_once('.') else {
134        return false;
135    };
136    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
137}
138
139fn validate_user_signal_name(signal_name: &str) -> Result<()> {
140    if signal_name == MESSAGE_STREAM_SIGNAL {
141        return Err(Error::Codec(format!(
142            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
143        )));
144    }
145    Ok(())
146}
147
148const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
149const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
150    "Workflow task waiting for scheduled history.";
151const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
152const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
153const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
154const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
155const MAX_MEMO_ENTRIES: usize = 100;
156const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
157const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
158
159const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
160    "lease_expired",
161    "query_task_not_found",
162    "query_task_not_leased",
163    "query_task_timed_out",
164];
165
166/// Manifest for the default service-worker profile.
167///
168/// Inline local execution is enabled separately by [`Worker::local_activities`].
169/// Local execution, sessions and caching require explicit Worker configuration.
170pub fn portable_worker_affinity_capability_manifest() -> Value {
171    json!({
172        "local_activities": {
173            "supported": false,
174            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
175            "reason": "rust_worker_does_not_execute_record_local_activity",
176        },
177        "worker_sessions": {
178            "supported": false,
179            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
180            "reason": "rust_worker_has_no_typed_session_lifecycle",
181        },
182        "sticky_execution": {
183            "supported": false,
184            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
185            "reason": "rust_worker_uses_complete_durable_history_replay",
186        },
187    })
188}
189
190/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
191pub const AVRO_VALUE_SCHEMA_JSON: &str =
192    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
193pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
194pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
195const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
196
197static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
198static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
199    OnceLock::new();
200
201#[derive(Clone, Copy)]
202enum RequestProtocol {
203    ControlPlane,
204    DefaultWorker,
205    Worker(&'static str),
206}
207
208pub type Result<T> = std::result::Result<T, Error>;
209
210#[derive(Debug, Error)]
211pub enum Error {
212    #[error("transport error: {0}")]
213    Transport(#[from] reqwest::Error),
214    #[error(
215        "invalid Durable Workflow base URL: omit the SDK-owned /api suffix and pass the Server or Cloud runtime base URL; the SDK appends /api automatically"
216    )]
217    InvalidBaseUrl,
218    #[error("json error: {0}")]
219    Json(#[from] serde_json::Error),
220    #[error("http {status}: {body}")]
221    Http {
222        status: reqwest::StatusCode,
223        body: String,
224    },
225    #[error("codec error: {0}")]
226    Codec(String),
227    #[error(transparent)]
228    QueryFailed(QueryFailure),
229    #[error(transparent)]
230    Protocol(ProtocolFailure),
231    #[error(transparent)]
232    NonDeterministicReplay(ReplayFailure),
233    #[error(transparent)]
234    ChildWorkflowFailed(ChildWorkflowFailure),
235    #[error(transparent)]
236    ActivityFailed(ActivityFailure),
237    #[error(transparent)]
238    ParallelFailed(ParallelFailure),
239    #[error(transparent)]
240    SagaCompensationFailed(SagaCompensationFailure),
241    #[error(transparent)]
242    InvalidParallelGroup(ParallelGroupError),
243    #[error(transparent)]
244    DurableOperationCancelled(DurableOperationCancelled),
245    #[error(transparent)]
246    WorkflowCancellationRequested(WorkflowCancellationRequested),
247    #[error(transparent)]
248    CooperativeCancellationRequested(CooperativeCancellationRequested),
249    #[error(transparent)]
250    CancellationScopeRequested(CancellationScopeRequested),
251    #[error(transparent)]
252    WorkflowCommandRejected(WorkflowCommandRejection),
253    #[error(transparent)]
254    WorkflowFailed(WorkflowTerminalOutcome),
255    #[error(transparent)]
256    WorkflowCancelled(WorkflowTerminalOutcome),
257    #[error(transparent)]
258    WorkflowTerminated(WorkflowTerminalOutcome),
259    #[error(transparent)]
260    WorkflowTimedOut(WorkflowTerminalOutcome),
261    #[error(transparent)]
262    ActivityTaskRejected(ActivityTaskRejection),
263    #[error("workflow handler {0:?} is not registered")]
264    WorkflowNotRegistered(String),
265    #[error("activity handler {0:?} is not registered")]
266    ActivityNotRegistered(String),
267    #[error(
268        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
269    )]
270    HandlerType {
271        handler_kind: HandlerKind,
272        handler_name: String,
273        value_kind: HandlerValueKind,
274        rust_type: &'static str,
275        message: String,
276    },
277    #[error("workflow future yielded without emitting a durable command")]
278    WorkflowYieldedWithoutCommand,
279    #[error(
280        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
281    )]
282    MissingWorkflowCommandIdentity,
283    #[error("workflow state lock is poisoned")]
284    WorkflowStatePoisoned,
285    #[error("timer duration is too large for the worker protocol")]
286    TimerDurationOverflow,
287    #[error(transparent)]
288    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
289    #[error(transparent)]
290    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
291    #[error("operation timed out")]
292    Timeout,
293    #[error(
294        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
295    )]
296    MissingRoleCredentials {
297        role: &'static str,
298        opposite_role: &'static str,
299    },
300    #[error("worker loop error: {0}")]
301    WorkerLoop(String),
302    #[error(
303        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
304    )]
305    UnsupportedUpdateValidators { workflow_type: String },
306    #[error("{primary}; worker deregistration also failed: {deregistration}")]
307    WorkerShutdown {
308        primary: Box<Error>,
309        deregistration: Box<Error>,
310    },
311    #[error("invalid child workflow options: {0}")]
312    InvalidChildWorkflowOptions(String),
313    #[error("invalid workflow memo update: {0}")]
314    InvalidMemoUpdate(String),
315    #[error(
316        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
317    )]
318    WorkflowMemoUpdatesUnavailable,
319    #[error("cooperative cancellation is unavailable: {0}")]
320    CooperativeCancellationUnavailable(String),
321    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
322    CancellationScopeExecutionUnavailable,
323    #[error("invalid cooperative cancellation: {0}")]
324    InvalidCooperativeCancellation(String),
325    #[error("activity execution no longer owns its claim: {0}")]
326    ActivityExecutionAbandoned(String),
327    #[error(transparent)]
328    InvalidActivityOptions(ActivityOptionsError),
329    #[error(transparent)]
330    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
331    #[doc(hidden)]
332    #[error("workflow requested continue as new")]
333    ContinueAsNew(ContinueAsNewRequest),
334}
335
336/// Handler namespaces checked independently within a Worker.
337#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
338pub enum RegistrationKind {
339    Workflow,
340    Activity,
341    Query,
342    Update,
343}
344
345impl std::fmt::Display for RegistrationKind {
346    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347        formatter.write_str(match self {
348            Self::Workflow => "workflow",
349            Self::Activity => "activity",
350            Self::Query => "query",
351            Self::Update => "update",
352        })
353    }
354}
355
356/// The authoring adapter and source location of a handler registration.
357#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct HandlerRegistration {
359    pub method: &'static str,
360    pub handler_type: &'static str,
361    pub file: &'static str,
362    pub line: u32,
363    pub column: u32,
364}
365
366impl std::fmt::Display for HandlerRegistration {
367    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368        write!(
369            formatter,
370            "{} at {}:{}:{} ({})",
371            self.method, self.file, self.line, self.column, self.handler_type
372        )
373    }
374}
375
376/// Ambiguous local configuration, rejected before contacting Server.
377#[derive(Clone, Debug, Error, PartialEq, Eq)]
378#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
379pub struct DuplicateRegistrationError {
380    pub handler_kind: RegistrationKind,
381    pub handler_name: String,
382    /// Query/update registrations are scoped to their owning workflow type.
383    pub workflow_type: Option<String>,
384    pub first_definition: HandlerRegistration,
385    pub second_definition: HandlerRegistration,
386}
387
388impl From<DuplicateRegistrationError> for Error {
389    fn from(error: DuplicateRegistrationError) -> Self {
390        Self::WorkerLoop(error.to_string())
391    }
392}
393
394/// Validation failure for a durable condition-wait definition.
395#[derive(Clone, Debug, Error, PartialEq, Eq)]
396pub enum ConditionWaitOptionsError {
397    #[error("condition_key must be non-empty")]
398    EmptyKey,
399    #[error("condition_definition_fingerprint must be non-empty")]
400    EmptyPredicateIdentity,
401    #[error("condition timeout is too large for the worker protocol")]
402    TimeoutOverflow,
403}
404
405/// Stable identity and optional durable timeout for a condition wait.
406///
407/// `predicate_identity` is recorded as the worker protocol's
408/// `condition_definition_fingerprint` and must change whenever predicate
409/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
410/// is written inline; it derives this identity from the predicate tokens.
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub struct ConditionWaitOptions {
413    condition_key: String,
414    predicate_identity: String,
415    timeout: Option<Duration>,
416}
417
418impl ConditionWaitOptions {
419    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
420        Self {
421            condition_key: condition_key.into(),
422            predicate_identity: predicate_identity.into(),
423            timeout: None,
424        }
425    }
426
427    pub fn timeout(mut self, timeout: Duration) -> Self {
428        self.timeout = Some(timeout);
429        self
430    }
431
432    fn validate(
433        &self,
434    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
435        let condition_key = self.condition_key.trim();
436        if condition_key.is_empty() {
437            return Err(ConditionWaitOptionsError::EmptyKey);
438        }
439        let predicate_identity = self.predicate_identity.trim();
440        if predicate_identity.is_empty() {
441            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
442        }
443        let timeout_seconds = self
444            .timeout
445            .map(|timeout| {
446                timeout
447                    .as_secs()
448                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
449                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
450            })
451            .transpose()?;
452
453        Ok(ValidatedConditionWaitOptions {
454            condition_key: condition_key.to_string(),
455            predicate_identity: predicate_identity.to_string(),
456            timeout_seconds,
457        })
458    }
459}
460
461#[derive(Clone, Debug, PartialEq, Eq)]
462struct ValidatedConditionWaitOptions {
463    condition_key: String,
464    predicate_identity: String,
465    timeout_seconds: Option<u64>,
466}
467
468const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
469
470/// Unambiguous terminal result of a durable condition wait.
471#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(rename_all = "snake_case")]
473pub enum ConditionWaitResult {
474    Satisfied,
475    TimedOut,
476}
477
478impl ConditionWaitResult {
479    pub fn is_satisfied(self) -> bool {
480        self == Self::Satisfied
481    }
482
483    pub fn is_timed_out(self) -> bool {
484        self == Self::TimedOut
485    }
486}
487
488/// Build the stable condition definition identity used by [`wait_condition!`].
489#[doc(hidden)]
490pub fn __condition_definition_fingerprint(source: &str) -> String {
491    let mut digest = Sha256::new();
492    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
493    digest.update(source.as_bytes());
494    format!("sha256:{:x}", digest.finalize())
495}
496
497/// Create a durable condition wait whose predicate definition is fingerprinted
498/// from its inline Rust tokens.
499///
500/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
501/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
502#[macro_export]
503macro_rules! wait_condition {
504    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
505        $ctx.wait_condition(
506            $crate::ConditionWaitOptions::new(
507                $key,
508                $crate::__condition_definition_fingerprint(concat!(
509                    module_path!(),
510                    "\0",
511                    stringify!($predicate)
512                )),
513            )
514            .timeout($timeout),
515            $predicate,
516        )
517    }};
518    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
519        $ctx.wait_condition(
520            $crate::ConditionWaitOptions::new(
521                $key,
522                $crate::__condition_definition_fingerprint(concat!(
523                    module_path!(),
524                    "\0",
525                    stringify!($predicate)
526                )),
527            ),
528            $predicate,
529        )
530    }};
531}
532
533const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
534const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
535const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
536const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
537const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
538
539/// Validation failure for a typed workflow search-attribute update.
540#[derive(Clone, Debug, Error, PartialEq, Eq)]
541pub enum SearchAttributeUpdateError {
542    #[error("search-attribute update requires at least one attribute")]
543    Empty,
544    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
545    InvalidKey(String),
546    #[error("search-attribute update exceeds the limit of 100 attributes")]
547    TooManyAttributes,
548    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
549    ValueTooLong {
550        key: String,
551        kind: &'static str,
552        limit: usize,
553    },
554    #[error(
555        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
556    )]
557    EmptyString(String),
558    #[error("search attribute {0:?} has a non-finite float value")]
559    NonFiniteFloat(String),
560    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
561    InvalidDateTime(String),
562    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
563    PayloadTooLarge,
564}
565
566/// One public typed search-attribute value.
567#[derive(Clone, Debug, PartialEq)]
568pub enum SearchAttributeValue {
569    String(String),
570    Keyword(String),
571    KeywordList(Vec<String>),
572    Int(i64),
573    Float(f64),
574    Bool(bool),
575    DateTime(String),
576    Delete,
577}
578
579impl SearchAttributeValue {
580    fn type_name(&self) -> Option<&'static str> {
581        match self {
582            Self::String(_) => Some("string"),
583            Self::Keyword(_) => Some("keyword"),
584            Self::KeywordList(_) => Some("keyword_list"),
585            Self::Int(_) => Some("int"),
586            Self::Float(_) => Some("float"),
587            Self::Bool(_) => Some("bool"),
588            Self::DateTime(_) => Some("datetime"),
589            Self::Delete => None,
590        }
591    }
592
593    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
594        let normalize_string = |value: String, kind: &'static str, limit: usize| {
595            let value = value.trim().to_string();
596            if value.is_empty() {
597                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
598            }
599            if value.len() > limit {
600                return Err(SearchAttributeUpdateError::ValueTooLong {
601                    key: key.to_string(),
602                    kind,
603                    limit,
604                });
605            }
606            Ok(value)
607        };
608
609        match self {
610            Self::String(value) => Ok(Self::String(normalize_string(
611                value,
612                "string",
613                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
614            )?)),
615            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
616                value,
617                "keyword",
618                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
619            )?)),
620            Self::KeywordList(values) => {
621                let values = values
622                    .into_iter()
623                    .map(|value| {
624                        let value = value.trim().to_string();
625                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
626                            return Err(SearchAttributeUpdateError::ValueTooLong {
627                                key: key.to_string(),
628                                kind: "keyword-list entry",
629                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
630                            });
631                        }
632                        Ok(value)
633                    })
634                    .collect::<std::result::Result<Vec<_>, _>>()?;
635                Ok(Self::KeywordList(values))
636            }
637            Self::Float(value) if !value.is_finite() => {
638                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
639            }
640            Self::DateTime(value) => {
641                let value =
642                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
643                if DateTime::parse_from_rfc3339(&value).is_err() {
644                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
645                }
646                Ok(Self::DateTime(value))
647            }
648            value => Ok(value),
649        }
650    }
651
652    fn into_json(self) -> Value {
653        match self {
654            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
655                Value::String(value)
656            }
657            Self::KeywordList(values) => {
658                Value::Array(values.into_iter().map(Value::String).collect())
659            }
660            Self::Int(value) => json!(value),
661            Self::Float(value) => json!(value),
662            Self::Bool(value) => json!(value),
663            Self::Delete => Value::Null,
664        }
665    }
666}
667
668/// Validated typed workflow-side search-attribute mutation.
669#[derive(Clone, Debug, Default, PartialEq)]
670pub struct SearchAttributeUpdate {
671    attributes: BTreeMap<String, SearchAttributeValue>,
672}
673
674impl SearchAttributeUpdate {
675    pub fn new() -> Self {
676        Self::default()
677    }
678
679    pub fn set(
680        mut self,
681        key: impl Into<String>,
682        value: SearchAttributeValue,
683    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
684        let key = key.into();
685        validate_search_attribute_key(&key)?;
686        if !self.attributes.contains_key(&key)
687            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
688        {
689            return Err(SearchAttributeUpdateError::TooManyAttributes);
690        }
691        self.attributes.insert(key.clone(), value.normalized(&key)?);
692        self.validate_size()?;
693        Ok(self)
694    }
695
696    pub fn string(
697        self,
698        key: impl Into<String>,
699        value: impl Into<String>,
700    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
701        self.set(key, SearchAttributeValue::String(value.into()))
702    }
703
704    pub fn keyword(
705        self,
706        key: impl Into<String>,
707        value: impl Into<String>,
708    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
709        self.set(key, SearchAttributeValue::Keyword(value.into()))
710    }
711
712    pub fn keyword_list<I, V>(
713        self,
714        key: impl Into<String>,
715        values: I,
716    ) -> std::result::Result<Self, SearchAttributeUpdateError>
717    where
718        I: IntoIterator<Item = V>,
719        V: Into<String>,
720    {
721        self.set(
722            key,
723            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
724        )
725    }
726
727    pub fn int(
728        self,
729        key: impl Into<String>,
730        value: i64,
731    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
732        self.set(key, SearchAttributeValue::Int(value))
733    }
734
735    pub fn float(
736        self,
737        key: impl Into<String>,
738        value: f64,
739    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
740        self.set(key, SearchAttributeValue::Float(value))
741    }
742
743    pub fn bool(
744        self,
745        key: impl Into<String>,
746        value: bool,
747    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
748        self.set(key, SearchAttributeValue::Bool(value))
749    }
750
751    pub fn datetime(
752        self,
753        key: impl Into<String>,
754        value: impl Into<String>,
755    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
756        self.set(key, SearchAttributeValue::DateTime(value.into()))
757    }
758
759    pub fn delete(
760        self,
761        key: impl Into<String>,
762    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
763        self.set(key, SearchAttributeValue::Delete)
764    }
765
766    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
767        let (attributes, _) = self.clone().into_wire_parts();
768        if serde_json::to_vec(&attributes)
769            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
770            .unwrap_or(true)
771        {
772            return Err(SearchAttributeUpdateError::PayloadTooLarge);
773        }
774        Ok(())
775    }
776
777    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
778        let mut attributes = serde_json::Map::new();
779        let mut attribute_types = BTreeMap::new();
780        for (key, value) in self.attributes {
781            if let Some(type_name) = value.type_name() {
782                attribute_types.insert(key.clone(), type_name.to_string());
783            }
784            attributes.insert(key, value.into_json());
785        }
786        (Value::Object(attributes), attribute_types)
787    }
788
789    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
790        if self.attributes.is_empty() {
791            return Err(SearchAttributeUpdateError::Empty);
792        }
793        self.validate_size()
794    }
795}
796
797fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
798    let valid = !key.is_empty()
799        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
800        && key
801            .bytes()
802            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
803    if valid {
804        Ok(())
805    } else {
806        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
807    }
808}
809
810/// The registered handler family reported by [`Error::HandlerType`].
811#[derive(Clone, Copy, Debug, PartialEq, Eq)]
812pub enum HandlerKind {
813    Workflow,
814    Activity,
815}
816
817impl std::fmt::Display for HandlerKind {
818    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819        formatter.write_str(match self {
820            Self::Workflow => "workflow",
821            Self::Activity => "activity",
822        })
823    }
824}
825
826/// Whether a typed handler failed to adapt its input or result.
827#[derive(Clone, Copy, Debug, PartialEq, Eq)]
828pub enum HandlerValueKind {
829    Input,
830    Result,
831}
832
833impl std::fmt::Display for HandlerValueKind {
834    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
835        formatter.write_str(match self {
836            Self::Input => "input",
837            Self::Result => "result",
838        })
839    }
840}
841
842/// The lifecycle command sent to a workflow execution.
843#[derive(Clone, Copy, Debug, PartialEq, Eq)]
844pub enum WorkflowCommandKind {
845    Cancel,
846    Terminate,
847}
848
849impl WorkflowCommandKind {
850    fn as_str(self) -> &'static str {
851        match self {
852            Self::Cancel => "cancel",
853            Self::Terminate => "terminate",
854        }
855    }
856}
857
858/// Optional structured fields for a cancellation or termination request.
859#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
860pub struct WorkflowCommandOptions {
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub reason: Option<String>,
863    #[serde(skip_serializing_if = "Option::is_none")]
864    pub request_id: Option<String>,
865}
866
867/// Server-enforced timeout policy for a workflow start.
868///
869/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
870/// only bounds how long the caller waits. A server deadline produces a terminal
871/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
872/// `run_timeout`.
873#[derive(Clone, Debug, PartialEq, Eq)]
874pub struct WorkflowStartOptions {
875    pub execution_timeout_seconds: u64,
876    pub run_timeout_seconds: u64,
877}
878
879impl Default for WorkflowStartOptions {
880    fn default() -> Self {
881        Self {
882            execution_timeout_seconds: 3600,
883            run_timeout_seconds: 600,
884        }
885    }
886}
887
888impl WorkflowStartOptions {
889    pub fn new() -> Self {
890        Self::default()
891    }
892
893    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
894        self.execution_timeout_seconds = seconds;
895        self
896    }
897
898    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
899        self.run_timeout_seconds = seconds;
900        self
901    }
902
903    fn validate(&self) -> Result<()> {
904        if self.execution_timeout_seconds == 0 {
905            return Err(Error::Codec(
906                "execution_timeout_seconds must be at least 1".to_string(),
907            ));
908        }
909        if self.run_timeout_seconds == 0 {
910            return Err(Error::Codec(
911                "run_timeout_seconds must be at least 1".to_string(),
912            ));
913        }
914        if self.run_timeout_seconds > self.execution_timeout_seconds {
915            return Err(Error::Codec(
916                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
917            ));
918        }
919
920        Ok(())
921    }
922}
923
924/// Optional routing overrides for a continue-as-new transition.
925///
926/// Omitted values retain the current workflow type and task queue. Server-owned
927/// instance metadata is not accepted here and is carried by the server.
928#[derive(Clone, Debug, Default, PartialEq, Eq)]
929pub struct ContinueAsNewOptions {
930    pub workflow_type: Option<String>,
931    pub task_queue: Option<String>,
932}
933
934impl ContinueAsNewOptions {
935    pub fn new() -> Self {
936        Self::default()
937    }
938
939    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
940        self.workflow_type = Some(workflow_type.into());
941        self
942    }
943
944    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
945        self.task_queue = Some(task_queue.into());
946        self
947    }
948
949    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
950        for (field, value) in [
951            ("workflow_type", self.workflow_type.as_deref()),
952            ("task_queue", self.task_queue.as_deref()),
953        ] {
954            if value.is_some_and(|value| value.trim().is_empty()) {
955                return Err(ContinueAsNewOptionsError {
956                    field,
957                    message: format!("{field} must not be empty"),
958                });
959            }
960        }
961        Ok(())
962    }
963}
964
965/// A stable validation error raised before a continue-as-new command is emitted.
966#[derive(Clone, Debug, Error, PartialEq, Eq)]
967#[error("invalid continue-as-new option {field}: {message}")]
968pub struct ContinueAsNewOptionsError {
969    pub field: &'static str,
970    pub message: String,
971}
972
973/// Public history-budget information attached to the current workflow task.
974#[derive(Clone, Debug, Default, PartialEq, Eq)]
975pub struct WorkflowHistoryBudget {
976    pub event_count: u64,
977    pub size_bytes: Option<u64>,
978    pub continue_as_new_recommended: bool,
979    pub pressure: Option<String>,
980}
981
982#[doc(hidden)]
983#[derive(Clone, Debug)]
984pub struct ContinueAsNewRequest {
985    arguments: AvroValue,
986    options: ContinueAsNewOptions,
987}
988
989impl WorkflowCommandOptions {
990    pub fn new() -> Self {
991        Self::default()
992    }
993
994    pub fn reason(mut self, reason: impl Into<String>) -> Self {
995        self.reason = Some(reason.into());
996        self
997    }
998
999    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1000        self.request_id = Some(request_id.into());
1001        self
1002    }
1003}
1004
1005/// The accepted, machine-readable result of a lifecycle command.
1006#[derive(Clone, Debug, PartialEq)]
1007pub struct WorkflowCommandResult {
1008    pub command: WorkflowCommandKind,
1009    pub workflow_id: String,
1010    pub run_id: Option<String>,
1011    pub outcome: Option<String>,
1012    pub reason: Option<String>,
1013    pub command_status: Option<String>,
1014    pub raw: Value,
1015}
1016
1017/// A new run continuing a failed run from its recorded activity boundary.
1018#[derive(Clone, Debug, PartialEq)]
1019pub struct WorkflowRedriveResult {
1020    pub workflow_id: String,
1021    pub source_run_id: String,
1022    pub run_id: String,
1023    pub resume_step_sequence: u64,
1024    pub raw: Value,
1025}
1026
1027/// A stable rejection returned by instance- or selected-run lifecycle commands.
1028#[derive(Clone, Debug, Error)]
1029#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1030pub struct WorkflowCommandRejection {
1031    pub command: WorkflowCommandKind,
1032    pub status: u16,
1033    pub reason: String,
1034    pub message: String,
1035    pub workflow_id: String,
1036    pub run_id: Option<String>,
1037    pub target_scope: Option<String>,
1038    pub body: Value,
1039}
1040
1041/// Stable terminal categories returned by [`WorkflowHandle::result`].
1042#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1043pub enum WorkflowTerminalKind {
1044    Failed,
1045    Cancelled,
1046    Terminated,
1047    TimedOut,
1048}
1049
1050/// A typed terminal workflow outcome with durable identity and failure metadata.
1051///
1052/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1053/// of parsing its display representation. Fields remain `None` when an older
1054/// server did not publish that metadata.
1055#[derive(Clone, Debug, Error)]
1056#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1057pub struct WorkflowTerminalOutcome {
1058    pub kind: WorkflowTerminalKind,
1059    pub workflow_id: String,
1060    pub run_id: Option<String>,
1061    pub reason: String,
1062    pub failure_category: Option<String>,
1063    pub failure_id: Option<String>,
1064    pub exception_type: Option<String>,
1065    pub exception_class: Option<String>,
1066    pub non_retryable: Option<bool>,
1067    pub message: Option<String>,
1068    pub exception: Option<Value>,
1069    pub raw: Value,
1070}
1071
1072/// A worker-side activity settlement or heartbeat rejected by durable state.
1073#[derive(Clone, Debug, Error)]
1074#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1075pub struct ActivityTaskRejection {
1076    pub operation: String,
1077    pub status: u16,
1078    pub reason: String,
1079    pub task_id: String,
1080    pub activity_attempt_id: String,
1081    pub cancel_requested: bool,
1082    pub can_continue: Option<bool>,
1083    pub run_closed_reason: Option<String>,
1084    pub body: Value,
1085}
1086
1087/// Stable validation categories for [`ActivityOptions`].
1088#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1089pub enum ActivityOptionsErrorKind {
1090    EmptyTaskQueue,
1091    EmptyRetryPolicy,
1092    InvalidMaxAttempts,
1093    BackoffWithoutRetryBudget,
1094    TooManyBackoffIntervals,
1095    InvalidBackoffCoefficient,
1096    BackoffGenerationTooLarge,
1097    BackoffOverflow,
1098    EmptyNonRetryableErrorType,
1099    TimeoutNotPositive,
1100    MissingTotalTimeout,
1101    TimeoutOverflow,
1102    TimeoutOrder,
1103}
1104
1105/// A machine-readable activity-options validation failure.
1106#[derive(Clone, Debug, Error, PartialEq, Eq)]
1107#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1108pub struct ActivityOptionsError {
1109    pub kind: ActivityOptionsErrorKind,
1110    pub field: Option<&'static str>,
1111    pub message: String,
1112}
1113
1114impl ActivityOptionsError {
1115    fn new(
1116        kind: ActivityOptionsErrorKind,
1117        field: Option<&'static str>,
1118        message: impl Into<String>,
1119    ) -> Self {
1120        Self {
1121            kind,
1122            field,
1123            message: message.into(),
1124        }
1125    }
1126}
1127
1128/// Stable terminal categories returned when an awaited activity does not succeed.
1129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1130pub enum ActivityFailureKind {
1131    Failed,
1132    Cancelled,
1133    TimedOut,
1134}
1135
1136/// A stable, machine-readable terminal activity failure.
1137///
1138/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1139/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1140#[derive(Clone, Debug, Error, PartialEq)]
1141#[error("activity failed ({reason}): {message}")]
1142pub struct ActivityFailure {
1143    pub kind: ActivityFailureKind,
1144    pub reason: String,
1145    pub message: String,
1146    pub activity_execution_id: Option<String>,
1147    pub activity_attempt_id: Option<String>,
1148    pub activity_type: Option<String>,
1149    pub activity_class: Option<String>,
1150    pub attempt_number: Option<u64>,
1151    pub failure_id: Option<String>,
1152    pub failure_category: Option<String>,
1153    pub timeout_kind: Option<String>,
1154    pub non_retryable: bool,
1155    pub exception_type: Option<String>,
1156    pub exception_class: Option<String>,
1157    pub code: Option<Value>,
1158    pub exception: Option<Value>,
1159}
1160
1161/// Stable terminal categories returned when an awaited child does not succeed.
1162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1163pub enum ChildWorkflowFailureKind {
1164    Failed,
1165    Cancelled,
1166    Terminated,
1167}
1168
1169/// A stable, machine-readable child workflow failure delivered to its parent.
1170///
1171/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1172/// of parsing the display message. Child and parent identifiers retain the
1173/// relationship recorded in durable history across worker restarts.
1174#[derive(Clone, Debug, Error)]
1175#[error("child workflow failed ({reason}): {message}")]
1176pub struct ChildWorkflowFailure {
1177    pub kind: ChildWorkflowFailureKind,
1178    pub reason: String,
1179    pub message: String,
1180    pub parent_workflow_id: Option<String>,
1181    pub parent_workflow_run_id: Option<String>,
1182    pub child_workflow_id: Option<String>,
1183    pub child_workflow_run_id: Option<String>,
1184    pub child_workflow_type: Option<String>,
1185    pub failure_id: Option<String>,
1186    pub failure_category: Option<String>,
1187    pub exception_type: Option<String>,
1188    pub exception_class: Option<String>,
1189    pub non_retryable: bool,
1190    pub code: Option<Value>,
1191    pub exception: Option<Value>,
1192}
1193
1194/// The identity of one durable workflow execution.
1195#[derive(Clone, Debug, PartialEq, Eq)]
1196pub struct WorkflowIdentity {
1197    pub workflow_id: Option<String>,
1198    pub run_id: Option<String>,
1199}
1200
1201/// A successful child result together with its durable parent-child identity.
1202#[derive(Clone, Debug, PartialEq)]
1203pub struct ChildWorkflowResult {
1204    pub parent: WorkflowIdentity,
1205    pub child: WorkflowIdentity,
1206    pub child_workflow_type: Option<String>,
1207    pub result: Value,
1208}
1209
1210/// Lossless successful child result for fixed Avro Value workflows.
1211#[derive(Clone, Debug, PartialEq)]
1212pub struct ChildWorkflowAvroResult {
1213    pub parent: WorkflowIdentity,
1214    pub child: WorkflowIdentity,
1215    pub child_workflow_type: Option<String>,
1216    pub result: AvroValue,
1217}
1218
1219/// Stable user-facing identity for one member of a durable selection group.
1220#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1221#[serde(untagged)]
1222pub enum SelectionKey {
1223    Index(usize),
1224    Name(String),
1225}
1226
1227impl From<usize> for SelectionKey {
1228    fn from(value: usize) -> Self {
1229        Self::Index(value)
1230    }
1231}
1232
1233impl From<String> for SelectionKey {
1234    fn from(value: String) -> Self {
1235        Self::Name(value)
1236    }
1237}
1238
1239impl From<&str> for SelectionKey {
1240    fn from(value: &str) -> Self {
1241        Self::Name(value.to_string())
1242    }
1243}
1244
1245/// Typed result of explicitly awaiting a cancelled non-winning operation.
1246#[derive(Clone, Debug, Error, PartialEq, Eq)]
1247#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1248pub struct DurableOperationCancelled {
1249    pub selection_group_id: String,
1250    pub member_key: SelectionKey,
1251    pub member_index: usize,
1252    pub operation_kind: String,
1253    pub operation_identity: String,
1254}
1255
1256/// Stable identity for one enclosing deterministic parallel group.
1257///
1258/// The same fields are attached to every ordinary activity, timer, or child
1259/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1260/// no Rust-specific wire command is introduced.
1261#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1262pub struct ParallelGroupMetadata {
1263    pub parallel_group_id: String,
1264    pub parallel_group_kind: String,
1265    pub parallel_group_base_sequence: u64,
1266    pub parallel_group_size: usize,
1267    pub parallel_group_index: usize,
1268    #[serde(default, skip_serializing_if = "Option::is_none")]
1269    pub parallel_group_mode: Option<String>,
1270    #[serde(default, skip_serializing_if = "Option::is_none")]
1271    pub selection_member_key: Option<SelectionKey>,
1272    #[serde(default, skip_serializing_if = "Option::is_none")]
1273    pub selection_member_index: Option<usize>,
1274    #[serde(default, skip_serializing_if = "Option::is_none")]
1275    pub selection_member_base_sequence: Option<u64>,
1276    #[serde(default, skip_serializing_if = "Option::is_none")]
1277    pub selection_member_size: Option<usize>,
1278    #[serde(default, skip_serializing_if = "Option::is_none")]
1279    pub selection_member_kind: Option<String>,
1280}
1281
1282/// One input-ordered result returned by [`WorkflowContext::parallel`].
1283#[derive(Clone, Debug, PartialEq)]
1284pub enum ParallelResult {
1285    Activity(Value),
1286    ChildWorkflow(ChildWorkflowResult),
1287    Timer,
1288    Signal(Vec<Value>),
1289    Condition(ConditionWaitResult),
1290    Group(Vec<ParallelResult>),
1291}
1292
1293/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1294#[derive(Clone, Debug, PartialEq)]
1295pub enum ParallelAvroResult {
1296    Activity(AvroValue),
1297    ChildWorkflow(ChildWorkflowAvroResult),
1298    Timer,
1299    Signal(Vec<AvroValue>),
1300    Condition(ConditionWaitResult),
1301    Group(Vec<ParallelAvroResult>),
1302}
1303
1304impl ParallelAvroResult {
1305    fn into_json_result(self) -> Result<ParallelResult> {
1306        match self {
1307            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1308            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1309                parent: result.parent,
1310                child: result.child,
1311                child_workflow_type: result.child_workflow_type,
1312                result: result.result.into_json()?,
1313            })),
1314            Self::Timer => Ok(ParallelResult::Timer),
1315            Self::Signal(values) => Ok(ParallelResult::Signal(
1316                values
1317                    .into_iter()
1318                    .map(AvroValue::into_json)
1319                    .collect::<Result<Vec<_>>>()?,
1320            )),
1321            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1322            Self::Group(results) => Ok(ParallelResult::Group(
1323                results
1324                    .into_iter()
1325                    .map(Self::into_json_result)
1326                    .collect::<Result<Vec<_>>>()?,
1327            )),
1328        }
1329    }
1330}
1331
1332/// One successful leaf retained when another parallel member failed.
1333#[derive(Clone, Debug, PartialEq)]
1334pub struct ParallelCompletion {
1335    pub member_path: Vec<usize>,
1336    pub result: ParallelResult,
1337}
1338
1339/// A deterministic join failed after some siblings had already completed.
1340///
1341/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1342/// error. `completed` is declaration ordered and contains only durable
1343/// successes observed in the same replay. Late sibling completions can add
1344/// entries on a later replay without changing `member_path` or the selected
1345/// positional failure.
1346#[derive(Debug, Error)]
1347#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1348pub struct ParallelFailure {
1349    pub group_id: String,
1350    pub member_path: Vec<usize>,
1351    pub group_path: Vec<ParallelGroupMetadata>,
1352    pub completed: Vec<ParallelCompletion>,
1353    #[source]
1354    pub cause: Box<Error>,
1355}
1356
1357/// Stable validation error returned before an invalid group emits commands.
1358#[derive(Clone, Debug, Error, PartialEq, Eq)]
1359#[error("invalid deterministic parallel group ({reason}): {message}")]
1360pub struct ParallelGroupError {
1361    pub reason: &'static str,
1362    pub member_path: Vec<usize>,
1363    pub message: String,
1364}
1365
1366/// Cooperative workflow cancellation observed at an author-controlled point.
1367#[derive(Clone, Debug, Error, PartialEq, Eq)]
1368#[error("workflow cancellation was requested")]
1369pub struct WorkflowCancellationRequested;
1370
1371/// A forward saga failure followed by a terminal compensation failure.
1372#[derive(Debug, Error)]
1373#[error(
1374    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1375)]
1376pub struct SagaCompensationFailure {
1377    pub initiating_failure: Box<Error>,
1378    pub compensation_failure: Box<Error>,
1379    pub compensation_activity_type: String,
1380    pub compensation_registration_order: usize,
1381}
1382
1383/// Server behavior when a parent closes while its child is still open.
1384#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1385pub enum ParentClosePolicy {
1386    #[default]
1387    Abandon,
1388    /// Legacy terminal cancellation without cooperative cleanup.
1389    RequestCancel,
1390    /// Request cooperative cleanup with the original lineage and deadline.
1391    RequestCancellation,
1392    Terminate,
1393}
1394
1395impl ParentClosePolicy {
1396    fn as_str(self) -> &'static str {
1397        match self {
1398            Self::Abandon => "abandon",
1399            Self::RequestCancel => "request_cancel",
1400            Self::RequestCancellation => "request_cancellation",
1401            Self::Terminate => "terminate",
1402        }
1403    }
1404}
1405
1406/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1407#[non_exhaustive]
1408#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1409pub enum CancellationPolicy {
1410    /// Request cancellation and continue without waiting. Historical Activity default.
1411    TryCancel,
1412    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1413    WaitCancellationCompleted,
1414    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1415    #[default]
1416    Abandon,
1417}
1418
1419impl CancellationPolicy {
1420    fn as_str(self) -> &'static str {
1421        match self {
1422            Self::TryCancel => "try_cancel",
1423            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1424            Self::Abandon => "abandon",
1425        }
1426    }
1427}
1428
1429/// Durable retry policy for one child workflow invocation.
1430#[derive(Clone, Debug, Default, PartialEq, Eq)]
1431pub struct ChildWorkflowRetryPolicy {
1432    pub max_attempts: Option<u32>,
1433    pub backoff_seconds: Vec<u64>,
1434    pub non_retryable_error_types: Vec<String>,
1435}
1436
1437/// Options recorded with a child-workflow command.
1438///
1439/// The task queue is mandatory so routing is explicit and replay-stable.
1440#[derive(Clone, Debug, PartialEq, Eq)]
1441pub struct ChildWorkflowOptions {
1442    pub task_queue: String,
1443    pub parent_close_policy: ParentClosePolicy,
1444    pub cancellation_policy: CancellationPolicy,
1445    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1446    pub execution_timeout_seconds: Option<u64>,
1447    pub run_timeout_seconds: Option<u64>,
1448}
1449
1450impl ChildWorkflowOptions {
1451    pub fn new(task_queue: impl Into<String>) -> Self {
1452        Self {
1453            task_queue: task_queue.into(),
1454            parent_close_policy: ParentClosePolicy::Abandon,
1455            cancellation_policy: CancellationPolicy::Abandon,
1456            retry_policy: None,
1457            execution_timeout_seconds: None,
1458            run_timeout_seconds: None,
1459        }
1460    }
1461
1462    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1463        self.parent_close_policy = policy;
1464        self
1465    }
1466
1467    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1468        self.cancellation_policy = policy;
1469        self
1470    }
1471
1472    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1473        self.retry_policy = Some(policy);
1474        self
1475    }
1476
1477    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1478        self.execution_timeout_seconds = Some(seconds);
1479        self
1480    }
1481
1482    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1483        self.run_timeout_seconds = Some(seconds);
1484        self
1485    }
1486}
1487
1488/// Backoff intervals for one durable activity retry policy.
1489#[derive(Clone, Debug, PartialEq, Eq)]
1490pub enum ActivityBackoff {
1491    /// Use these intervals between attempts. The server repeats the final
1492    /// interval if the retry budget contains more attempts than entries.
1493    /// All entries are retained, including those beyond the retry budget.
1494    Explicit(Vec<Duration>),
1495    /// Generate one interval for every retry using integer exponential growth.
1496    Exponential {
1497        initial_interval: Duration,
1498        coefficient: u32,
1499        maximum_interval: Option<Duration>,
1500    },
1501}
1502
1503/// Durable server-side retry policy for one activity execution.
1504#[derive(Clone, Debug, Default, PartialEq, Eq)]
1505pub struct ActivityRetryPolicy {
1506    pub max_attempts: Option<u32>,
1507    pub backoff: Option<ActivityBackoff>,
1508    pub non_retryable_error_types: Vec<String>,
1509}
1510
1511impl ActivityRetryPolicy {
1512    /// Start a policy with a finite attempt budget, including the first attempt.
1513    pub fn new(max_attempts: u32) -> Self {
1514        Self {
1515            max_attempts: Some(max_attempts),
1516            ..Self::default()
1517        }
1518    }
1519
1520    /// Preserve the complete explicit list independently of the attempt budget.
1521    /// Unused entries remain part of the policy compared during replay.
1522    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1523        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1524        self
1525    }
1526
1527    pub fn exponential_backoff(
1528        mut self,
1529        initial_interval: Duration,
1530        coefficient: u32,
1531        maximum_interval: Option<Duration>,
1532    ) -> Self {
1533        self.backoff = Some(ActivityBackoff::Exponential {
1534            initial_interval,
1535            coefficient,
1536            maximum_interval,
1537        });
1538        self
1539    }
1540
1541    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1542        self.non_retryable_error_types.push(error_type.into());
1543        self
1544    }
1545
1546    pub fn non_retryable_error_types(
1547        mut self,
1548        error_types: impl IntoIterator<Item = impl Into<String>>,
1549    ) -> Self {
1550        self.non_retryable_error_types
1551            .extend(error_types.into_iter().map(Into::into));
1552        self
1553    }
1554}
1555
1556/// Options recorded atomically on one deterministic `schedule_activity` command.
1557///
1558/// Durations are rounded up to whole seconds when encoded, so the server never
1559/// receives a shorter timeout or backoff than the caller requested.
1560#[derive(Clone, Debug, Default, PartialEq, Eq)]
1561pub struct ActivityOptions {
1562    pub task_queue: Option<String>,
1563    pub retry_policy: Option<ActivityRetryPolicy>,
1564    pub start_to_close_timeout: Option<Duration>,
1565    pub schedule_to_start_timeout: Option<Duration>,
1566    pub schedule_to_close_timeout: Option<Duration>,
1567    pub heartbeat_timeout: Option<Duration>,
1568    pub cancellation_policy: Option<CancellationPolicy>,
1569}
1570
1571impl ActivityOptions {
1572    pub fn new() -> Self {
1573        Self::default()
1574    }
1575
1576    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1577        self.task_queue = Some(task_queue.into());
1578        self
1579    }
1580
1581    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1582        self.retry_policy = Some(policy);
1583        self
1584    }
1585
1586    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1587        self.start_to_close_timeout = Some(timeout);
1588        self
1589    }
1590
1591    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1592        self.schedule_to_start_timeout = Some(timeout);
1593        self
1594    }
1595
1596    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1597        self.schedule_to_close_timeout = Some(timeout);
1598        self
1599    }
1600
1601    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1602        self.heartbeat_timeout = Some(timeout);
1603        self
1604    }
1605
1606    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1607        self.cancellation_policy = Some(policy);
1608        self
1609    }
1610
1611    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1612        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1613            && self.schedule_to_close_timeout.is_none()
1614        {
1615            return Err(ActivityOptionsError::new(
1616                ActivityOptionsErrorKind::MissingTotalTimeout,
1617                Some("schedule_to_close_timeout"),
1618                "remote Activity Abandon requires a finite positive total timeout",
1619            ));
1620        }
1621        if self
1622            .task_queue
1623            .as_deref()
1624            .is_some_and(|queue| queue.trim().is_empty())
1625        {
1626            return Err(ActivityOptionsError::new(
1627                ActivityOptionsErrorKind::EmptyTaskQueue,
1628                Some("task_queue"),
1629                "task_queue must not be empty",
1630            ));
1631        }
1632
1633        for (field, value) in [
1634            ("start_to_close_timeout", self.start_to_close_timeout),
1635            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1636            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1637            ("heartbeat_timeout", self.heartbeat_timeout),
1638        ] {
1639            if value.is_some_and(|value| value.is_zero()) {
1640                return Err(ActivityOptionsError::new(
1641                    ActivityOptionsErrorKind::TimeoutNotPositive,
1642                    Some(field),
1643                    format!("{field} must be positive"),
1644                ));
1645            }
1646        }
1647
1648        validate_timeout_order(
1649            "heartbeat_timeout",
1650            self.heartbeat_timeout,
1651            "start_to_close_timeout",
1652            self.start_to_close_timeout,
1653        )?;
1654        validate_timeout_order(
1655            "start_to_close_timeout",
1656            self.start_to_close_timeout,
1657            "schedule_to_close_timeout",
1658            self.schedule_to_close_timeout,
1659        )?;
1660        validate_timeout_order(
1661            "schedule_to_start_timeout",
1662            self.schedule_to_start_timeout,
1663            "schedule_to_close_timeout",
1664            self.schedule_to_close_timeout,
1665        )?;
1666
1667        Ok(ValidatedActivityOptions {
1668            task_queue: self.task_queue.clone(),
1669            retry_policy: self
1670                .retry_policy
1671                .as_ref()
1672                .map(validate_activity_retry_policy)
1673                .transpose()?,
1674            start_to_close_timeout: timeout_seconds(
1675                "start_to_close_timeout",
1676                self.start_to_close_timeout,
1677            )?,
1678            schedule_to_start_timeout: timeout_seconds(
1679                "schedule_to_start_timeout",
1680                self.schedule_to_start_timeout,
1681            )?,
1682            schedule_to_close_timeout: timeout_seconds(
1683                "schedule_to_close_timeout",
1684                self.schedule_to_close_timeout,
1685            )?,
1686            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1687            cancellation_policy: self.cancellation_policy,
1688        })
1689    }
1690}
1691
1692/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1693///
1694/// Constructors capture arguments but perform no I/O. The join validates the
1695/// complete tree, attaches the existing parallel-group metadata to every
1696/// ordinary command, schedules all leaves, and then suspends.
1697pub enum ParallelOperation {
1698    Activity {
1699        activity_type: String,
1700        options: ActivityOptions,
1701        arguments: Result<AvroValue>,
1702    },
1703    ChildWorkflow {
1704        workflow_type: String,
1705        options: ChildWorkflowOptions,
1706        arguments: Result<AvroValue>,
1707    },
1708    Timer(Duration),
1709    Signal(String),
1710    Condition {
1711        options: ConditionWaitOptions,
1712        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1713    },
1714    Group(Vec<ParallelOperation>),
1715}
1716
1717impl ParallelOperation {
1718    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1719        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1720    }
1721
1722    pub fn activity_with_options<T: Serialize>(
1723        activity_type: impl Into<String>,
1724        options: ActivityOptions,
1725        args: T,
1726    ) -> Self {
1727        Self::Activity {
1728            activity_type: activity_type.into(),
1729            options,
1730            arguments: AvroValue::from_serialize(&args),
1731        }
1732    }
1733
1734    pub fn child_workflow<T: Serialize>(
1735        workflow_type: impl Into<String>,
1736        options: ChildWorkflowOptions,
1737        args: T,
1738    ) -> Self {
1739        Self::ChildWorkflow {
1740            workflow_type: workflow_type.into(),
1741            options,
1742            arguments: AvroValue::from_serialize(&args),
1743        }
1744    }
1745
1746    pub fn timer(duration: Duration) -> Self {
1747        Self::Timer(duration)
1748    }
1749
1750    pub fn signal(signal_name: impl Into<String>) -> Self {
1751        Self::Signal(signal_name.into())
1752    }
1753
1754    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1755    where
1756        F: Fn() -> Result<bool> + Send + 'static,
1757    {
1758        Self::Condition {
1759            options,
1760            predicate: Box::new(predicate),
1761        }
1762    }
1763
1764    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1765        Self::Group(operations)
1766    }
1767}
1768
1769#[derive(Clone, Debug)]
1770struct ValidatedActivityOptions {
1771    task_queue: Option<String>,
1772    retry_policy: Option<Value>,
1773    start_to_close_timeout: Option<u64>,
1774    schedule_to_start_timeout: Option<u64>,
1775    schedule_to_close_timeout: Option<u64>,
1776    heartbeat_timeout: Option<u64>,
1777    cancellation_policy: Option<CancellationPolicy>,
1778}
1779
1780fn validate_timeout_order(
1781    smaller_name: &'static str,
1782    smaller: Option<Duration>,
1783    larger_name: &'static str,
1784    larger: Option<Duration>,
1785) -> std::result::Result<(), ActivityOptionsError> {
1786    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1787        return Err(ActivityOptionsError::new(
1788            ActivityOptionsErrorKind::TimeoutOrder,
1789            Some(smaller_name),
1790            format!("{smaller_name} must be <= {larger_name}"),
1791        ));
1792    }
1793    Ok(())
1794}
1795
1796fn timeout_seconds(
1797    field: &'static str,
1798    value: Option<Duration>,
1799) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1800    value
1801        .map(|value| {
1802            activity_protocol_seconds(value).ok_or_else(|| {
1803                ActivityOptionsError::new(
1804                    ActivityOptionsErrorKind::TimeoutOverflow,
1805                    Some(field),
1806                    format!("{field} is too large for the worker protocol"),
1807                )
1808            })
1809        })
1810        .transpose()
1811}
1812
1813fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1814    value
1815        .as_secs()
1816        .checked_add(u64::from(value.subsec_nanos() > 0))
1817}
1818
1819fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1820    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1821}
1822
1823fn validate_activity_retry_policy(
1824    policy: &ActivityRetryPolicy,
1825) -> std::result::Result<Value, ActivityOptionsError> {
1826    if policy.max_attempts.is_none()
1827        && policy.backoff.is_none()
1828        && policy.non_retryable_error_types.is_empty()
1829    {
1830        return Err(ActivityOptionsError::new(
1831            ActivityOptionsErrorKind::EmptyRetryPolicy,
1832            Some("retry_policy"),
1833            "retry_policy must configure at least one field",
1834        ));
1835    }
1836    if policy.max_attempts == Some(0) {
1837        return Err(ActivityOptionsError::new(
1838            ActivityOptionsErrorKind::InvalidMaxAttempts,
1839            Some("retry_policy.max_attempts"),
1840            "max_attempts must be >= 1",
1841        ));
1842    }
1843    if policy
1844        .non_retryable_error_types
1845        .iter()
1846        .any(|error_type| error_type.trim().is_empty())
1847    {
1848        return Err(ActivityOptionsError::new(
1849            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1850            Some("retry_policy.non_retryable_error_types"),
1851            "non_retryable_error_types must not contain empty values",
1852        ));
1853    }
1854
1855    let backoff_seconds = match &policy.backoff {
1856        None => None,
1857        Some(backoff) => {
1858            let max_attempts = policy.max_attempts.ok_or_else(|| {
1859                ActivityOptionsError::new(
1860                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1861                    Some("retry_policy.backoff"),
1862                    "backoff requires max_attempts",
1863                )
1864            })?;
1865            let retry_count = max_attempts.saturating_sub(1) as usize;
1866            let intervals = match backoff {
1867                ActivityBackoff::Explicit(intervals) => intervals.clone(),
1868                ActivityBackoff::Exponential {
1869                    initial_interval,
1870                    coefficient,
1871                    maximum_interval,
1872                } => {
1873                    if *coefficient < 1 {
1874                        return Err(ActivityOptionsError::new(
1875                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1876                            Some("retry_policy.backoff.coefficient"),
1877                            "backoff coefficient must be >= 1",
1878                        ));
1879                    }
1880                    if retry_count > 10_000 {
1881                        return Err(ActivityOptionsError::new(
1882                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1883                            Some("retry_policy.max_attempts"),
1884                            "generated backoff supports at most 10000 retry intervals",
1885                        ));
1886                    }
1887                    let mut current = *initial_interval;
1888                    let mut intervals = Vec::with_capacity(retry_count);
1889                    for _ in 0..retry_count {
1890                        let interval = maximum_interval
1891                            .map(|maximum| current.min(maximum))
1892                            .unwrap_or(current);
1893                        intervals.push(interval);
1894                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1895                            break;
1896                        }
1897                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1898                            ActivityOptionsError::new(
1899                                ActivityOptionsErrorKind::BackoffOverflow,
1900                                Some("retry_policy.backoff"),
1901                                "generated backoff interval overflowed",
1902                            )
1903                        })?;
1904                    }
1905                    intervals
1906                }
1907            };
1908            Some(
1909                intervals
1910                    .into_iter()
1911                    .map(|interval| {
1912                        activity_protocol_seconds(interval).ok_or_else(|| {
1913                            ActivityOptionsError::new(
1914                                ActivityOptionsErrorKind::BackoffOverflow,
1915                                Some("retry_policy.backoff"),
1916                                "backoff interval is too large for the worker protocol",
1917                            )
1918                        })
1919                    })
1920                    .collect::<std::result::Result<Vec<_>, _>>()?,
1921            )
1922        }
1923    };
1924
1925    let mut encoded = serde_json::Map::new();
1926    if let Some(max_attempts) = policy.max_attempts {
1927        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1928    }
1929    if let Some(backoff_seconds) = backoff_seconds {
1930        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1931    }
1932    if !policy.non_retryable_error_types.is_empty() {
1933        let mut canonical_error_types = Vec::new();
1934        for error_type in policy
1935            .non_retryable_error_types
1936            .iter()
1937            .map(|error_type| error_type.trim())
1938        {
1939            if !canonical_error_types.contains(&error_type) {
1940                canonical_error_types.push(error_type);
1941            }
1942        }
1943        encoded.insert(
1944            "non_retryable_error_types".to_string(),
1945            json!(canonical_error_types),
1946        );
1947    }
1948    Ok(Value::Object(encoded))
1949}
1950
1951/// A stable, machine-readable failure raised when workflow code no longer
1952/// reconstructs the durable command stream recorded in history.
1953#[derive(Clone, Debug, Error)]
1954#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1955pub struct ReplayFailure {
1956    pub reason: String,
1957    pub sequence: Option<u64>,
1958    pub expected: Option<String>,
1959    pub actual: Option<String>,
1960    pub message: String,
1961}
1962
1963impl ReplayFailure {
1964    fn new(
1965        reason: impl Into<String>,
1966        sequence: Option<u64>,
1967        expected: Option<String>,
1968        actual: Option<String>,
1969        message: impl Into<String>,
1970    ) -> Self {
1971        Self {
1972            reason: reason.into(),
1973            sequence,
1974            expected,
1975            actual,
1976            message: message.into(),
1977        }
1978    }
1979}
1980
1981/// A stable, machine-readable workflow query or query-task settlement failure.
1982#[derive(Clone, Debug, Error)]
1983#[error("query failed ({reason}, HTTP {status}): {message}")]
1984pub struct QueryFailure {
1985    pub status: u16,
1986    pub reason: String,
1987    pub message: String,
1988    pub body: Value,
1989}
1990
1991/// A stable failure returned when a server rejects an SDK protocol version.
1992#[derive(Clone, Debug, Error)]
1993#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1994pub struct ProtocolFailure {
1995    pub status: u16,
1996    pub reason: String,
1997    pub message: String,
1998    pub supported_version: Option<String>,
1999    pub requested_version: Option<String>,
2000    pub body: Value,
2001}
2002
2003#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2004pub struct PayloadEnvelope {
2005    pub codec: String,
2006    pub blob: String,
2007}
2008
2009impl PayloadEnvelope {
2010    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2011        encode_payload(value, DEFAULT_CODEC)
2012    }
2013
2014    /// Encode an explicit typed value, including the bytes branch that JSON
2015    /// serialization cannot represent.
2016    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2017        encode_avro_value(value)
2018    }
2019}
2020
2021/// Native adapter for the fixed language-neutral Avro Value schema.
2022#[derive(Clone, Debug)]
2023pub enum AvroValue {
2024    Null,
2025    Boolean(bool),
2026    Long(i64),
2027    Double(f64),
2028    Bytes(Vec<u8>),
2029    String(String),
2030    Array(Vec<AvroValue>),
2031    Map(BTreeMap<String, AvroValue>),
2032}
2033
2034impl PartialEq for AvroValue {
2035    fn eq(&self, other: &Self) -> bool {
2036        match (self, other) {
2037            (Self::Null, Self::Null) => true,
2038            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2039            (Self::Long(left), Self::Long(right)) => left == right,
2040            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2041            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2042            (Self::String(left), Self::String(right)) => left == right,
2043            (Self::Array(left), Self::Array(right)) => left == right,
2044            (Self::Map(left), Self::Map(right)) => left == right,
2045            _ => false,
2046        }
2047    }
2048}
2049
2050impl AvroValue {
2051    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2052        Self::from_serde_value(
2053            serde_value::to_value(value).map_err(|error| {
2054                Error::Codec(format!("could not adapt value for Avro: {error}"))
2055            })?,
2056        )
2057    }
2058
2059    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2060        use serde_value::Value as SerdeValue;
2061
2062        match value {
2063            SerdeValue::Unit => Ok(Self::Null),
2064            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2065            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2066            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2067            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2068            SerdeValue::I64(value) => Ok(Self::Long(value)),
2069            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2070            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2071            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2072            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2073                Error::Codec(
2074                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2075                        .to_string(),
2076                )
2077            }),
2078            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2079            SerdeValue::F64(value) => Self::finite_double(value),
2080            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2081            SerdeValue::String(value) => Ok(Self::String(value)),
2082            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2083            SerdeValue::Option(None) => Ok(Self::Null),
2084            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2085                Self::from_serde_value(*value)
2086            }
2087            SerdeValue::Seq(values) => values
2088                .into_iter()
2089                .map(Self::from_serde_value)
2090                .collect::<Result<Vec<_>>>()
2091                .map(Self::Array),
2092            SerdeValue::Map(values) => values
2093                .into_iter()
2094                .map(|(key, value)| {
2095                    let SerdeValue::String(key) = key else {
2096                        return Err(Error::Codec(
2097                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2098                        ));
2099                    };
2100
2101                    Ok((key, Self::from_serde_value(value)?))
2102                })
2103                .collect::<Result<BTreeMap<_, _>>>()
2104                .map(Self::Map),
2105        }
2106    }
2107
2108    fn finite_double(value: f64) -> Result<Self> {
2109        if !value.is_finite() {
2110            return Err(Error::Codec(
2111                "non_finite_float: Avro Value doubles must be finite".to_string(),
2112            ));
2113        }
2114
2115        Ok(Self::Double(value))
2116    }
2117
2118    fn into_json(self) -> Result<Value> {
2119        match self {
2120            Self::Null => Ok(Value::Null),
2121            Self::Boolean(value) => Ok(Value::Bool(value)),
2122            Self::Long(value) => Ok(Value::Number(value.into())),
2123            Self::Double(value) => serde_json::Number::from_f64(value)
2124                .map(Value::Number)
2125                .ok_or_else(|| {
2126                    Error::Codec(
2127                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2128                    )
2129                }),
2130            Self::Bytes(value) => Ok(json!({
2131                "$type": "bytes",
2132                "base64": BASE64.encode(value),
2133            })),
2134            Self::String(value) => Ok(Value::String(value)),
2135            Self::Array(values) => values
2136                .into_iter()
2137                .map(Self::into_json)
2138                .collect::<Result<Vec<_>>>()
2139                .map(Value::Array),
2140            Self::Map(values) => values
2141                .into_iter()
2142                .map(|(key, value)| Ok((key, value.into_json()?)))
2143                .collect::<Result<serde_json::Map<_, _>>>()
2144                .map(Value::Object),
2145        }
2146    }
2147
2148    fn into_serde_value(self) -> serde_value::Value {
2149        use serde_value::Value as SerdeValue;
2150
2151        match self {
2152            Self::Null => SerdeValue::Unit,
2153            Self::Boolean(value) => SerdeValue::Bool(value),
2154            Self::Long(value) => SerdeValue::I64(value),
2155            Self::Double(value) => SerdeValue::F64(value),
2156            Self::Bytes(value) => SerdeValue::Bytes(value),
2157            Self::String(value) => SerdeValue::String(value),
2158            Self::Array(values) => {
2159                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2160            }
2161            Self::Map(values) => SerdeValue::Map(
2162                values
2163                    .into_iter()
2164                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2165                    .collect(),
2166            ),
2167        }
2168    }
2169
2170    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2171        self.into_serde_value().deserialize_into().map_err(|error| {
2172            Error::Codec(format!(
2173                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2174            ))
2175        })
2176    }
2177}
2178
2179impl Serialize for AvroValue {
2180    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2181    where
2182        S: Serializer,
2183    {
2184        match self {
2185            Self::Null => serializer.serialize_unit(),
2186            Self::Boolean(value) => serializer.serialize_bool(*value),
2187            Self::Long(value) => serializer.serialize_i64(*value),
2188            Self::Double(value) => serializer.serialize_f64(*value),
2189            Self::Bytes(value) => serializer.serialize_bytes(value),
2190            Self::String(value) => serializer.serialize_str(value),
2191            Self::Array(values) => {
2192                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2193                for value in values {
2194                    sequence.serialize_element(value)?;
2195                }
2196                sequence.end()
2197            }
2198            Self::Map(values) => {
2199                let mut map = serializer.serialize_map(Some(values.len()))?;
2200                for (key, value) in values {
2201                    map.serialize_entry(key, value)?;
2202                }
2203                map.end()
2204            }
2205        }
2206    }
2207}
2208
2209pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2210    let datum = avro_value_to_datum(value)?;
2211    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2212        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2213    let mut bytes = Vec::with_capacity(datum.len() + 10);
2214    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2215    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2216    bytes.extend_from_slice(&datum);
2217    Ok(PayloadEnvelope {
2218        codec: DEFAULT_CODEC.to_string(),
2219        blob: BASE64.encode(bytes),
2220    })
2221}
2222
2223pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2224    if envelope.codec != DEFAULT_CODEC {
2225        return Err(unsupported_payload_codec(&envelope.codec));
2226    }
2227    decode_avro_value_blob(&envelope.blob)
2228}
2229
2230pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2231    let blob = match codec {
2232        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2233        other => return Err(unsupported_payload_codec(other)),
2234    };
2235
2236    Ok(PayloadEnvelope {
2237        codec: codec.to_string(),
2238        blob,
2239    })
2240}
2241
2242pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2243    match envelope.codec.as_str() {
2244        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2245        other => Err(unsupported_payload_codec(other)),
2246    }
2247}
2248
2249fn handler_type_error<T>(
2250    handler_kind: HandlerKind,
2251    handler_name: &str,
2252    value_kind: HandlerValueKind,
2253    message: impl Into<String>,
2254) -> Error {
2255    Error::HandlerType {
2256        handler_kind,
2257        handler_name: handler_name.to_string(),
2258        value_kind,
2259        rust_type: type_name::<T>(),
2260        message: message.into(),
2261    }
2262}
2263
2264fn decode_handler_input<T: DeserializeOwned>(
2265    arguments: AvroValue,
2266    handler_kind: HandlerKind,
2267    handler_name: &str,
2268) -> Result<T> {
2269    let argument = match arguments {
2270        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2271            arguments.pop().expect("one typed handler argument")
2272        }
2273        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2274        AvroValue::Array(arguments) => {
2275            return Err(handler_type_error::<T>(
2276                handler_kind,
2277                handler_name,
2278                HandlerValueKind::Input,
2279                format!(
2280                    "typed handlers accept one request value, but the task carried {} arguments",
2281                    arguments.len()
2282                ),
2283            ));
2284        }
2285        argument => argument,
2286    };
2287
2288    argument.deserialize().map_err(|error| {
2289        handler_type_error::<T>(
2290            handler_kind,
2291            handler_name,
2292            HandlerValueKind::Input,
2293            error.to_string(),
2294        )
2295    })
2296}
2297
2298fn encode_handler_result<T: Serialize>(
2299    result: &T,
2300    handler_kind: HandlerKind,
2301    handler_name: &str,
2302) -> Result<AvroValue> {
2303    AvroValue::from_serialize(result).map_err(|error| {
2304        handler_type_error::<T>(
2305            handler_kind,
2306            handler_name,
2307            HandlerValueKind::Result,
2308            error.to_string(),
2309        )
2310    })
2311}
2312
2313fn decode_handler_result<T: DeserializeOwned>(
2314    result: AvroValue,
2315    handler_kind: HandlerKind,
2316    handler_name: &str,
2317) -> Result<T> {
2318    result.deserialize().map_err(|error| {
2319        handler_type_error::<T>(
2320            handler_kind,
2321            handler_name,
2322            HandlerValueKind::Result,
2323            error.to_string(),
2324        )
2325    })
2326}
2327
2328#[cfg(test)]
2329fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2330    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2331}
2332
2333fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2334    validate_payload_codec(fallback_codec)?;
2335
2336    if value.is_null() {
2337        return Ok(Value::Null);
2338    }
2339
2340    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2341        return decode_blob(blob, codec);
2342    }
2343
2344    if let Some(blob) = value.as_str() {
2345        return decode_blob(blob, fallback_codec);
2346    }
2347
2348    Err(untagged_payload_value())
2349}
2350
2351fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2352    let envelope = match codec {
2353        DEFAULT_CODEC => encode_avro_value(value)?,
2354        other => return Err(unsupported_payload_codec(other)),
2355    };
2356    Ok(serde_json::to_value(envelope)?)
2357}
2358
2359fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2360    validate_payload_codec(fallback_codec)?;
2361
2362    if value.is_null() {
2363        return Ok(AvroValue::Null);
2364    }
2365
2366    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2367        validate_payload_codec(codec)?;
2368        return decode_avro_value_blob(blob);
2369    }
2370
2371    if let Some(blob) = value.as_str() {
2372        return match fallback_codec {
2373            DEFAULT_CODEC => decode_avro_value_blob(blob),
2374            other => Err(unsupported_payload_codec(other)),
2375        };
2376    }
2377
2378    Err(untagged_payload_value())
2379}
2380
2381fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2382    match value {
2383        AvroValue::Null => AvroValue::Array(Vec::new()),
2384        AvroValue::Array(_) => value,
2385        other => AvroValue::Array(vec![other]),
2386    }
2387}
2388
2389fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2390    match codec {
2391        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2392        other => Err(unsupported_payload_codec(other)),
2393    }
2394}
2395
2396fn validate_payload_codec(codec: &str) -> Result<()> {
2397    match codec {
2398        DEFAULT_CODEC => Ok(()),
2399        MISSING_TASK_PAYLOAD_CODEC => {
2400            Err(invalid_task_payload_codec("task payload_codec is missing"))
2401        }
2402        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2403        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2404            "task payload_codec must be a string",
2405        )),
2406        other => Err(unsupported_payload_codec(other)),
2407    }
2408}
2409
2410fn invalid_task_payload_codec(reason: &str) -> Error {
2411    Error::Codec(format!(
2412        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2413    ))
2414}
2415
2416fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2417    let Some(object) = value.as_object() else {
2418        return Ok(None);
2419    };
2420    if !object.contains_key("codec") && !object.contains_key("blob") {
2421        return Ok(None);
2422    }
2423
2424    let codec = object
2425        .get("codec")
2426        .and_then(Value::as_str)
2427        .ok_or_else(invalid_payload_envelope)?;
2428    validate_payload_codec(codec)?;
2429    let blob = object
2430        .get("blob")
2431        .and_then(Value::as_str)
2432        .ok_or_else(invalid_payload_envelope)?;
2433    Ok(Some((codec, blob)))
2434}
2435
2436fn invalid_payload_envelope() -> Error {
2437    Error::Codec(
2438        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2439            .to_string(),
2440    )
2441}
2442
2443fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2444    for command in commands {
2445        let Some(command) = command.as_object() else {
2446            continue;
2447        };
2448        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2449            continue;
2450        };
2451        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2452            continue;
2453        };
2454
2455        if let Some(codec) = command.get("payload_codec") {
2456            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2457            validate_payload_codec(codec)?;
2458        }
2459
2460        let payload = command
2461            .get(payload_field)
2462            .ok_or_else(invalid_payload_envelope)?;
2463        if runtime_payloads::Reference::parse(payload)?.is_none() {
2464            validate_outbound_payload_envelope(payload)?;
2465        }
2466    }
2467    Ok(())
2468}
2469
2470fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2471    if commands.iter().any(|command| {
2472        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2473            && command
2474                .get("condition_wait_occurrence_id")
2475                .and_then(Value::as_str)
2476                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2477    }) {
2478        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2479    } else if commands.iter().any(|command| {
2480        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2481            && command.get("attribute_types").is_some()
2482    }) {
2483        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2484    } else if commands
2485        .iter()
2486        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2487    {
2488        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2489    } else if commands
2490        .iter()
2491        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2492    {
2493        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2494    } else if commands.iter().any(|command| {
2495        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2496    }) {
2497        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2498    } else {
2499        MINIMUM_WORKER_PROTOCOL_VERSION
2500    }
2501}
2502
2503fn workflow_completion_protocol_version_with_message_streams(
2504    commands: &[Value],
2505    has_message_stream_metadata: bool,
2506) -> &'static str {
2507    let command_protocol = workflow_completion_protocol_version(commands);
2508    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2509        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2510    } else {
2511        command_protocol
2512    }
2513}
2514
2515fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2516    match command_type {
2517        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2518        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2519        "start_service_operation" => Some("request_payload"),
2520        "upsert_memo" => Some("entries"),
2521        _ => None,
2522    }
2523}
2524
2525fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2526    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2527        return Err(untagged_payload_value());
2528    };
2529    validate_payload_codec(codec)?;
2530    decode_avro_value_blob(blob)?;
2531    Ok(())
2532}
2533
2534fn unsupported_payload_codec(codec: &str) -> Error {
2535    Error::Codec(format!(
2536        "unsupported_payload_codec: workflow payload codec {codec:?} is not supported by Durable Workflow 2.0; use codec=\"avro\" with the fixed Avro Value schema and single-object framing. JSON remains the HTTP document transport, not a workflow payload codec"
2537    ))
2538}
2539
2540fn untagged_payload_value() -> Error {
2541    Error::Codec(
2542        "unsupported_payload_codec: untagged durable payload values are not supported by Durable Workflow 2.0; use codec=\"avro\" with the fixed Avro Value schema and single-object framing. JSON remains the HTTP document transport, not a workflow payload codec"
2543            .to_string(),
2544    )
2545}
2546
2547fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2548    let bytes = BASE64.decode(blob).map_err(|err| {
2549        Error::Codec(format!(
2550            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2551        ))
2552    })?;
2553
2554    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2555        return Err(unsupported_payload_codec("json"));
2556    }
2557
2558    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2559        return Err(Error::Codec(
2560            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2561        ));
2562    }
2563
2564    let fingerprint: [u8; 8] = bytes[2..10]
2565        .try_into()
2566        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2567    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2568        return Err(Error::Codec(format!(
2569            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2570            fingerprint
2571                .iter()
2572                .map(|byte| format!("{byte:02x}"))
2573                .collect::<String>()
2574        )));
2575    }
2576
2577    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2578    // The current fingerprint selects the current immutable schema, so reader
2579    // resolution would only re-walk the same recursive union. Future retained
2580    // writer fingerprints supply a distinct reader schema in this branch.
2581    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2582    if datum_reader.truncated {
2583        return Err(Error::Codec(
2584            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2585        ));
2586    }
2587    let datum = datum.map_err(|err| {
2588        Error::Codec(format!(
2589            "invalid_payload_framing: malformed Avro Value datum: {err}"
2590        ))
2591    })?;
2592    if datum_reader.remaining() != 0 {
2593        return Err(Error::Codec(format!(
2594            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2595            datum_reader.remaining()
2596        )));
2597    }
2598    avro_value_from_datum(datum)
2599}
2600
2601struct StrictAvroDatumReader<'a> {
2602    bytes: &'a [u8],
2603    offset: usize,
2604    truncated: bool,
2605}
2606
2607impl<'a> StrictAvroDatumReader<'a> {
2608    fn new(bytes: &'a [u8]) -> Self {
2609        Self {
2610            bytes,
2611            offset: 0,
2612            truncated: false,
2613        }
2614    }
2615
2616    fn remaining(&self) -> usize {
2617        self.bytes.len() - self.offset
2618    }
2619}
2620
2621impl Read for StrictAvroDatumReader<'_> {
2622    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2623        let count = buffer.len().min(self.remaining());
2624        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2625        self.offset += count;
2626        if count < buffer.len() {
2627            self.truncated = true;
2628        }
2629
2630        Ok(count)
2631    }
2632}
2633
2634fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2635    let branch = match value {
2636        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2637        AvroValue::Boolean(value) => AvroDatum::Union(
2638            1,
2639            Box::new(AvroDatum::Record(vec![(
2640                "boolean".to_string(),
2641                AvroDatum::Boolean(*value),
2642            )])),
2643        ),
2644        AvroValue::Long(value) => AvroDatum::Union(
2645            2,
2646            Box::new(AvroDatum::Record(vec![(
2647                "long".to_string(),
2648                AvroDatum::Long(*value),
2649            )])),
2650        ),
2651        AvroValue::Double(value) => {
2652            if !value.is_finite() {
2653                return Err(Error::Codec(
2654                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2655                ));
2656            }
2657            AvroDatum::Union(
2658                3,
2659                Box::new(AvroDatum::Record(vec![(
2660                    "double".to_string(),
2661                    AvroDatum::Double(*value),
2662                )])),
2663            )
2664        }
2665        AvroValue::Bytes(value) => AvroDatum::Union(
2666            4,
2667            Box::new(AvroDatum::Record(vec![(
2668                "bytes".to_string(),
2669                AvroDatum::Bytes(value.clone()),
2670            )])),
2671        ),
2672        AvroValue::String(value) => AvroDatum::Union(
2673            5,
2674            Box::new(AvroDatum::Record(vec![(
2675                "string".to_string(),
2676                AvroDatum::String(value.clone()),
2677            )])),
2678        ),
2679        AvroValue::Array(values) => AvroDatum::Union(
2680            6,
2681            Box::new(AvroDatum::Record(vec![(
2682                "items".to_string(),
2683                AvroDatum::Array(
2684                    values
2685                        .iter()
2686                        .map(avro_value_to_datum)
2687                        .collect::<Result<Vec<_>>>()?,
2688                ),
2689            )])),
2690        ),
2691        AvroValue::Map(values) => AvroDatum::Union(
2692            7,
2693            Box::new(AvroDatum::Record(vec![(
2694                "entries".to_string(),
2695                AvroDatum::Array(
2696                    values
2697                        .iter()
2698                        .map(|(key, value)| {
2699                            Ok(AvroDatum::Record(vec![
2700                                ("key".to_string(), AvroDatum::String(key.clone())),
2701                                ("value".to_string(), avro_value_to_datum(value)?),
2702                            ]))
2703                        })
2704                        .collect::<Result<Vec<_>>>()?,
2705                ),
2706            )])),
2707        ),
2708    };
2709    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2710}
2711
2712fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2713    let AvroDatum::Record(mut outer) = datum else {
2714        return Err(Error::Codec(
2715            "invalid_payload_framing: datum is not a Value record".to_string(),
2716        ));
2717    };
2718    let (_, branch) = outer
2719        .pop()
2720        .filter(|(name, _)| name == "value")
2721        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2722    let AvroDatum::Union(_, branch) = branch else {
2723        return Err(Error::Codec(
2724            "invalid_payload_framing: invalid Value union".to_string(),
2725        ));
2726    };
2727    match *branch {
2728        AvroDatum::Null => Ok(AvroValue::Null),
2729        AvroDatum::Record(mut fields) => {
2730            let (name, value) = fields.pop().ok_or_else(|| {
2731                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2732            })?;
2733            match (name.as_str(), value) {
2734                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2735                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2736                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2737                    Ok(AvroValue::Double(value))
2738                }
2739                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2740                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2741                ("items", AvroDatum::Array(values)) => values
2742                    .into_iter()
2743                    .map(avro_value_from_datum)
2744                    .collect::<Result<Vec<_>>>()
2745                    .map(AvroValue::Array),
2746                ("entries", AvroDatum::Map(values)) => values
2747                    .into_iter()
2748                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2749                    .collect::<Result<BTreeMap<_, _>>>()
2750                    .map(AvroValue::Map),
2751                _ => Err(Error::Codec(
2752                    "invalid_payload_framing: unknown Value branch".to_string(),
2753                )),
2754            }
2755        }
2756        _ => Err(Error::Codec(
2757            "invalid_payload_framing: invalid Value branch".to_string(),
2758        )),
2759    }
2760}
2761
2762fn avro_value_schema() -> Result<&'static Schema> {
2763    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2764        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2765            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2766    }) {
2767        Ok(schema) => Ok(schema),
2768        Err(message) => Err(Error::Codec(message.clone())),
2769    }
2770}
2771
2772fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2773    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2774        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2775        // have the same block representation when each ordered array record
2776        // contains the map key followed by its value, so this encoding-only
2777        // adaptation lets the official encoder retain BTreeMap wire order.
2778        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2779            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2780        let entries_schema = schema
2781            .pointer_mut("/fields/0/type/7/fields/0/type")
2782            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2783        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2784            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2785        }
2786        *entries_schema = json!({
2787            "type": "array",
2788            "items": {
2789                "type": "record",
2790                "name": "MapEntry",
2791                "fields": [
2792                    {"name": "key", "type": "string"},
2793                    {"name": "value", "type": "Value"}
2794                ]
2795            }
2796        });
2797        Schema::parse_str(&schema.to_string())
2798            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2799    }) {
2800        Ok(schema) => Ok(schema),
2801        Err(message) => Err(Error::Codec(message.clone())),
2802    }
2803}
2804
2805#[derive(Clone, Debug)]
2806pub struct Client {
2807    http: reqwest::Client,
2808    hydration_timeout: Duration,
2809    base_url: String,
2810    token: Option<String>,
2811    control_token: Option<String>,
2812    worker_token: Option<String>,
2813    namespace: String,
2814    max_external_payload_bytes: usize,
2815    worker_storage_admission: Option<WorkerStorageAdmission>,
2816    cooperative_worker_protocol: bool,
2817    worker_protocol_version: WorkerProtocolVersion,
2818    local_activities_enabled: bool,
2819    worker_sessions_enabled: bool,
2820    max_concurrent_worker_sessions: usize,
2821    worker_build_id: Option<String>,
2822    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2823    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2824}
2825
2826impl Client {
2827    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2828        Self::builder(base_url).build()
2829    }
2830
2831    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2832        ClientBuilder {
2833            base_url: base_url.into(),
2834            token: None,
2835            control_token: None,
2836            worker_token: None,
2837            namespace: "default".to_string(),
2838            timeout: Duration::from_secs(60),
2839            max_external_payload_bytes: 64 * 1024 * 1024,
2840            worker_protocol_version: WorkerProtocolVersion::default(),
2841        }
2842    }
2843
2844    pub async fn health(&self) -> Result<Value> {
2845        self.request_json(
2846            reqwest::Method::GET,
2847            "/health",
2848            RequestProtocol::ControlPlane,
2849            Option::<&Value>::None,
2850        )
2851        .await
2852    }
2853
2854    pub async fn cluster_info(&self) -> Result<Value> {
2855        self.request_json(
2856            reqwest::Method::GET,
2857            "/cluster/info",
2858            RequestProtocol::ControlPlane,
2859            Option::<&Value>::None,
2860        )
2861        .await
2862    }
2863
2864    pub async fn start_workflow<T: Serialize>(
2865        &self,
2866        workflow_type: &str,
2867        task_queue: &str,
2868        workflow_id: &str,
2869        input: T,
2870    ) -> Result<WorkflowHandle> {
2871        self.start_workflow_with_options(
2872            workflow_type,
2873            task_queue,
2874            workflow_id,
2875            WorkflowStartOptions::default(),
2876            input,
2877        )
2878        .await
2879    }
2880
2881    /// Start a workflow with explicit server-enforced execution and run
2882    /// deadlines.
2883    pub async fn start_workflow_with_options<T: Serialize>(
2884        &self,
2885        workflow_type: &str,
2886        task_queue: &str,
2887        workflow_id: &str,
2888        options: WorkflowStartOptions,
2889        input: T,
2890    ) -> Result<WorkflowHandle> {
2891        options.validate()?;
2892        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2893        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2894        let body = json!({
2895            "workflow_id": workflow_id,
2896            "workflow_type": workflow_type,
2897            "task_queue": task_queue,
2898            "input": input_envelope,
2899            "execution_timeout_seconds": options.execution_timeout_seconds,
2900            "run_timeout_seconds": options.run_timeout_seconds
2901        });
2902
2903        let data: Value = self
2904            .request_json(
2905                reqwest::Method::POST,
2906                "/workflows",
2907                RequestProtocol::ControlPlane,
2908                Some(&body),
2909            )
2910            .await?;
2911
2912        Ok(WorkflowHandle {
2913            client: self.clone(),
2914            workflow_id: data
2915                .get("workflow_id")
2916                .and_then(Value::as_str)
2917                .unwrap_or(workflow_id)
2918                .to_string(),
2919            run_id: data
2920                .get("run_id")
2921                .and_then(Value::as_str)
2922                .map(str::to_string),
2923            workflow_type: data
2924                .get("workflow_type")
2925                .and_then(Value::as_str)
2926                .unwrap_or(workflow_type)
2927                .to_string(),
2928        })
2929    }
2930
2931    pub async fn signal_workflow<T: Serialize>(
2932        &self,
2933        workflow_id: &str,
2934        signal_name: &str,
2935        input: T,
2936    ) -> Result<Value> {
2937        self.signal_workflow_target(workflow_id, None, signal_name, input)
2938            .await
2939    }
2940
2941    /// Append one idempotently identified item to an instance-scoped input stream.
2942    pub async fn append_message_stream<T: Serialize>(
2943        &self,
2944        workflow_id: &str,
2945        stream_name: &str,
2946        message_id: &str,
2947        input: T,
2948    ) -> Result<Value> {
2949        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2950        let body = json!({
2951            "message_id": message_id,
2952            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2953        });
2954        self.request_json(
2955            reqwest::Method::POST,
2956            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2957            RequestProtocol::ControlPlane,
2958            Some(&body),
2959        )
2960        .await
2961    }
2962
2963    /// Signal only if `run_id` is still the current run for this instance.
2964    pub async fn signal_workflow_run<T: Serialize>(
2965        &self,
2966        workflow_id: &str,
2967        run_id: &str,
2968        signal_name: &str,
2969        input: T,
2970    ) -> Result<Value> {
2971        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2972            .await
2973    }
2974
2975    async fn signal_workflow_target<T: Serialize>(
2976        &self,
2977        workflow_id: &str,
2978        run_id: Option<&str>,
2979        signal_name: &str,
2980        input: T,
2981    ) -> Result<Value> {
2982        validate_user_signal_name(signal_name)?;
2983        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2984        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2985        let body = json!({
2986            "input": input_envelope
2987        });
2988        let path = match run_id {
2989            Some(run_id) => {
2990                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2991            }
2992            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2993        };
2994        self.request_json(
2995            reqwest::Method::POST,
2996            &path,
2997            RequestProtocol::ControlPlane,
2998            Some(&body),
2999        )
3000        .await
3001    }
3002
3003    /// Close the current run as cancelled immediately.
3004    ///
3005    /// Server revokes open tasks and timers without resuming workflow code for
3006    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3007    /// request on a supporting runtime and opted-in worker.
3008    pub async fn cancel_workflow(
3009        &self,
3010        workflow_id: &str,
3011        options: WorkflowCommandOptions,
3012    ) -> Result<WorkflowCommandResult> {
3013        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3014            .await
3015    }
3016
3017    /// Close the selected run as cancelled, only if `run_id` is still current.
3018    pub async fn cancel_workflow_run(
3019        &self,
3020        workflow_id: &str,
3021        run_id: &str,
3022        options: WorkflowCommandOptions,
3023    ) -> Result<WorkflowCommandResult> {
3024        self.workflow_command(
3025            workflow_id,
3026            Some(run_id),
3027            WorkflowCommandKind::Cancel,
3028            options,
3029        )
3030        .await
3031    }
3032
3033    /// Forcefully terminate the current run for an instance.
3034    pub async fn terminate_workflow(
3035        &self,
3036        workflow_id: &str,
3037        options: WorkflowCommandOptions,
3038    ) -> Result<WorkflowCommandResult> {
3039        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3040            .await
3041    }
3042
3043    /// Forcefully terminate only if `run_id` is still current.
3044    pub async fn terminate_workflow_run(
3045        &self,
3046        workflow_id: &str,
3047        run_id: &str,
3048        options: WorkflowCommandOptions,
3049    ) -> Result<WorkflowCommandResult> {
3050        self.workflow_command(
3051            workflow_id,
3052            Some(run_id),
3053            WorkflowCommandKind::Terminate,
3054            options,
3055        )
3056        .await
3057    }
3058
3059    /// Continue a failed run from its recorded activity failure boundary.
3060    pub async fn redrive_workflow_run(
3061        &self,
3062        workflow_id: &str,
3063        failed_run_id: &str,
3064        request_id: Option<&str>,
3065    ) -> Result<WorkflowRedriveResult> {
3066        let body = request_id
3067            .map(|id| json!({"request_id": id}))
3068            .unwrap_or_else(|| json!({}));
3069        let data: Value = self
3070            .request_json(
3071                reqwest::Method::POST,
3072                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3073                RequestProtocol::ControlPlane,
3074                Some(&body),
3075            )
3076            .await?;
3077        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3078            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3079        {
3080            return Err(Error::Codec(
3081                "redrive response was not accepted".to_string(),
3082            ));
3083        }
3084        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3085            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3086        {
3087            return Err(Error::Codec(
3088                "redrive response does not match the requested source run".to_string(),
3089            ));
3090        }
3091        let run_id = data
3092            .get("run_id")
3093            .and_then(Value::as_str)
3094            .filter(|id| !id.is_empty() && *id != failed_run_id)
3095            .ok_or_else(|| {
3096                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3097            })?;
3098        let resume_step_sequence = data
3099            .get("resume_step_sequence")
3100            .and_then(Value::as_u64)
3101            .filter(|sequence| *sequence > 0)
3102            .ok_or_else(|| {
3103                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3104            })?;
3105        Ok(WorkflowRedriveResult {
3106            workflow_id: workflow_id.to_string(),
3107            source_run_id: failed_run_id.to_string(),
3108            run_id: run_id.to_string(),
3109            resume_step_sequence,
3110            raw: data,
3111        })
3112    }
3113
3114    async fn workflow_command(
3115        &self,
3116        workflow_id: &str,
3117        run_id: Option<&str>,
3118        command: WorkflowCommandKind,
3119        options: WorkflowCommandOptions,
3120    ) -> Result<WorkflowCommandResult> {
3121        let path = match run_id {
3122            Some(run_id) => format!(
3123                "/workflows/{workflow_id}/runs/{run_id}/{}",
3124                command.as_str()
3125            ),
3126            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3127        };
3128        let data = match self
3129            .request_json(
3130                reqwest::Method::POST,
3131                &path,
3132                RequestProtocol::ControlPlane,
3133                Some(&options),
3134            )
3135            .await
3136        {
3137            Ok(data) => data,
3138            Err(Error::Http { status, body }) => {
3139                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3140                    command,
3141                    status,
3142                    body,
3143                    workflow_id,
3144                    run_id,
3145                )));
3146            }
3147            Err(error) => return Err(error),
3148        };
3149
3150        Ok(workflow_command_result(command, data, workflow_id, run_id))
3151    }
3152
3153    /// Execute a named, read-only query against a running or completed workflow.
3154    ///
3155    /// Arguments and results use the platform payload envelope. Server and
3156    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3157    /// reason, HTTP status, and original response body.
3158    pub async fn query_workflow<T: Serialize>(
3159        &self,
3160        workflow_id: &str,
3161        query_name: &str,
3162        input: T,
3163    ) -> Result<Value> {
3164        self.query_workflow_target(workflow_id, None, query_name, input)
3165            .await
3166    }
3167
3168    /// Query only if `run_id` is still current, preventing accidental retargeting.
3169    pub async fn query_workflow_run<T: Serialize>(
3170        &self,
3171        workflow_id: &str,
3172        run_id: &str,
3173        query_name: &str,
3174        input: T,
3175    ) -> Result<Value> {
3176        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3177            .await
3178    }
3179
3180    /// Query a workflow and return the lossless fixed Avro Value result.
3181    pub async fn query_workflow_avro_value<T: Serialize>(
3182        &self,
3183        workflow_id: &str,
3184        query_name: &str,
3185        input: T,
3186    ) -> Result<AvroValue> {
3187        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3188            .await
3189    }
3190
3191    /// Query a selected run and return the lossless fixed Avro Value result.
3192    pub async fn query_workflow_run_avro_value<T: Serialize>(
3193        &self,
3194        workflow_id: &str,
3195        run_id: &str,
3196        query_name: &str,
3197        input: T,
3198    ) -> Result<AvroValue> {
3199        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3200            .await
3201    }
3202
3203    async fn query_workflow_avro_value_target<T: Serialize>(
3204        &self,
3205        workflow_id: &str,
3206        run_id: Option<&str>,
3207        query_name: &str,
3208        input: T,
3209    ) -> Result<AvroValue> {
3210        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3211        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3212        let path = match run_id {
3213            Some(run_id) => {
3214                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3215            }
3216            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3217        };
3218        let response: Value = match self
3219            .request_json(
3220                reqwest::Method::POST,
3221                &path,
3222                RequestProtocol::ControlPlane,
3223                Some(&body),
3224            )
3225            .await
3226        {
3227            Ok(response) => response,
3228            Err(Error::Http { status, body }) => {
3229                return Err(Error::QueryFailed(query_failure(status, body)));
3230            }
3231            Err(error) => return Err(error),
3232        };
3233
3234        let envelope = response
3235            .get("result_envelope")
3236            .filter(|envelope| !envelope.is_null())
3237            .ok_or_else(|| {
3238                Error::Codec(
3239                    "missing_payload_envelope: typed query result requires result_envelope"
3240                        .to_string(),
3241                )
3242            })?;
3243        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3244    }
3245
3246    async fn query_workflow_target<T: Serialize>(
3247        &self,
3248        workflow_id: &str,
3249        run_id: Option<&str>,
3250        query_name: &str,
3251        input: T,
3252    ) -> Result<Value> {
3253        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3254        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3255        let body = json!({
3256            "input": input_envelope
3257        });
3258        let path = match run_id {
3259            Some(run_id) => {
3260                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3261            }
3262            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3263        };
3264        let response: Value = match self
3265            .request_json(
3266                reqwest::Method::POST,
3267                &path,
3268                RequestProtocol::ControlPlane,
3269                Some(&body),
3270            )
3271            .await
3272        {
3273            Ok(response) => response,
3274            Err(Error::Http { status, body }) => {
3275                return Err(Error::QueryFailed(query_failure(status, body)));
3276            }
3277            Err(error) => return Err(error),
3278        };
3279
3280        if let Some(envelope) = response
3281            .get("result_envelope")
3282            .filter(|envelope| !envelope.is_null())
3283        {
3284            return decode_wire_value(envelope, DEFAULT_CODEC);
3285        }
3286
3287        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3288    }
3289
3290    /// Send a synchronous update using fixed Avro Value arguments.
3291    pub async fn update_workflow<T: Serialize>(
3292        &self,
3293        workflow_id: &str,
3294        update_name: &str,
3295        input: T,
3296        request_id: Option<&str>,
3297    ) -> Result<Value> {
3298        let response = self
3299            .update_workflow_response(workflow_id, update_name, input, request_id)
3300            .await?;
3301        if let Some(envelope) = response
3302            .get("result_envelope")
3303            .filter(|envelope| !envelope.is_null())
3304        {
3305            return decode_wire_value(envelope, DEFAULT_CODEC);
3306        }
3307        Ok(response.get("result").cloned().unwrap_or(response))
3308    }
3309
3310    /// Send a synchronous update and retain a bytes-capable Avro result.
3311    pub async fn update_workflow_avro_value<T: Serialize>(
3312        &self,
3313        workflow_id: &str,
3314        update_name: &str,
3315        input: T,
3316        request_id: Option<&str>,
3317    ) -> Result<AvroValue> {
3318        let response = self
3319            .update_workflow_response(workflow_id, update_name, input, request_id)
3320            .await?;
3321        let envelope = response
3322            .get("result_envelope")
3323            .filter(|envelope| !envelope.is_null())
3324            .ok_or_else(|| {
3325                Error::Codec(
3326                    "missing_payload_envelope: typed update result requires result_envelope"
3327                        .to_string(),
3328                )
3329            })?;
3330        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3331    }
3332
3333    async fn update_workflow_response<T: Serialize>(
3334        &self,
3335        workflow_id: &str,
3336        update_name: &str,
3337        input: T,
3338        request_id: Option<&str>,
3339    ) -> Result<Value> {
3340        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3341        let mut body = json!({
3342            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3343            "wait_for": "completed",
3344        });
3345        if let Some(request_id) = request_id {
3346            body["request_id"] = json!(request_id);
3347        }
3348        self.request_json(
3349            reqwest::Method::POST,
3350            &format!("/workflows/{workflow_id}/update/{update_name}"),
3351            RequestProtocol::ControlPlane,
3352            Some(&body),
3353        )
3354        .await
3355    }
3356
3357    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3358        let path = format!("/workflows/{workflow_id}");
3359        let mut data: WorkflowDescription = self
3360            .request_json(
3361                reqwest::Method::GET,
3362                &path,
3363                RequestProtocol::ControlPlane,
3364                Option::<&Value>::None,
3365            )
3366            .await?;
3367        data.decode_payloads()?;
3368        Ok(data)
3369    }
3370
3371    /// Describe one selected run, including historical terminal runs.
3372    pub async fn describe_workflow_run(
3373        &self,
3374        workflow_id: &str,
3375        run_id: &str,
3376    ) -> Result<WorkflowDescription> {
3377        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3378        let mut data: WorkflowDescription = self
3379            .request_json(
3380                reqwest::Method::GET,
3381                &path,
3382                RequestProtocol::ControlPlane,
3383                Option::<&Value>::None,
3384            )
3385            .await?;
3386        data.decode_payloads()?;
3387        Ok(data)
3388    }
3389
3390    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3391        let mut path = format!(
3392            "/workflows/{}/runs/{}/streams",
3393            percent_encode_path_segment(workflow_id),
3394            percent_encode_path_segment(run_id),
3395        );
3396        if let Some(stream_name) = stream_name {
3397            path.push('/');
3398            path.push_str(&percent_encode_path_segment(stream_name));
3399        }
3400        path
3401    }
3402
3403    /// List the run-scoped output streams already opened by a workflow.
3404    pub async fn list_workflow_streams(
3405        &self,
3406        workflow_id: &str,
3407        run_id: &str,
3408    ) -> Result<Vec<WorkflowStreamDescription>> {
3409        let response: WorkflowStreamListResponse = self
3410            .request_json(
3411                reqwest::Method::GET,
3412                &Self::workflow_stream_path(workflow_id, run_id, None),
3413                RequestProtocol::ControlPlane,
3414                Option::<&Value>::None,
3415            )
3416            .await?;
3417        Ok(response.streams)
3418    }
3419
3420    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3421    pub async fn describe_workflow_stream(
3422        &self,
3423        workflow_id: &str,
3424        run_id: &str,
3425        stream_name: &str,
3426    ) -> Result<WorkflowStreamDescription> {
3427        let response: WorkflowStreamDescriptionResponse = self
3428            .request_json(
3429                reqwest::Method::GET,
3430                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3431                RequestProtocol::ControlPlane,
3432                Option::<&Value>::None,
3433            )
3434            .await?;
3435        Ok(response.stream)
3436    }
3437
3438    /// Read one bounded page beginning at a zero-based offset.
3439    ///
3440    /// Delivery is at least once: persist `next_offset` only after processing
3441    /// the page. The future is cancellation-safe; dropping it cancels the
3442    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3443    /// service contract.
3444    pub async fn subscribe_workflow_stream(
3445        &self,
3446        workflow_id: &str,
3447        run_id: &str,
3448        stream_name: &str,
3449        from_offset: u64,
3450        max_items: usize,
3451        wait: Duration,
3452    ) -> Result<WorkflowStreamPage> {
3453        let max_items = max_items.clamp(1, 500);
3454        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3455        let path = format!(
3456            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3457            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3458        );
3459        let response: WorkflowStreamPageResponse = self
3460            .request_json_with_timeout(
3461                reqwest::Method::GET,
3462                &path,
3463                RequestProtocol::ControlPlane,
3464                Option::<&Value>::None,
3465                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3466            )
3467            .await?;
3468
3469        let items = response
3470            .items
3471            .into_iter()
3472            .map(|raw| {
3473                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3474                let envelope = raw.get("payload").cloned();
3475                let payload = envelope
3476                    .as_ref()
3477                    .filter(|value| value.get("blob").is_some())
3478                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3479                    .transpose()?
3480                    .map(AvroValue::into_json)
3481                    .transpose()?;
3482                Ok(WorkflowStreamItem {
3483                    offset,
3484                    payload,
3485                    payload_envelope: envelope,
3486                    payload_reference: raw
3487                        .get("payload_reference")
3488                        .and_then(Value::as_str)
3489                        .map(str::to_string),
3490                    payload_codec: raw
3491                        .get("payload_codec")
3492                        .and_then(Value::as_str)
3493                        .map(str::to_string),
3494                    idempotency_key: raw
3495                        .get("idempotency_key")
3496                        .and_then(Value::as_str)
3497                        .map(str::to_string),
3498                    item_type: raw
3499                        .get("item_type")
3500                        .and_then(Value::as_str)
3501                        .map(str::to_string),
3502                    content_type: raw
3503                        .get("content_type")
3504                        .and_then(Value::as_str)
3505                        .map(str::to_string),
3506                    origin: raw
3507                        .get("origin")
3508                        .and_then(Value::as_str)
3509                        .map(str::to_string),
3510                    origin_reference: raw
3511                        .get("origin_reference")
3512                        .and_then(Value::as_str)
3513                        .map(str::to_string),
3514                    emitted_at: raw
3515                        .get("emitted_at")
3516                        .and_then(Value::as_str)
3517                        .map(str::to_string),
3518                    raw,
3519                })
3520            })
3521            .collect::<Result<Vec<_>>>()?;
3522        Ok(WorkflowStreamPage {
3523            stream: response.stream,
3524            items,
3525            next_offset: response.next_offset,
3526            terminal: response.terminal,
3527        })
3528    }
3529
3530    /// Append inline Avro envelopes or opaque external payload references.
3531    pub async fn append_workflow_stream(
3532        &self,
3533        workflow_id: &str,
3534        run_id: &str,
3535        stream_name: &str,
3536        items: &[WorkflowStreamAppendItem],
3537        max_pending_items: Option<u64>,
3538    ) -> Result<WorkflowStreamAppendResult> {
3539        if items.is_empty() {
3540            return Err(Error::Codec(
3541                "workflow_stream_items_empty: append requires at least one item".to_string(),
3542            ));
3543        }
3544        let mut body = json!({
3545            "items": items
3546                .iter()
3547                .map(|item| item.wire_value(None))
3548                .collect::<Vec<_>>(),
3549        });
3550        if let Some(max_pending_items) = max_pending_items {
3551            if max_pending_items == 0 {
3552                return Err(Error::Codec(
3553                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3554                        .to_string(),
3555                ));
3556            }
3557            body["max_pending_items"] = json!(max_pending_items);
3558        }
3559        let response: WorkflowStreamAppendResponse = self
3560            .request_json(
3561                reqwest::Method::POST,
3562                &format!(
3563                    "{}/items",
3564                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3565                ),
3566                RequestProtocol::ControlPlane,
3567                Some(&body),
3568            )
3569            .await?;
3570        Ok(WorkflowStreamAppendResult {
3571            stream: response.stream,
3572            accepted_offsets: response.accepted_offsets,
3573            accepted: response.accepted,
3574            deduped: response.deduped,
3575        })
3576    }
3577
3578    /// Close a stream, or mark it errored when `error_reason` is supplied.
3579    pub async fn close_workflow_stream(
3580        &self,
3581        workflow_id: &str,
3582        run_id: &str,
3583        stream_name: &str,
3584        error_reason: Option<&str>,
3585        retention_seconds: Option<u64>,
3586    ) -> Result<WorkflowStreamDescription> {
3587        let mut body = json!({});
3588        if let Some(error_reason) = error_reason {
3589            body["error_reason"] = json!(error_reason);
3590        }
3591        if let Some(retention_seconds) = retention_seconds {
3592            if retention_seconds == 0 {
3593                return Err(Error::Codec(
3594                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3595                        .to_string(),
3596                ));
3597            }
3598            body["retention_seconds"] = json!(retention_seconds);
3599        }
3600        let response: WorkflowStreamDescriptionResponse = self
3601            .request_json(
3602                reqwest::Method::POST,
3603                &format!(
3604                    "{}/close",
3605                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3606                ),
3607                RequestProtocol::ControlPlane,
3608                Some(&body),
3609            )
3610            .await?;
3611        Ok(response.stream)
3612    }
3613
3614    pub async fn register_worker(
3615        &self,
3616        worker_id: &str,
3617        task_queue: &str,
3618        supported_workflow_types: Vec<String>,
3619        supported_activity_types: Vec<String>,
3620        max_concurrent_workflow_tasks: usize,
3621        max_concurrent_activity_tasks: usize,
3622    ) -> Result<RegisterWorkerResponse> {
3623        self.register_worker_with_capabilities(
3624            worker_id,
3625            task_queue,
3626            supported_workflow_types,
3627            supported_activity_types,
3628            max_concurrent_workflow_tasks,
3629            max_concurrent_activity_tasks,
3630            Vec::new(),
3631        )
3632        .await
3633    }
3634
3635    /// Register a worker and explicitly advertise additive worker capabilities.
3636    pub async fn register_worker_with_capabilities(
3637        &self,
3638        worker_id: &str,
3639        task_queue: &str,
3640        supported_workflow_types: Vec<String>,
3641        supported_activity_types: Vec<String>,
3642        max_concurrent_workflow_tasks: usize,
3643        max_concurrent_activity_tasks: usize,
3644        capabilities: Vec<String>,
3645    ) -> Result<RegisterWorkerResponse> {
3646        self.register_worker_with_command_contracts(
3647            worker_id,
3648            task_queue,
3649            supported_workflow_types,
3650            supported_activity_types,
3651            max_concurrent_workflow_tasks,
3652            max_concurrent_activity_tasks,
3653            capabilities,
3654            Value::Object(serde_json::Map::new()),
3655        )
3656        .await
3657    }
3658
3659    /// Register a worker and advertise its named query and update handlers.
3660    ///
3661    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3662    /// so a workflow contract with a non-empty or malformed
3663    /// `update_validators` declaration returns
3664    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3665    #[allow(clippy::too_many_arguments)]
3666    pub async fn register_worker_with_command_contracts(
3667        &self,
3668        worker_id: &str,
3669        task_queue: &str,
3670        supported_workflow_types: Vec<String>,
3671        supported_activity_types: Vec<String>,
3672        max_concurrent_workflow_tasks: usize,
3673        max_concurrent_activity_tasks: usize,
3674        capabilities: Vec<String>,
3675        workflow_command_contracts: Value,
3676    ) -> Result<RegisterWorkerResponse> {
3677        self.register_worker_with_definition_fingerprints(
3678            worker_id,
3679            task_queue,
3680            supported_workflow_types,
3681            supported_activity_types,
3682            max_concurrent_workflow_tasks,
3683            max_concurrent_activity_tasks,
3684            capabilities,
3685            workflow_command_contracts,
3686            None,
3687        )
3688        .await
3689    }
3690
3691    #[allow(clippy::too_many_arguments)]
3692    async fn register_worker_with_definition_fingerprints(
3693        &self,
3694        worker_id: &str,
3695        task_queue: &str,
3696        supported_workflow_types: Vec<String>,
3697        supported_activity_types: Vec<String>,
3698        max_concurrent_workflow_tasks: usize,
3699        max_concurrent_activity_tasks: usize,
3700        capabilities: Vec<String>,
3701        workflow_command_contracts: Value,
3702        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3703    ) -> Result<RegisterWorkerResponse> {
3704        if let Some(contracts) = workflow_command_contracts.as_object() {
3705            for (workflow_type, contract) in contracts {
3706                let Some(update_validators) = contract.get("update_validators") else {
3707                    continue;
3708                };
3709                if !update_validators
3710                    .as_array()
3711                    .is_some_and(|validators| validators.is_empty())
3712                {
3713                    return Err(Error::UnsupportedUpdateValidators {
3714                        workflow_type: workflow_type.clone(),
3715                    });
3716                }
3717            }
3718        }
3719
3720        let mut body = json!({
3721            "worker_id": worker_id,
3722            "task_queue": task_queue,
3723            "runtime": "rust",
3724            "sdk_version": SDK_VERSION,
3725            "supported_workflow_types": supported_workflow_types,
3726            "supported_activity_types": supported_activity_types,
3727            "capabilities": capabilities,
3728            "capability_manifest": portable_worker_affinity_capability_manifest(),
3729            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3730            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3731        });
3732        if let Some(build_id) = &self.worker_build_id {
3733            if build_id.is_empty() || build_id.len() > 255 {
3734                return Err(Error::WorkerLoop(
3735                    "worker build ID must contain 1 to 255 bytes".into(),
3736                ));
3737            }
3738            body["build_id"] = json!(build_id);
3739        }
3740        if self.sticky_cache.is_some() {
3741            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3742                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3743                "implementation":"bounded_durable_history_cache"});
3744        }
3745        if self.local_activities_enabled {
3746            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3747                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3748        }
3749        if self.worker_sessions_enabled {
3750            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3751                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3752            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3753        }
3754        if workflow_command_contracts
3755            .as_object()
3756            .is_some_and(|contracts| !contracts.is_empty())
3757        {
3758            body["workflow_command_contracts"] = workflow_command_contracts;
3759        }
3760        if let Some(fingerprints) = workflow_definition_fingerprints {
3761            body["workflow_definition_fingerprints"] = json!(fingerprints);
3762        }
3763
3764        let response: Value = self
3765            .request_json(
3766                reqwest::Method::POST,
3767                "/worker/register",
3768                RequestProtocol::DefaultWorker,
3769                Some(&body),
3770            )
3771            .await?;
3772        if self.sticky_cache.is_some() {
3773            self.confirm_sticky_registration(&response, worker_id, task_queue)
3774                .await?;
3775        }
3776        if self.local_activities_enabled || self.worker_sessions_enabled {
3777            let compatible = response["registered"].as_bool() == Some(true)
3778                && response["worker_id"].as_str() == Some(worker_id)
3779                && response["namespace"].as_str() == Some(self.namespace.as_str())
3780                && response["task_queue"].as_str() == Some(task_queue)
3781                && response["protocol_version"]
3782                    .as_str()
3783                    .and_then(|version| version.strip_prefix("1."))
3784                    .and_then(|minor| minor.parse::<u64>().ok())
3785                    .is_some_and(|minor| minor >= 18)
3786                && (!self.local_activities_enabled
3787                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3788                        == Some(true))
3789                && (!self.worker_sessions_enabled
3790                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3791                        == Some(true)
3792                        && response["capabilities"].as_array().is_some_and(|accepted| {
3793                            capabilities.iter().all(|capability| {
3794                                accepted
3795                                    .iter()
3796                                    .any(|value| value.as_str() == Some(capability.as_str()))
3797                            })
3798                        })));
3799            if !compatible {
3800                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3801                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3802                } else {
3803                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3804                });
3805                if response["registered"] == true
3806                    && response["worker_id"].as_str() == Some(worker_id)
3807                {
3808                    if let Err(deregistration) =
3809                        self.deregister_worker_registration(worker_id).await
3810                    {
3811                        return Err(Error::WorkerShutdown {
3812                            primary: Box::new(error),
3813                            deregistration: Box::new(deregistration),
3814                        });
3815                    }
3816                }
3817                return Err(error);
3818            }
3819        }
3820        if self.cooperative_worker_protocol {
3821            let compatible = response["registered"].as_bool() == Some(true)
3822                && response["worker_id"].as_str() == Some(worker_id)
3823                && response["namespace"].as_str() == Some(self.namespace.as_str())
3824                && response["task_queue"].as_str() == Some(task_queue)
3825                && response["protocol_version"]
3826                    .as_str()
3827                    .is_some_and(cooperative_cancellation::supports_protocol)
3828                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3829                    == Some(true)
3830                && response["capabilities"].as_array().is_some_and(|accepted| {
3831                    capabilities.iter().all(|capability| {
3832                        accepted
3833                            .iter()
3834                            .any(|value| value.as_str() == Some(capability.as_str()))
3835                    })
3836                });
3837            if !compatible {
3838                let error = Error::CooperativeCancellationUnavailable(
3839                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3840                );
3841                if response["registered"].as_bool() == Some(true)
3842                    && response["worker_id"].as_str() == Some(worker_id)
3843                {
3844                    if let Err(deregistration) =
3845                        self.deregister_worker_registration(worker_id).await
3846                    {
3847                        return Err(Error::WorkerShutdown {
3848                            primary: Box::new(error),
3849                            deregistration: Box::new(deregistration),
3850                        });
3851                    }
3852                }
3853                return Err(error);
3854            }
3855        }
3856        Ok(serde_json::from_value(response)?)
3857    }
3858
3859    /// Gracefully remove one worker's registration through the worker plane.
3860    ///
3861    /// This operation is separate from operator-facing worker management. It
3862    /// uses worker-protocol authentication and returns the server's lease
3863    /// recovery result.
3864    pub async fn deregister_worker_registration(
3865        &self,
3866        worker_id: &str,
3867    ) -> Result<WorkerDeregistrationEnvelope> {
3868        let path = format!(
3869            "/worker/registrations/{}",
3870            percent_encode_path_segment(worker_id)
3871        );
3872        self.request_json(
3873            reqwest::Method::DELETE,
3874            &path,
3875            RequestProtocol::DefaultWorker,
3876            Option::<&Value>::None,
3877        )
3878        .await
3879    }
3880
3881    /// Long-poll for an ephemeral, read-only workflow query task.
3882    pub async fn poll_query_task(
3883        &self,
3884        worker_id: &str,
3885        task_queue: &str,
3886        timeout: Duration,
3887    ) -> Result<Option<QueryTask>> {
3888        Ok(self
3889            .poll_query_task_response(worker_id, task_queue, timeout)
3890            .await?
3891            .task)
3892    }
3893
3894    /// Poll a query task while preserving server stop and drain metadata.
3895    pub async fn poll_query_task_response(
3896        &self,
3897        worker_id: &str,
3898        task_queue: &str,
3899        timeout: Duration,
3900    ) -> Result<PollQueryTaskResponse> {
3901        let poll_request_id = unique_request_id("rust-query-poll");
3902        self.poll_query_task_response_with_request_id(
3903            worker_id,
3904            task_queue,
3905            timeout,
3906            &poll_request_id,
3907            1,
3908        )
3909        .await
3910    }
3911
3912    async fn poll_query_task_response_with_request_id(
3913        &self,
3914        worker_id: &str,
3915        task_queue: &str,
3916        timeout: Duration,
3917        poll_request_id: &str,
3918        transport_retries: usize,
3919    ) -> Result<PollQueryTaskResponse> {
3920        let timeout_seconds = long_poll_timeout_seconds(timeout);
3921        let body = json!({
3922            "worker_id": worker_id,
3923            "task_queue": task_queue,
3924            "poll_request_id": poll_request_id,
3925            "timeout_seconds": timeout_seconds,
3926        });
3927        self.poll_request_json(
3928            "/worker/query-tasks/poll",
3929            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3930            &body,
3931            timeout + Duration::from_secs(5),
3932            transport_retries,
3933        )
3934        .await
3935    }
3936
3937    /// Complete a query task without appending workflow history.
3938    pub async fn complete_query_task<T: Serialize>(
3939        &self,
3940        query_task_id: &str,
3941        lease_owner: &str,
3942        query_task_attempt: u64,
3943        result: T,
3944        codec: &str,
3945    ) -> Result<Value> {
3946        let typed_result = AvroValue::from_serialize(&result)?;
3947        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3948        self.complete_query_task_with_envelope(
3949            query_task_id,
3950            lease_owner,
3951            query_task_attempt,
3952            typed_result.into_json()?,
3953            result_envelope,
3954        )
3955        .await
3956    }
3957
3958    async fn complete_query_task_with_envelope(
3959        &self,
3960        query_task_id: &str,
3961        lease_owner: &str,
3962        query_task_attempt: u64,
3963        result: Value,
3964        result_envelope: Value,
3965    ) -> Result<Value> {
3966        let body = json!({
3967            "lease_owner": lease_owner,
3968            "query_task_attempt": query_task_attempt,
3969            "result": result,
3970            "result_envelope": result_envelope,
3971        });
3972        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3973        let response = self
3974            .request_json(
3975                reqwest::Method::POST,
3976                &path,
3977                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3978                Some(&body),
3979            )
3980            .await;
3981        query_task_response(response)
3982    }
3983
3984    /// Report a stable machine-readable query-task failure.
3985    pub async fn fail_query_task(
3986        &self,
3987        query_task_id: &str,
3988        lease_owner: &str,
3989        query_task_attempt: u64,
3990        message: impl Into<String>,
3991        reason: impl Into<String>,
3992        failure_type: impl Into<String>,
3993    ) -> Result<Value> {
3994        let body = json!({
3995            "lease_owner": lease_owner,
3996            "query_task_attempt": query_task_attempt,
3997            "failure": {
3998                "message": message.into(),
3999                "reason": reason.into(),
4000                "type": failure_type.into(),
4001            }
4002        });
4003        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4004        let response = self
4005            .request_json(
4006                reqwest::Method::POST,
4007                &path,
4008                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4009                Some(&body),
4010            )
4011            .await;
4012        query_task_response(response)
4013    }
4014
4015    pub async fn heartbeat_worker(
4016        &self,
4017        worker_id: &str,
4018        workflow_available: usize,
4019        activity_available: usize,
4020    ) -> Result<Value> {
4021        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4022            .await
4023    }
4024
4025    async fn heartbeat_worker_with_sessions(
4026        &self,
4027        worker_id: &str,
4028        workflow_available: usize,
4029        activity_available: usize,
4030        session_available: Option<usize>,
4031    ) -> Result<Value> {
4032        let mut body = json!({
4033            "worker_id": worker_id,
4034            "task_slots": {
4035                "workflow_available": workflow_available,
4036                "activity_available": activity_available
4037            },
4038            "process_metrics": {
4039                "process_id": std::process::id(),
4040                "process_uptime_seconds": 0
4041            }
4042        });
4043
4044        if let Some(available) = session_available {
4045            body["task_slots"]["session_available"] = json!(available);
4046        }
4047
4048        self.request_json(
4049            reqwest::Method::POST,
4050            "/worker/heartbeat",
4051            RequestProtocol::DefaultWorker,
4052            Some(&body),
4053        )
4054        .await
4055    }
4056
4057    pub async fn poll_workflow_task(
4058        &self,
4059        worker_id: &str,
4060        task_queue: &str,
4061        timeout: Duration,
4062    ) -> Result<Option<WorkflowTask>> {
4063        Ok(self
4064            .poll_workflow_task_response(worker_id, task_queue, timeout)
4065            .await?
4066            .task)
4067    }
4068
4069    pub async fn poll_workflow_task_response(
4070        &self,
4071        worker_id: &str,
4072        task_queue: &str,
4073        timeout: Duration,
4074    ) -> Result<PollWorkflowTaskResponse> {
4075        let poll_request_id = unique_request_id("rust-workflow-poll");
4076        self.poll_workflow_task_response_with_request_id(
4077            worker_id,
4078            task_queue,
4079            timeout,
4080            &poll_request_id,
4081            1,
4082        )
4083        .await
4084    }
4085
4086    async fn poll_workflow_task_response_with_request_id(
4087        &self,
4088        worker_id: &str,
4089        task_queue: &str,
4090        timeout: Duration,
4091        poll_request_id: &str,
4092        transport_retries: usize,
4093    ) -> Result<PollWorkflowTaskResponse> {
4094        let body = json!({
4095            "worker_id": worker_id,
4096            "task_queue": task_queue,
4097            "poll_request_id": poll_request_id,
4098            "timeout_seconds": long_poll_timeout_seconds(timeout),
4099            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4100        });
4101        let mut wire: Value = self
4102            .poll_request_json_unresolved(
4103                "/worker/workflow-tasks/poll",
4104                RequestProtocol::DefaultWorker,
4105                &body,
4106                timeout + Duration::from_secs(5),
4107                transport_retries,
4108            )
4109            .await?;
4110        let claim =
4111            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4112        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4113            self.resolve_runtime_payloads(
4114                &mut wire,
4115                "/worker/workflow-tasks/poll",
4116                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4117            )
4118            .await?;
4119            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4120            if let Some(task) = data.task.as_mut() {
4121                self.fetch_remaining_workflow_history(worker_id, task)
4122                    .await?;
4123            }
4124            Ok(data)
4125        })
4126        .await?;
4127        Ok(data)
4128    }
4129
4130    async fn fetch_remaining_workflow_history(
4131        &self,
4132        worker_id: &str,
4133        task: &mut WorkflowTask,
4134    ) -> Result<()> {
4135        let mut next_token = task.next_history_page_token.clone();
4136        let mut seen = BTreeSet::new();
4137
4138        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4139            if seen.len() >= 128 || !seen.insert(token.clone()) {
4140                return Err(Error::Codec(
4141                    "workflow history pagination exceeded its page bound or repeated a token"
4142                        .into(),
4143                ));
4144            }
4145            let lease_owner = task
4146                .lease_owner
4147                .clone()
4148                .unwrap_or_else(|| worker_id.to_string());
4149            let page = self
4150                .workflow_task_history_page(
4151                    &task.task_id,
4152                    &lease_owner,
4153                    task.workflow_task_attempt,
4154                    &token,
4155                )
4156                .await?;
4157
4158            task.append_history_page(page);
4159
4160            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4161                return Err(Error::Codec(
4162                    "workflow history pagination returned the same page token".to_string(),
4163                ));
4164            }
4165
4166            next_token = task.next_history_page_token.clone();
4167        }
4168
4169        Ok(())
4170    }
4171
4172    async fn workflow_task_history_page(
4173        &self,
4174        task_id: &str,
4175        lease_owner: &str,
4176        workflow_task_attempt: u64,
4177        next_history_page_token: &str,
4178    ) -> Result<WorkflowTaskHistoryPage> {
4179        let body = json!({
4180            "lease_owner": lease_owner,
4181            "workflow_task_attempt": workflow_task_attempt,
4182            "next_history_page_token": next_history_page_token
4183        });
4184        let path = format!("/worker/workflow-tasks/{task_id}/history");
4185
4186        self.request_json(
4187            reqwest::Method::POST,
4188            &path,
4189            RequestProtocol::DefaultWorker,
4190            Some(&body),
4191        )
4192        .await
4193    }
4194
4195    pub async fn complete_workflow_task(
4196        &self,
4197        task_id: &str,
4198        lease_owner: &str,
4199        workflow_task_attempt: u64,
4200        commands: Vec<Value>,
4201    ) -> Result<Value> {
4202        self.complete_workflow_task_with_message_streams(
4203            task_id,
4204            lease_owner,
4205            workflow_task_attempt,
4206            commands,
4207            Vec::new(),
4208            Vec::new(),
4209            None,
4210        )
4211        .await
4212    }
4213
4214    #[allow(clippy::too_many_arguments)]
4215    async fn complete_workflow_task_with_message_streams(
4216        &self,
4217        task_id: &str,
4218        lease_owner: &str,
4219        workflow_task_attempt: u64,
4220        commands: Vec<Value>,
4221        message_stream_cursors: Vec<Value>,
4222        message_stream_waits: Vec<Value>,
4223        sticky_cache: Option<Value>,
4224    ) -> Result<Value> {
4225        validate_workflow_task_commands(&commands)?;
4226        let has_message_stream_metadata =
4227            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4228        if has_message_stream_metadata
4229            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4230        {
4231            return Err(Error::Codec(
4232                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4233                    .to_string(),
4234            ));
4235        }
4236        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4237            &commands,
4238            has_message_stream_metadata,
4239        );
4240        let protocol_version = if sticky_cache.is_some()
4241            && protocol_version
4242                .strip_prefix("1.")
4243                .and_then(|minor| minor.parse::<u64>().ok())
4244                .is_some_and(|minor| minor < 18)
4245        {
4246            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4247        } else {
4248            protocol_version
4249        };
4250        let mut body = json!({
4251            "lease_owner": lease_owner,
4252            "workflow_task_attempt": workflow_task_attempt,
4253            "commands": commands
4254        });
4255        if !message_stream_cursors.is_empty() {
4256            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4257        }
4258        if !message_stream_waits.is_empty() {
4259            body["message_stream_waits"] = Value::Array(message_stream_waits);
4260        }
4261        if let Some(claim) = sticky_cache {
4262            body["sticky_cache"] = claim;
4263        }
4264        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4265        self.request_json(
4266            reqwest::Method::POST,
4267            &path,
4268            RequestProtocol::Worker(protocol_version),
4269            Some(&body),
4270        )
4271        .await
4272    }
4273
4274    pub async fn fail_workflow_task(
4275        &self,
4276        task_id: &str,
4277        lease_owner: &str,
4278        workflow_task_attempt: u64,
4279        message: impl Into<String>,
4280    ) -> Result<Value> {
4281        self.fail_workflow_task_with_type(
4282            task_id,
4283            lease_owner,
4284            workflow_task_attempt,
4285            message,
4286            "RustWorkflowTaskFailure",
4287        )
4288        .await
4289    }
4290
4291    async fn fail_workflow_task_with_type(
4292        &self,
4293        task_id: &str,
4294        lease_owner: &str,
4295        workflow_task_attempt: u64,
4296        message: impl Into<String>,
4297        failure_type: &str,
4298    ) -> Result<Value> {
4299        let body = json!({
4300            "lease_owner": lease_owner,
4301            "workflow_task_attempt": workflow_task_attempt,
4302            "failure": {
4303                "message": message.into(),
4304                "type": failure_type
4305            }
4306        });
4307        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4308        self.request_json(
4309            reqwest::Method::POST,
4310            &path,
4311            RequestProtocol::DefaultWorker,
4312            Some(&body),
4313        )
4314        .await
4315    }
4316
4317    pub async fn poll_activity_task(
4318        &self,
4319        worker_id: &str,
4320        task_queue: &str,
4321        timeout: Duration,
4322    ) -> Result<Option<ActivityTask>> {
4323        Ok(self
4324            .poll_activity_task_response(worker_id, task_queue, timeout)
4325            .await?
4326            .task)
4327    }
4328
4329    /// Poll an activity task while preserving server stop and drain metadata.
4330    pub async fn poll_activity_task_response(
4331        &self,
4332        worker_id: &str,
4333        task_queue: &str,
4334        timeout: Duration,
4335    ) -> Result<PollActivityTaskResponse> {
4336        let poll_request_id = unique_request_id("rust-activity-poll");
4337        self.poll_activity_task_response_with_request_id(
4338            worker_id,
4339            task_queue,
4340            timeout,
4341            &poll_request_id,
4342            1,
4343        )
4344        .await
4345        .map(worker_session::SessionPollResponse::ordinary)
4346    }
4347
4348    async fn poll_activity_task_response_with_request_id(
4349        &self,
4350        worker_id: &str,
4351        task_queue: &str,
4352        timeout: Duration,
4353        poll_request_id: &str,
4354        transport_retries: usize,
4355    ) -> Result<worker_session::SessionPollResponse> {
4356        let body = json!({
4357            "worker_id": worker_id,
4358            "task_queue": task_queue,
4359            "poll_request_id": poll_request_id,
4360            "timeout_seconds": long_poll_timeout_seconds(timeout),
4361        });
4362        let mut wire: Value = self
4363            .poll_request_json_unresolved(
4364                "/worker/activity-tasks/poll",
4365                RequestProtocol::DefaultWorker,
4366                &body,
4367                timeout + Duration::from_secs(5),
4368                transport_retries,
4369            )
4370            .await?;
4371        let claim = activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?;
4372        let mut data: worker_session::SessionPollResponse =
4373            activity_hydration::HydrationClaim::protect(claim.as_ref(), self, async {
4374                self.resolve_runtime_payloads(
4375                    &mut wire,
4376                    "/worker/activity-tasks/poll",
4377                    RequestProtocol::DefaultWorker,
4378                )
4379                .await?;
4380                Ok(serde_json::from_value(wire)?)
4381            })
4382            .await?;
4383        if let Some(task) = data.task.as_mut() {
4384            task.hydration_claim = claim;
4385        }
4386        Ok(data)
4387    }
4388
4389    pub async fn complete_activity_task<T: Serialize>(
4390        &self,
4391        task_id: &str,
4392        activity_attempt_id: &str,
4393        lease_owner: &str,
4394        result: T,
4395        codec: &str,
4396    ) -> Result<Value> {
4397        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4398        let body = json!({
4399            "activity_attempt_id": activity_attempt_id,
4400            "lease_owner": lease_owner,
4401            "result": result
4402        });
4403        let path = format!("/worker/activity-tasks/{task_id}/complete");
4404        activity_task_response(
4405            self.request_json(
4406                reqwest::Method::POST,
4407                &path,
4408                RequestProtocol::DefaultWorker,
4409                Some(&body),
4410            )
4411            .await,
4412            "complete",
4413            task_id,
4414            activity_attempt_id,
4415        )
4416    }
4417
4418    pub async fn fail_activity_task(
4419        &self,
4420        task_id: &str,
4421        activity_attempt_id: &str,
4422        lease_owner: &str,
4423        message: impl Into<String>,
4424        non_retryable: bool,
4425    ) -> Result<Value> {
4426        let body = json!({
4427            "activity_attempt_id": activity_attempt_id,
4428            "lease_owner": lease_owner,
4429            "failure": {
4430                "message": message.into(),
4431                "type": "RustActivityFailure",
4432                "non_retryable": non_retryable
4433            }
4434        });
4435        let path = format!("/worker/activity-tasks/{task_id}/fail");
4436        activity_task_response(
4437            self.request_json(
4438                reqwest::Method::POST,
4439                &path,
4440                RequestProtocol::DefaultWorker,
4441                Some(&body),
4442            )
4443            .await,
4444            "fail",
4445            task_id,
4446            activity_attempt_id,
4447        )
4448    }
4449
4450    /// Record a flat map of scalar/null activity progress metadata.
4451    ///
4452    /// Heartbeat details use the Server's bounded JSON progress contract.
4453    /// They are not workflow payload envelopes.
4454    pub async fn heartbeat_activity_task<T: Serialize>(
4455        &self,
4456        task_id: &str,
4457        activity_attempt_id: &str,
4458        lease_owner: &str,
4459        details: T,
4460    ) -> Result<ActivityHeartbeatResponse> {
4461        serde_json::from_value(
4462            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4463                .await?,
4464        )
4465        .map_err(Error::from)
4466    }
4467
4468    async fn heartbeat_activity_task_value<T: Serialize>(
4469        &self,
4470        task_id: &str,
4471        activity_attempt_id: &str,
4472        lease_owner: &str,
4473        details: T,
4474    ) -> Result<Value> {
4475        let details = AvroValue::from_serialize(&details)?.into_json()?;
4476        let body = json!({
4477            "activity_attempt_id": activity_attempt_id,
4478            "lease_owner": lease_owner,
4479            "details": details
4480        });
4481        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4482        activity_task_response(
4483            self.request_json(
4484                reqwest::Method::POST,
4485                &path,
4486                RequestProtocol::DefaultWorker,
4487                Some(&body),
4488            )
4489            .await,
4490            "heartbeat",
4491            task_id,
4492            activity_attempt_id,
4493        )
4494    }
4495
4496    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4497        &self,
4498        method: reqwest::Method,
4499        path: &str,
4500        protocol: RequestProtocol,
4501        body: Option<&B>,
4502    ) -> Result<T> {
4503        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4504            .await
4505    }
4506
4507    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4508        &self,
4509        method: reqwest::Method,
4510        path: &str,
4511        protocol: RequestProtocol,
4512        body: Option<&B>,
4513        timeout: Duration,
4514    ) -> Result<T> {
4515        let mut value: Value = self
4516            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4517            .await?;
4518        let protocol = match protocol {
4519            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4520                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4521            }
4522            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4523        };
4524        self.resolve_runtime_payloads(&mut value, path, protocol)
4525            .await?;
4526        Ok(serde_json::from_value(value)?)
4527    }
4528
4529    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4530        &self,
4531        method: reqwest::Method,
4532        path: &str,
4533        protocol: RequestProtocol,
4534        body: Option<&B>,
4535        timeout: Duration,
4536    ) -> Result<T> {
4537        let protocol = match protocol {
4538            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4539                let selected = self.worker_protocol_version.as_str();
4540                if self.cooperative_worker_protocol
4541                    && !cooperative_cancellation::supports_protocol(selected)
4542                {
4543                    return Err(Error::CooperativeCancellationUnavailable(
4544                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4545                    ));
4546                }
4547                if let RequestProtocol::Worker(minimum) = protocol {
4548                    let supported = minimum
4549                        .strip_prefix("1.")
4550                        .and_then(|minor| minor.parse::<u64>().ok())
4551                        .zip(
4552                            selected
4553                                .strip_prefix("1.")
4554                                .and_then(|minor| minor.parse::<u64>().ok()),
4555                        )
4556                        .is_some_and(|(minimum, selected)| selected >= minimum);
4557                    if !supported {
4558                        return Err(Error::WorkerLoop(format!(
4559                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4560                        )));
4561                    }
4562                }
4563                RequestProtocol::Worker(selected)
4564            }
4565            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4566        };
4567        let auth_token = self.auth_token(protocol)?;
4568        let mut request = self
4569            .http
4570            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4571            .timeout(timeout)
4572            .header(reqwest::header::ACCEPT, "application/json")
4573            .header(reqwest::header::CONTENT_TYPE, "application/json")
4574            .header("X-Namespace", &self.namespace);
4575
4576        match protocol {
4577            RequestProtocol::DefaultWorker => {
4578                request = request.header(
4579                    "X-Durable-Workflow-Protocol-Version",
4580                    self.worker_protocol_version.as_str(),
4581                );
4582            }
4583            RequestProtocol::Worker(version) => {
4584                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4585            }
4586            RequestProtocol::ControlPlane => {
4587                request = request.header(
4588                    "X-Durable-Workflow-Control-Plane-Version",
4589                    CONTROL_PLANE_VERSION,
4590                );
4591            }
4592        }
4593
4594        if let Some(token) = auth_token {
4595            request = request.bearer_auth(token);
4596        }
4597
4598        if let Some(body) = body {
4599            let mut body = serde_json::to_value(body)?;
4600            if matches!(
4601                method,
4602                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4603            ) {
4604                self.externalize_runtime_payloads(&mut body, path, protocol)
4605                    .await?;
4606            }
4607            request = request.json(&body);
4608        }
4609
4610        let request = request.build()?;
4611        let request_body = request
4612            .body()
4613            .and_then(reqwest::Body::as_bytes)
4614            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4615        let poll_request_id = path.ends_with("/poll").then(|| {
4616            request_body
4617                .as_ref()
4618                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4619                .unwrap_or_default()
4620        });
4621        let mut storage_retries = 0_usize;
4622
4623        loop {
4624            // Keep the serialized body and lease/poll identity across admission pauses.
4625            let response = self
4626                .http
4627                .execute(request.try_clone().ok_or_else(|| {
4628                    Error::WorkerLoop("worker request body cannot be retried".to_string())
4629                })?)
4630                .await?;
4631            let status = response.status();
4632            let bytes = response.bytes().await?;
4633
4634            if !status.is_success() {
4635                let body = String::from_utf8_lossy(&bytes).to_string();
4636                if let Some(protocol) = protocol_failure(status, &body) {
4637                    return Err(Error::Protocol(protocol));
4638                }
4639                let error = Error::Http { status, body };
4640                if self
4641                    .wait_for_storage_admission(
4642                        &error,
4643                        protocol,
4644                        Some(path),
4645                        poll_request_id.as_deref(),
4646                        request_body.as_ref(),
4647                        &mut storage_retries,
4648                    )
4649                    .await
4650                {
4651                    continue;
4652                }
4653                return Err(error);
4654            }
4655
4656            if bytes.is_empty() {
4657                return Ok(serde_json::from_value(Value::Null)?);
4658            }
4659
4660            return Ok(serde_json::from_slice(&bytes)?);
4661        }
4662    }
4663
4664    async fn wait_for_storage_admission(
4665        &self,
4666        error: &Error,
4667        protocol: RequestProtocol,
4668        path: Option<&str>,
4669        poll_request_id: Option<&str>,
4670        request_body: Option<&Value>,
4671        retries: &mut usize,
4672    ) -> bool {
4673        let Some(admission) = self
4674            .worker_storage_admission
4675            .as_ref()
4676            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4677        else {
4678            return false;
4679        };
4680        let Some(advertised_delay) = worker_storage_admission_retry_after(error, poll_request_id)
4681            .or_else(|| {
4682                path.and_then(|path| {
4683                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4684                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4685                })
4686            })
4687        else {
4688            return false;
4689        };
4690        *retries = retries.saturating_add(1);
4691        let delay = worker_retry_delay(admission.policy, *retries)
4692            .max(advertised_delay)
4693            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4694        let deadline = tokio::time::Instant::now() + delay;
4695        loop {
4696            if admission.stop.load(Ordering::SeqCst) {
4697                return false;
4698            }
4699            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
4700            if remaining.is_zero() {
4701                return true;
4702            }
4703            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4704        }
4705    }
4706
4707    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4708        &self,
4709        path: &str,
4710        protocol: RequestProtocol,
4711        body: &B,
4712        timeout: Duration,
4713        max_retries: usize,
4714    ) -> Result<T> {
4715        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4716            .await
4717    }
4718
4719    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4720        &self,
4721        path: &str,
4722        protocol: RequestProtocol,
4723        body: &B,
4724        timeout: Duration,
4725        max_retries: usize,
4726    ) -> Result<T> {
4727        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4728            .await
4729    }
4730
4731    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4732        &self,
4733        path: &str,
4734        protocol: RequestProtocol,
4735        body: &B,
4736        timeout: Duration,
4737        max_retries: usize,
4738        resolve: bool,
4739    ) -> Result<T> {
4740        let mut retries = 0;
4741
4742        loop {
4743            let response = if resolve {
4744                self.request_json_with_timeout(
4745                    reqwest::Method::POST,
4746                    path,
4747                    protocol,
4748                    Some(body),
4749                    timeout,
4750                )
4751                .await
4752            } else {
4753                self.request_json_unresolved_with_timeout(
4754                    reqwest::Method::POST,
4755                    path,
4756                    protocol,
4757                    Some(body),
4758                    timeout,
4759                )
4760                .await
4761            };
4762
4763            match response {
4764                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4765                response => return worker_poll_response(response),
4766            }
4767        }
4768    }
4769
4770    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4771        match protocol {
4772            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4773                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4774                    return Ok(Some(token));
4775                }
4776                if self.control_token.is_some() {
4777                    return Err(Error::MissingRoleCredentials {
4778                        role: "worker",
4779                        opposite_role: "control",
4780                    });
4781                }
4782                Ok(None)
4783            }
4784            RequestProtocol::ControlPlane => {
4785                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4786                    return Ok(Some(token));
4787                }
4788                if self.worker_token.is_some() {
4789                    return Err(Error::MissingRoleCredentials {
4790                        role: "control",
4791                        opposite_role: "worker",
4792                    });
4793                }
4794                Ok(None)
4795            }
4796        }
4797    }
4798}
4799
4800fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4801    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4802    let reason = body
4803        .get("reason")
4804        .and_then(Value::as_str)
4805        .unwrap_or("query_rejected")
4806        .to_string();
4807    let message = body
4808        .get("message")
4809        .or_else(|| body.get("error"))
4810        .and_then(Value::as_str)
4811        .unwrap_or("workflow query was rejected")
4812        .to_string();
4813
4814    QueryFailure {
4815        status: status.as_u16(),
4816        reason,
4817        message,
4818        body,
4819    }
4820}
4821
4822fn workflow_command_result(
4823    command: WorkflowCommandKind,
4824    data: Value,
4825    workflow_id: &str,
4826    run_id: Option<&str>,
4827) -> WorkflowCommandResult {
4828    WorkflowCommandResult {
4829        command,
4830        workflow_id: data
4831            .get("workflow_id")
4832            .and_then(Value::as_str)
4833            .unwrap_or(workflow_id)
4834            .to_string(),
4835        run_id: data
4836            .get("run_id")
4837            .and_then(Value::as_str)
4838            .or(run_id)
4839            .map(str::to_string),
4840        outcome: data
4841            .get("outcome")
4842            .and_then(Value::as_str)
4843            .map(str::to_string),
4844        reason: data
4845            .get("reason")
4846            .and_then(Value::as_str)
4847            .map(str::to_string),
4848        command_status: data
4849            .get("command_status")
4850            .and_then(Value::as_str)
4851            .map(str::to_string),
4852        raw: data,
4853    }
4854}
4855
4856fn workflow_command_rejection(
4857    command: WorkflowCommandKind,
4858    status: reqwest::StatusCode,
4859    raw_body: String,
4860    workflow_id: &str,
4861    run_id: Option<&str>,
4862) -> WorkflowCommandRejection {
4863    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4864    WorkflowCommandRejection {
4865        command,
4866        status: status.as_u16(),
4867        reason: body
4868            .get("reason")
4869            .and_then(Value::as_str)
4870            .unwrap_or("workflow_command_rejected")
4871            .to_string(),
4872        message: body
4873            .get("message")
4874            .or_else(|| body.get("error"))
4875            .and_then(Value::as_str)
4876            .unwrap_or("workflow lifecycle command was rejected")
4877            .to_string(),
4878        workflow_id: body
4879            .get("workflow_id")
4880            .and_then(Value::as_str)
4881            .unwrap_or(workflow_id)
4882            .to_string(),
4883        run_id: body
4884            .get("run_id")
4885            .and_then(Value::as_str)
4886            .or(run_id)
4887            .map(str::to_string),
4888        target_scope: body
4889            .get("target_scope")
4890            .and_then(Value::as_str)
4891            .map(str::to_string),
4892        body,
4893    }
4894}
4895
4896fn query_task_response(response: Result<Value>) -> Result<Value> {
4897    match response {
4898        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4899        response => response,
4900    }
4901}
4902
4903fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4904    match response {
4905        Err(Error::Http { status, body })
4906            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4907        {
4908            Ok(serde_json::from_str(&body)?)
4909        }
4910        response => response,
4911    }
4912}
4913
4914fn worker_poll_body_is_stop(body: &str) -> bool {
4915    serde_json::from_str::<Value>(body)
4916        .ok()
4917        .is_some_and(|body| {
4918            worker_poll_is_stop(
4919                body.get("poll_status").and_then(Value::as_str),
4920                body.get("reason").and_then(Value::as_str),
4921            )
4922        })
4923}
4924
4925fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4926    matches!(poll_status, Some("draining" | "stopped"))
4927        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4928}
4929
4930fn query_task_rejection_is_final(error: &Error) -> bool {
4931    matches!(
4932        error,
4933        Error::QueryFailed(failure)
4934            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4935    )
4936}
4937
4938fn activity_task_response<T>(
4939    response: Result<T>,
4940    operation: &str,
4941    task_id: &str,
4942    activity_attempt_id: &str,
4943) -> Result<T> {
4944    match response {
4945        Err(Error::Http { status, body }) => {
4946            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4947            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4948                operation: operation.to_string(),
4949                status: status.as_u16(),
4950                reason: body
4951                    .get("reason")
4952                    .and_then(Value::as_str)
4953                    .unwrap_or("activity_task_rejected")
4954                    .to_string(),
4955                task_id: body
4956                    .get("task_id")
4957                    .and_then(Value::as_str)
4958                    .unwrap_or(task_id)
4959                    .to_string(),
4960                activity_attempt_id: body
4961                    .get("activity_attempt_id")
4962                    .and_then(Value::as_str)
4963                    .unwrap_or(activity_attempt_id)
4964                    .to_string(),
4965                cancel_requested: body
4966                    .get("cancel_requested")
4967                    .and_then(Value::as_bool)
4968                    .unwrap_or(false),
4969                can_continue: body.get("can_continue").and_then(Value::as_bool),
4970                run_closed_reason: body
4971                    .get("run_closed_reason")
4972                    .and_then(Value::as_str)
4973                    .map(str::to_string),
4974                body,
4975            }))
4976        }
4977        response => response,
4978    }
4979}
4980
4981fn activity_task_rejection_is_final(error: &Error) -> bool {
4982    matches!(
4983        error,
4984        Error::ActivityTaskRejected(rejection)
4985            if matches!(
4986                rejection.reason.as_str(),
4987                "run_cancelled"
4988                    | "run_terminated"
4989                    | "attempt_closed"
4990                    | "stale_attempt"
4991                    | "activity_cancelled"
4992                    | "task_cancelled"
4993                    | "run_closed"
4994                    | "activity_not_running"
4995                    | "attempt_not_found"
4996            )
4997    )
4998}
4999
5000fn workflow_task_completion_is_terminal_timeout(
5001    error: &Error,
5002    task_id: &str,
5003    workflow_task_attempt: u64,
5004    run_id: Option<&str>,
5005) -> bool {
5006    let Error::Http { status, body } = error else {
5007        return false;
5008    };
5009    if *status != reqwest::StatusCode::CONFLICT {
5010        return false;
5011    }
5012
5013    let Some(run_id) = run_id else {
5014        return false;
5015    };
5016    let Ok(body) = serde_json::from_str::<Value>(body) else {
5017        return false;
5018    };
5019
5020    body.get("recorded").and_then(Value::as_bool) == Some(false)
5021        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5022        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5023        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5024        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5025        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5026}
5027
5028fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5029    let body: Value = serde_json::from_str(raw_body).ok()?;
5030    let reason = body.get("reason")?.as_str()?;
5031    if !matches!(
5032        reason,
5033        "missing_protocol_version"
5034            | "unsupported_protocol_version"
5035            | "missing_control_plane_version"
5036            | "unsupported_control_plane_version"
5037    ) {
5038        return None;
5039    }
5040
5041    Some(ProtocolFailure {
5042        status: status.as_u16(),
5043        reason: reason.to_string(),
5044        message: body
5045            .get("message")
5046            .or_else(|| body.get("error"))
5047            .and_then(Value::as_str)
5048            .unwrap_or("protocol version rejected")
5049            .to_string(),
5050        supported_version: body
5051            .get("supported_version")
5052            .and_then(Value::as_str)
5053            .map(str::to_string),
5054        requested_version: body
5055            .get("requested_version")
5056            .and_then(Value::as_str)
5057            .map(str::to_string),
5058        body,
5059    })
5060}
5061
5062fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5063    timeout
5064        .as_secs()
5065        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5066        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5067}
5068
5069fn worker_operation_is_retryable(error: &Error) -> bool {
5070    if worker_poll_capacity_retry_after(error).is_some()
5071        || worker_storage_admission_body(error).is_some()
5072        || worker_backend_unavailable_body(error).is_some()
5073        || worker_operation_is_explicitly_non_retryable(error)
5074    {
5075        return false;
5076    }
5077
5078    match error {
5079        Error::Transport(error) => {
5080            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5081        }
5082        Error::Http { status, .. } => {
5083            matches!(
5084                *status,
5085                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5086            ) || status.is_server_error()
5087        }
5088        _ => false,
5089    }
5090}
5091
5092fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5093    let body: Value = match error {
5094        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5095        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5096        _ => return None,
5097    };
5098    matches!(
5099        body.get("reason").and_then(Value::as_str),
5100        Some("storage_pressure" | "storage_admission_unavailable")
5101    )
5102    .then_some(body)
5103}
5104
5105fn worker_storage_admission_retry_after(
5106    error: &Error,
5107    poll_request_id: Option<&str>,
5108) -> Option<Duration> {
5109    let Error::Http { status, .. } = error else {
5110        return None;
5111    };
5112    let body = worker_storage_admission_body(error)?;
5113    let delay = body.get("retry_after_seconds")?.as_u64()?;
5114    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5115        || delay == 0
5116        || body.get("retryable") != Some(&Value::Bool(true))
5117        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5118        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5119        || body
5120            .get("request_admitted")
5121            .is_some_and(|admitted| admitted != &Value::Bool(false))
5122    {
5123        return None;
5124    }
5125    match poll_request_id {
5126        Some(id) => {
5127            if id.is_empty()
5128                || body.get("task") != Some(&Value::Null)
5129                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5130                || body.get("poll_status") != body.get("reason")
5131                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5132                || body.get("claim_admitted") != Some(&Value::Bool(false))
5133            {
5134                return None;
5135            }
5136        }
5137        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5138        None => {}
5139    }
5140    Some(Duration::from_secs(delay))
5141}
5142
5143fn worker_backend_unavailable_retry_after(
5144    error: &Error,
5145    path: &str,
5146    poll_request_id: Option<&str>,
5147) -> Option<Duration> {
5148    let operation = match path {
5149        "/worker/register" => "register_worker",
5150        "/worker/heartbeat" => "heartbeat_worker",
5151        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5152        "/worker/activity-tasks/poll" => "poll_activity_task",
5153        "/worker/query-tasks/poll" => "poll_query_task",
5154        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5155        _ => return None,
5156    };
5157    let body = worker_backend_unavailable_body(error)?;
5158    let delay = body.get("retry_after_seconds")?.as_u64()?;
5159    if delay == 0
5160        || body.get("operation")?.as_str()? != operation
5161        || body.get("outcome")?.as_str()? != "unknown"
5162        || body.get("retryable") != Some(&Value::Bool(true))
5163        || body.get("worker_id")?.as_str()?.is_empty()
5164    {
5165        return None;
5166    }
5167    if let Some(id) = poll_request_id {
5168        if id.is_empty()
5169            || body.get("task") != Some(&Value::Null)
5170            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5171            || body.get("poll_request_id")?.as_str()? != id
5172            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5173        {
5174            return None;
5175        }
5176    } else if path.ends_with("/poll") {
5177        return None;
5178    }
5179    Some(Duration::from_secs(delay))
5180}
5181
5182fn worker_fenced_completion_retry_after(
5183    error: &Error,
5184    path: &str,
5185    request_body: Option<&Value>,
5186) -> Option<Duration> {
5187    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5188        .strip_prefix("/worker/workflow-tasks/")
5189        .and_then(|tail| tail.strip_suffix("/complete"))
5190    {
5191        ("complete_workflow_task", task_id, "workflow_task_attempt")
5192    } else if let Some(task_id) = path
5193        .strip_prefix("/worker/activity-tasks/")
5194        .and_then(|tail| tail.strip_suffix("/complete"))
5195    {
5196        ("complete_activity_task", task_id, "activity_attempt_id")
5197    } else {
5198        return None;
5199    };
5200    if task_id.is_empty() || task_id.contains('/') {
5201        return None;
5202    }
5203
5204    let request = request_body?.as_object()?;
5205    let lease_owner = request.get("lease_owner")?.as_str()?;
5206    if lease_owner.is_empty() {
5207        return None;
5208    }
5209    let attempt = request.get(attempt_field)?;
5210    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5211        || (attempt_field == "activity_attempt_id"
5212            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5213    {
5214        return None;
5215    }
5216
5217    let body = worker_backend_unavailable_body(error)?;
5218    let delay = body.get("retry_after_seconds")?.as_u64()?;
5219    if delay == 0
5220        || body.get("operation")?.as_str()? != operation
5221        || body.get("outcome")?.as_str()? != "unknown"
5222        || body.get("retryable") != Some(&Value::Bool(true))
5223        || body.get("worker_id")?.as_str()? != lease_owner
5224        || body.get("task_queue") != Some(&Value::Null)
5225        || body.get("task_id")?.as_str()? != task_id
5226        || body.get("lease_owner")?.as_str()? != lease_owner
5227        || body.get(attempt_field) != Some(attempt)
5228    {
5229        return None;
5230    }
5231
5232    Some(Duration::from_secs(delay))
5233}
5234
5235fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5236    let Error::Http { status, body } = error else {
5237        return None;
5238    };
5239    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5240        return None;
5241    }
5242    let body: Value = serde_json::from_str(body).ok()?;
5243    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5244}
5245
5246fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5247    let Error::Http { body, .. } = error else {
5248        return false;
5249    };
5250
5251    serde_json::from_str::<Value>(body)
5252        .ok()
5253        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5254        == Some(false)
5255}
5256
5257fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5258    let Error::Http { status, body } = error else {
5259        return None;
5260    };
5261    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5262        return None;
5263    }
5264
5265    let body = serde_json::from_str::<Value>(body).ok()?;
5266    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5267        == Some("long_poll_capacity_exhausted")
5268        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5269    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5270        return None;
5271    }
5272
5273    Some(Duration::from_secs(
5274        body.get("retry_after_seconds")
5275            .and_then(Value::as_u64)
5276            .unwrap_or_default(),
5277    ))
5278}
5279
5280fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5281    let exponent = retry.saturating_sub(1).min(31) as u32;
5282    policy
5283        .initial_backoff
5284        .saturating_mul(1_u32 << exponent)
5285        .min(policy.max_backoff)
5286}
5287
5288#[derive(Debug)]
5289pub struct ClientBuilder {
5290    base_url: String,
5291    token: Option<String>,
5292    control_token: Option<String>,
5293    worker_token: Option<String>,
5294    namespace: String,
5295    timeout: Duration,
5296    max_external_payload_bytes: usize,
5297    worker_protocol_version: WorkerProtocolVersion,
5298}
5299
5300impl ClientBuilder {
5301    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5302    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5303        self.worker_protocol_version = version;
5304        self
5305    }
5306
5307    pub fn token(mut self, token: Option<String>) -> Self {
5308        self.token = token;
5309        self
5310    }
5311
5312    pub fn control_token(mut self, token: Option<String>) -> Self {
5313        self.control_token = token;
5314        self
5315    }
5316
5317    pub fn worker_token(mut self, token: Option<String>) -> Self {
5318        self.worker_token = token;
5319        self
5320    }
5321
5322    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5323        self.namespace = namespace.into();
5324        self
5325    }
5326
5327    pub fn timeout(mut self, timeout: Duration) -> Self {
5328        self.timeout = timeout;
5329        self
5330    }
5331
5332    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5333    /// References are fetched only from this client's authenticated runtime.
5334    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5335        self.max_external_payload_bytes = bytes;
5336        self
5337    }
5338
5339    pub fn build(self) -> Result<Client> {
5340        let base_url = self.base_url.trim_end_matches('/').to_string();
5341        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5342            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5343            .unwrap_or_else(|_| base_url.ends_with("/api"));
5344
5345        if has_sdk_api_suffix {
5346            return Err(Error::InvalidBaseUrl);
5347        }
5348
5349        Ok(Client {
5350            http: reqwest::Client::builder()
5351                .timeout(self.timeout)
5352                .redirect(reqwest::redirect::Policy::none())
5353                .build()?,
5354            hydration_timeout: self.timeout,
5355            base_url,
5356            token: self.token,
5357            control_token: self.control_token,
5358            worker_token: self.worker_token,
5359            namespace: self.namespace,
5360            max_external_payload_bytes: self.max_external_payload_bytes,
5361            worker_storage_admission: None,
5362            cooperative_worker_protocol: false,
5363            worker_protocol_version: self.worker_protocol_version,
5364            local_activities_enabled: false,
5365            worker_sessions_enabled: false,
5366            max_concurrent_worker_sessions: 10,
5367            worker_build_id: None,
5368            sticky_cache: None,
5369            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5370        })
5371    }
5372}
5373
5374#[derive(Clone, Debug)]
5375pub struct WorkflowHandle {
5376    client: Client,
5377    pub workflow_id: String,
5378    pub run_id: Option<String>,
5379    pub workflow_type: String,
5380}
5381
5382impl WorkflowHandle {
5383    /// Describe whichever run is current for this stable workflow instance.
5384    pub async fn describe(&self) -> Result<WorkflowDescription> {
5385        self.client.describe_workflow(&self.workflow_id).await
5386    }
5387
5388    /// Describe the run identity originally selected by this handle.
5389    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5390        let run_id = self.run_id.as_deref().ok_or_else(|| {
5391            Error::Codec("run_id is required for selected-run description".to_string())
5392        })?;
5393        self.client
5394            .describe_workflow_run(&self.workflow_id, run_id)
5395            .await
5396    }
5397
5398    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5399        self.client
5400            .signal_workflow(&self.workflow_id, signal_name, input)
5401            .await
5402    }
5403
5404    pub async fn append_message<T: Serialize>(
5405        &self,
5406        stream_name: &str,
5407        message_id: &str,
5408        input: T,
5409    ) -> Result<Value> {
5410        self.client
5411            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5412            .await
5413    }
5414
5415    /// Signal only if this handle's selected run is still current.
5416    pub async fn signal_selected_run<T: Serialize>(
5417        &self,
5418        signal_name: &str,
5419        input: T,
5420    ) -> Result<Value> {
5421        let run_id = self.run_id.as_deref().ok_or_else(|| {
5422            Error::Codec("run_id is required for selected-run signaling".to_string())
5423        })?;
5424        self.client
5425            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5426            .await
5427    }
5428
5429    /// Close whichever run is current as cancelled, without workflow cleanup.
5430    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5431        self.client
5432            .cancel_workflow(&self.workflow_id, options)
5433            .await
5434    }
5435
5436    /// Request cancellation only if this handle's selected run is still current.
5437    pub async fn cancel_selected_run(
5438        &self,
5439        options: WorkflowCommandOptions,
5440    ) -> Result<WorkflowCommandResult> {
5441        let run_id = self.run_id.as_deref().ok_or_else(|| {
5442            Error::Codec("run_id is required for selected-run cancellation".to_string())
5443        })?;
5444        self.client
5445            .cancel_workflow_run(&self.workflow_id, run_id, options)
5446            .await
5447    }
5448
5449    /// Forcefully terminate whichever run is current.
5450    pub async fn terminate(
5451        &self,
5452        options: WorkflowCommandOptions,
5453    ) -> Result<WorkflowCommandResult> {
5454        self.client
5455            .terminate_workflow(&self.workflow_id, options)
5456            .await
5457    }
5458
5459    /// Terminate only if this handle's selected run is still current.
5460    pub async fn terminate_selected_run(
5461        &self,
5462        options: WorkflowCommandOptions,
5463    ) -> Result<WorkflowCommandResult> {
5464        let run_id = self.run_id.as_deref().ok_or_else(|| {
5465            Error::Codec("run_id is required for selected-run termination".to_string())
5466        })?;
5467        self.client
5468            .terminate_workflow_run(&self.workflow_id, run_id, options)
5469            .await
5470    }
5471
5472    /// Continue this handle's failed run without repeating completed activities.
5473    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5474        let run_id = self
5475            .run_id
5476            .as_deref()
5477            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5478        self.client
5479            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5480            .await
5481    }
5482
5483    /// Execute a named, read-only query against this workflow.
5484    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5485        self.client
5486            .query_workflow(&self.workflow_id, query_name, input)
5487            .await
5488    }
5489
5490    pub async fn query_avro_value<T: Serialize>(
5491        &self,
5492        query_name: &str,
5493        input: T,
5494    ) -> Result<AvroValue> {
5495        self.client
5496            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5497            .await
5498    }
5499
5500    pub async fn update<T: Serialize>(
5501        &self,
5502        update_name: &str,
5503        input: T,
5504        request_id: Option<&str>,
5505    ) -> Result<Value> {
5506        self.client
5507            .update_workflow(&self.workflow_id, update_name, input, request_id)
5508            .await
5509    }
5510
5511    pub async fn update_avro_value<T: Serialize>(
5512        &self,
5513        update_name: &str,
5514        input: T,
5515        request_id: Option<&str>,
5516    ) -> Result<AvroValue> {
5517        self.client
5518            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5519            .await
5520    }
5521
5522    /// Query only if this handle's selected run is still current.
5523    pub async fn query_selected_run<T: Serialize>(
5524        &self,
5525        query_name: &str,
5526        input: T,
5527    ) -> Result<Value> {
5528        let run_id = self
5529            .run_id
5530            .as_deref()
5531            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5532        self.client
5533            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5534            .await
5535    }
5536
5537    /// Await the final terminal outcome of the current continue-as-new chain.
5538    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5539        self.result_target(options, None).await
5540    }
5541
5542    /// Await the final result without projecting Avro bytes through JSON.
5543    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5544        self.result_avro_value_target(options, None).await
5545    }
5546
5547    /// Await the final result and decode it into a Serde application type.
5548    pub async fn result_typed<T: DeserializeOwned>(
5549        &self,
5550        options: WorkflowResultOptions,
5551    ) -> Result<T> {
5552        let result = self.result_avro_value(options).await?;
5553        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5554    }
5555
5556    /// Await only the run identity originally selected by this handle.
5557    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5558        let run_id = self.run_id.as_deref().ok_or_else(|| {
5559            Error::Codec("run_id is required for selected-run result".to_string())
5560        })?;
5561        self.result_target(options, Some(run_id)).await
5562    }
5563
5564    /// Await the selected run's result on the lossless Avro Value surface.
5565    pub async fn result_selected_run_avro_value(
5566        &self,
5567        options: WorkflowResultOptions,
5568    ) -> Result<AvroValue> {
5569        let run_id = self.run_id.as_deref().ok_or_else(|| {
5570            Error::Codec("run_id is required for selected-run result".to_string())
5571        })?;
5572        self.result_avro_value_target(options, Some(run_id)).await
5573    }
5574
5575    /// Await the selected run and decode its result into a Serde type.
5576    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5577        &self,
5578        options: WorkflowResultOptions,
5579    ) -> Result<T> {
5580        let result = self.result_selected_run_avro_value(options).await?;
5581        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5582    }
5583
5584    async fn result_avro_value_target(
5585        &self,
5586        options: WorkflowResultOptions,
5587        selected_run_id: Option<&str>,
5588    ) -> Result<AvroValue> {
5589        let started = Instant::now();
5590
5591        loop {
5592            let description = match selected_run_id {
5593                Some(run_id) => {
5594                    self.client
5595                        .describe_workflow_run(&self.workflow_id, run_id)
5596                        .await?
5597                }
5598                None => self.describe().await?,
5599            };
5600            if description.is_completed() {
5601                return description.output_avro_value.ok_or_else(|| {
5602                    Error::Codec(
5603                        "missing_payload_envelope: typed workflow result requires output_envelope"
5604                            .to_string(),
5605                    )
5606                });
5607            }
5608            if description.is_terminal() {
5609                let outcome =
5610                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5611                return Err(match outcome.kind {
5612                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5613                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5614                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5615                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5616                });
5617            }
5618            if started.elapsed() >= options.timeout {
5619                return Err(Error::Timeout);
5620            }
5621            tokio::time::sleep(options.poll_interval).await;
5622        }
5623    }
5624
5625    async fn result_target(
5626        &self,
5627        options: WorkflowResultOptions,
5628        selected_run_id: Option<&str>,
5629    ) -> Result<Value> {
5630        let started = Instant::now();
5631
5632        loop {
5633            let description = match selected_run_id {
5634                Some(run_id) => {
5635                    self.client
5636                        .describe_workflow_run(&self.workflow_id, run_id)
5637                        .await?
5638                }
5639                None => self.describe().await?,
5640            };
5641            if description.is_completed() {
5642                return Ok(description.output.unwrap_or(Value::Null));
5643            }
5644
5645            if description.is_terminal() {
5646                let outcome =
5647                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5648                return Err(match outcome.kind {
5649                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5650                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5651                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5652                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5653                });
5654            }
5655
5656            if started.elapsed() >= options.timeout {
5657                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5658                    kind: WorkflowTerminalKind::TimedOut,
5659                    workflow_id: description
5660                        .workflow_id
5661                        .clone()
5662                        .unwrap_or_else(|| self.workflow_id.clone()),
5663                    run_id: description
5664                        .run_id
5665                        .clone()
5666                        .or_else(|| selected_run_id.map(str::to_string)),
5667                    reason: "result_wait_timeout".to_string(),
5668                    failure_category: Some("client_timeout".to_string()),
5669                    failure_id: None,
5670                    exception_type: None,
5671                    exception_class: None,
5672                    non_retryable: None,
5673                    message: Some(format!(
5674                        "workflow result was not terminal within {:?}",
5675                        options.timeout
5676                    )),
5677                    exception: None,
5678                    raw: description.raw_value(),
5679                }));
5680            }
5681
5682            tokio::time::sleep(options.poll_interval).await;
5683        }
5684    }
5685}
5686
5687#[derive(Clone, Copy, Debug)]
5688pub struct WorkflowResultOptions {
5689    pub poll_interval: Duration,
5690    pub timeout: Duration,
5691}
5692
5693impl Default for WorkflowResultOptions {
5694    fn default() -> Self {
5695        Self {
5696            poll_interval: Duration::from_millis(500),
5697            timeout: Duration::from_secs(30),
5698        }
5699    }
5700}
5701
5702#[derive(Clone, Debug, Deserialize)]
5703pub struct WorkflowDescription {
5704    pub workflow_id: Option<String>,
5705    pub run_id: Option<String>,
5706    pub workflow_type: Option<String>,
5707    pub status: Option<String>,
5708    #[serde(default)]
5709    pub closed_reason: Option<String>,
5710    #[serde(default)]
5711    pub error: Option<String>,
5712    #[serde(default)]
5713    pub failure: Option<Value>,
5714    #[serde(default)]
5715    pub exception: Option<Value>,
5716    #[serde(default)]
5717    pub failures: Vec<Value>,
5718    #[serde(default)]
5719    pub output: Option<Value>,
5720    #[serde(default)]
5721    pub output_envelope: Option<Value>,
5722    #[serde(skip)]
5723    pub output_avro_value: Option<AvroValue>,
5724    #[serde(flatten)]
5725    pub raw: HashMap<String, Value>,
5726}
5727
5728/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5729#[derive(Clone, Debug, Deserialize)]
5730pub struct WorkflowStreamDescription {
5731    pub stream_name: String,
5732    pub status: String,
5733    pub last_offset: i64,
5734    pub total_items: u64,
5735    pub pending_items: u64,
5736    #[serde(default)]
5737    pub opened_at: Option<String>,
5738    #[serde(default)]
5739    pub last_appended_at: Option<String>,
5740    #[serde(default)]
5741    pub closed_at: Option<String>,
5742    #[serde(default)]
5743    pub error_reason: Option<String>,
5744    #[serde(default)]
5745    pub retention_seconds: Option<u64>,
5746    #[serde(flatten)]
5747    pub raw: HashMap<String, Value>,
5748}
5749
5750impl WorkflowStreamDescription {
5751    pub fn is_terminal(&self) -> bool {
5752        matches!(self.status.as_str(), "closed" | "errored")
5753    }
5754}
5755
5756/// One item for direct or replay-safe append.
5757#[derive(Clone, Debug, Default)]
5758pub struct WorkflowStreamAppendItem {
5759    pub payload_envelope: Option<Value>,
5760    pub payload_reference: Option<String>,
5761    pub item_type: Option<String>,
5762    pub content_type: Option<String>,
5763    pub idempotency_key: Option<String>,
5764}
5765
5766impl WorkflowStreamAppendItem {
5767    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5768    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5769        let value = AvroValue::from_serialize(&payload)?;
5770        Ok(Self {
5771            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5772            ..Self::default()
5773        })
5774    }
5775
5776    /// Preserve an external payload URI as an opaque service-contract reference.
5777    pub fn from_reference(reference: impl Into<String>) -> Self {
5778        Self {
5779            payload_reference: Some(reference.into()),
5780            ..Self::default()
5781        }
5782    }
5783
5784    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5785        self.item_type = Some(item_type.into());
5786        self
5787    }
5788
5789    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5790        self.content_type = Some(content_type.into());
5791        self
5792    }
5793
5794    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5795        self.idempotency_key = Some(idempotency_key.into());
5796        self
5797    }
5798
5799    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5800        let mut item = serde_json::Map::new();
5801        if let Some(payload) = &self.payload_envelope {
5802            item.insert("payload".to_string(), payload.clone());
5803            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5804        }
5805        if let Some(reference) = &self.payload_reference {
5806            item.insert("payload_reference".to_string(), json!(reference));
5807        }
5808        if let Some(item_type) = &self.item_type {
5809            item.insert("item_type".to_string(), json!(item_type));
5810        }
5811        if let Some(content_type) = &self.content_type {
5812            item.insert("content_type".to_string(), json!(content_type));
5813        }
5814        if let Some(key) = derived_idempotency_key
5815            .as_ref()
5816            .or(self.idempotency_key.as_ref())
5817        {
5818            item.insert("idempotency_key".to_string(), json!(key));
5819        }
5820        Value::Object(item)
5821    }
5822}
5823
5824/// One durable item at its stable zero-based offset.
5825#[derive(Clone, Debug)]
5826pub struct WorkflowStreamItem {
5827    pub offset: u64,
5828    pub payload: Option<Value>,
5829    pub payload_envelope: Option<Value>,
5830    pub payload_reference: Option<String>,
5831    pub payload_codec: Option<String>,
5832    pub idempotency_key: Option<String>,
5833    pub item_type: Option<String>,
5834    pub content_type: Option<String>,
5835    pub origin: Option<String>,
5836    pub origin_reference: Option<String>,
5837    pub emitted_at: Option<String>,
5838    pub raw: Value,
5839}
5840
5841/// One bounded at-least-once subscription page.
5842#[derive(Clone, Debug)]
5843pub struct WorkflowStreamPage {
5844    pub stream: WorkflowStreamDescription,
5845    pub items: Vec<WorkflowStreamItem>,
5846    pub next_offset: u64,
5847    pub terminal: bool,
5848}
5849
5850/// Durable acceptance and deduplication outcome for an append request.
5851#[derive(Clone, Debug)]
5852pub struct WorkflowStreamAppendResult {
5853    pub stream: WorkflowStreamDescription,
5854    pub accepted_offsets: Vec<u64>,
5855    pub accepted: u64,
5856    pub deduped: u64,
5857}
5858
5859#[derive(Deserialize)]
5860struct WorkflowStreamListResponse {
5861    #[serde(default)]
5862    streams: Vec<WorkflowStreamDescription>,
5863}
5864
5865#[derive(Deserialize)]
5866struct WorkflowStreamDescriptionResponse {
5867    stream: WorkflowStreamDescription,
5868}
5869
5870#[derive(Deserialize)]
5871struct WorkflowStreamPageResponse {
5872    stream: WorkflowStreamDescription,
5873    #[serde(default)]
5874    items: Vec<Value>,
5875    next_offset: u64,
5876    terminal: bool,
5877}
5878
5879#[derive(Deserialize)]
5880struct WorkflowStreamAppendResponse {
5881    stream: WorkflowStreamDescription,
5882    #[serde(default)]
5883    accepted_offsets: Vec<u64>,
5884    accepted: u64,
5885    deduped: u64,
5886}
5887
5888impl WorkflowDescription {
5889    pub fn is_completed(&self) -> bool {
5890        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5891    }
5892
5893    pub fn is_terminal(&self) -> bool {
5894        matches!(
5895            self.status.as_deref(),
5896            Some(
5897                "completed"
5898                    | "Completed"
5899                    | "failed"
5900                    | "Failed"
5901                    | "cancelled"
5902                    | "Cancelled"
5903                    | "terminated"
5904                    | "Terminated"
5905                    | "timed_out"
5906                    | "TimedOut",
5907            )
5908        )
5909    }
5910
5911    fn decode_payloads(&mut self) -> Result<()> {
5912        if let Some(envelope) = &self.output_envelope {
5913            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5914            self.output = Some(value.clone().into_json()?);
5915            self.output_avro_value = Some(value);
5916        }
5917
5918        Ok(())
5919    }
5920
5921    fn raw_value(&self) -> Value {
5922        let mut data = self.raw.clone();
5923        data.insert(
5924            "workflow_id".to_string(),
5925            self.workflow_id
5926                .clone()
5927                .map(Value::String)
5928                .unwrap_or(Value::Null),
5929        );
5930        data.insert(
5931            "run_id".to_string(),
5932            self.run_id
5933                .clone()
5934                .map(Value::String)
5935                .unwrap_or(Value::Null),
5936        );
5937        data.insert(
5938            "workflow_type".to_string(),
5939            self.workflow_type
5940                .clone()
5941                .map(Value::String)
5942                .unwrap_or(Value::Null),
5943        );
5944        data.insert(
5945            "status".to_string(),
5946            self.status
5947                .clone()
5948                .map(Value::String)
5949                .unwrap_or(Value::Null),
5950        );
5951        data.insert(
5952            "closed_reason".to_string(),
5953            self.closed_reason
5954                .clone()
5955                .map(Value::String)
5956                .unwrap_or(Value::Null),
5957        );
5958        if let Some(failure) = &self.failure {
5959            data.insert("failure".to_string(), failure.clone());
5960        }
5961        if let Some(exception) = &self.exception {
5962            data.insert("exception".to_string(), exception.clone());
5963        }
5964        Value::Object(data.into_iter().collect())
5965    }
5966}
5967
5968fn workflow_terminal_outcome(
5969    description: &WorkflowDescription,
5970    workflow_id: &str,
5971    run_id: Option<&str>,
5972) -> WorkflowTerminalOutcome {
5973    let terminal_kind = description
5974        .closed_reason
5975        .as_deref()
5976        .or(description.status.as_deref())
5977        .unwrap_or("failed")
5978        .to_ascii_lowercase();
5979    let kind = match terminal_kind.as_str() {
5980        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
5981        "terminated" => WorkflowTerminalKind::Terminated,
5982        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
5983        _ => WorkflowTerminalKind::Failed,
5984    };
5985    let default_reason = match kind {
5986        WorkflowTerminalKind::Failed => "workflow_failed",
5987        WorkflowTerminalKind::Cancelled => "cancelled",
5988        WorkflowTerminalKind::Terminated => "terminated",
5989        WorkflowTerminalKind::TimedOut => "timed_out",
5990    };
5991    let failure = description
5992        .failure
5993        .as_ref()
5994        .filter(|value| value.is_object());
5995    let nested_failure = failure
5996        .and_then(|value| value.get("failures"))
5997        .and_then(Value::as_array)
5998        .and_then(|failures| failures.last())
5999        .or_else(|| description.failures.last());
6000    let exception = description
6001        .exception
6002        .clone()
6003        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6004        .or_else(|| {
6005            nested_failure
6006                .and_then(|value| value.get("exception_payload"))
6007                .cloned()
6008        });
6009    let string_field = |name: &str| {
6010        failure
6011            .and_then(|value| value.get(name))
6012            .and_then(Value::as_str)
6013            .or_else(|| {
6014                nested_failure
6015                    .and_then(|value| value.get(name))
6016                    .and_then(Value::as_str)
6017            })
6018            .map(str::to_string)
6019    };
6020    let exception_field = |name: &str| {
6021        exception
6022            .as_ref()
6023            .and_then(|value| value.get(name))
6024            .and_then(Value::as_str)
6025            .map(str::to_string)
6026    };
6027    let message = description
6028        .error
6029        .clone()
6030        .or_else(|| string_field("message"))
6031        .or_else(|| exception_field("message"));
6032    let reason = description
6033        .raw
6034        .get("reason")
6035        .and_then(Value::as_str)
6036        .map(str::to_string)
6037        .or_else(|| {
6038            failure
6039                .and_then(|value| value.get("reason"))
6040                .and_then(Value::as_str)
6041                .map(str::to_string)
6042        })
6043        .or_else(|| description.closed_reason.clone())
6044        .unwrap_or_else(|| default_reason.to_string());
6045    let failure_id = string_field("failure_id").or_else(|| {
6046        nested_failure
6047            .and_then(|value| value.get("id"))
6048            .and_then(Value::as_str)
6049            .map(str::to_string)
6050    });
6051
6052    WorkflowTerminalOutcome {
6053        kind,
6054        workflow_id: description
6055            .workflow_id
6056            .clone()
6057            .unwrap_or_else(|| workflow_id.to_string()),
6058        run_id: description
6059            .run_id
6060            .clone()
6061            .or_else(|| run_id.map(str::to_string)),
6062        reason,
6063        failure_category: string_field("failure_category")
6064            .or_else(|| Some(default_reason.to_string())),
6065        failure_id,
6066        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6067        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6068        non_retryable: failure
6069            .and_then(|value| value.get("non_retryable"))
6070            .and_then(Value::as_bool)
6071            .or_else(|| {
6072                nested_failure
6073                    .and_then(|value| value.get("non_retryable"))
6074                    .and_then(Value::as_bool)
6075            }),
6076        message,
6077        exception,
6078        raw: description.raw_value(),
6079    }
6080}
6081
6082#[derive(Clone, Debug, Deserialize)]
6083pub struct RegisterWorkerResponse {
6084    pub worker_id: String,
6085    pub registered: bool,
6086    #[serde(default)]
6087    pub heartbeat_interval_seconds: Option<u64>,
6088    #[serde(default)]
6089    pub protocol_version: Option<String>,
6090    #[serde(default)]
6091    pub server_capabilities: Option<Value>,
6092}
6093
6094/// Result of gracefully removing a worker-plane registration.
6095#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6096pub struct WorkerDeregistrationEnvelope {
6097    pub worker_id: String,
6098    pub outcome: String,
6099    pub recovered_workflow_task_count: u64,
6100}
6101
6102#[derive(Clone, Debug, Deserialize)]
6103pub struct PollWorkflowTaskResponse {
6104    #[serde(default)]
6105    pub task: Option<WorkflowTask>,
6106    #[serde(default)]
6107    pub poll_status: Option<String>,
6108    #[serde(default)]
6109    pub reason: Option<String>,
6110    #[serde(default)]
6111    pub protocol_version: Option<String>,
6112    #[serde(default)]
6113    pub server_capabilities: Option<Value>,
6114}
6115
6116impl PollWorkflowTaskResponse {
6117    /// Classify this response without parsing server display text.
6118    pub fn outcome(&self) -> WorkerPollOutcome {
6119        worker_poll_outcome(
6120            self.task.is_some(),
6121            self.poll_status.as_deref(),
6122            self.reason.as_deref(),
6123        )
6124    }
6125}
6126
6127fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6128    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6129        return false;
6130    };
6131    let supported = capabilities
6132        .get("workflow_memo_updates")
6133        .and_then(Value::as_object)
6134        .and_then(|memo| memo.get("supported"))
6135        .and_then(Value::as_bool)
6136        == Some(true);
6137    let command_advertised = capabilities
6138        .get("supported_workflow_task_commands")
6139        .and_then(Value::as_array)
6140        .is_some_and(|commands| {
6141            commands
6142                .iter()
6143                .any(|command| command.as_str() == Some("upsert_memo"))
6144        });
6145    supported && command_advertised
6146}
6147
6148fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6149    commands
6150        .iter()
6151        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6152}
6153
6154#[derive(Clone, Debug, Deserialize)]
6155pub struct PollActivityTaskResponse {
6156    #[serde(default)]
6157    pub task: Option<ActivityTask>,
6158    #[serde(default)]
6159    pub poll_status: Option<String>,
6160    #[serde(default)]
6161    pub reason: Option<String>,
6162}
6163
6164impl PollActivityTaskResponse {
6165    /// Classify this response without parsing server display text.
6166    pub fn outcome(&self) -> WorkerPollOutcome {
6167        worker_poll_outcome(
6168            self.task.is_some(),
6169            self.poll_status.as_deref(),
6170            self.reason.as_deref(),
6171        )
6172    }
6173}
6174
6175#[derive(Clone, Debug, Deserialize)]
6176pub struct PollQueryTaskResponse {
6177    #[serde(default)]
6178    pub task: Option<QueryTask>,
6179    #[serde(default)]
6180    pub poll_status: Option<String>,
6181    #[serde(default)]
6182    pub reason: Option<String>,
6183}
6184
6185impl PollQueryTaskResponse {
6186    /// Classify this response without parsing server display text.
6187    pub fn outcome(&self) -> WorkerPollOutcome {
6188        worker_poll_outcome(
6189            self.task.is_some(),
6190            self.poll_status.as_deref(),
6191            self.reason.as_deref(),
6192        )
6193    }
6194}
6195
6196/// Stable classification for worker poll responses.
6197#[derive(Clone, Debug, PartialEq, Eq)]
6198pub enum WorkerPollOutcome {
6199    /// A task was leased and is available on the response.
6200    Task,
6201    /// No task was leased, but the worker should continue polling.
6202    Idle {
6203        poll_status: Option<String>,
6204        reason: Option<String>,
6205    },
6206    /// The server asked this worker to stop claiming new work.
6207    Stop {
6208        poll_status: Option<String>,
6209        reason: Option<String>,
6210    },
6211}
6212
6213impl WorkerPollOutcome {
6214    pub fn should_stop(&self) -> bool {
6215        matches!(self, Self::Stop { .. })
6216    }
6217}
6218
6219fn worker_poll_outcome(
6220    has_task: bool,
6221    poll_status: Option<&str>,
6222    reason: Option<&str>,
6223) -> WorkerPollOutcome {
6224    if worker_poll_is_stop(poll_status, reason) {
6225        return WorkerPollOutcome::Stop {
6226            poll_status: poll_status.map(str::to_string),
6227            reason: reason.map(str::to_string),
6228        };
6229    }
6230
6231    if has_task {
6232        WorkerPollOutcome::Task
6233    } else {
6234        WorkerPollOutcome::Idle {
6235            poll_status: poll_status.map(str::to_string),
6236            reason: reason.map(str::to_string),
6237        }
6238    }
6239}
6240
6241/// An ephemeral server-routed query task.
6242#[derive(Clone, Debug, Deserialize)]
6243pub struct QueryTask {
6244    pub query_task_id: String,
6245    #[serde(default = "default_workflow_task_attempt")]
6246    pub query_task_attempt: u64,
6247    #[serde(default)]
6248    pub lease_owner: Option<String>,
6249    #[serde(default)]
6250    pub workflow_id: Option<String>,
6251    #[serde(default)]
6252    pub run_id: Option<String>,
6253    pub workflow_type: String,
6254    pub query_name: String,
6255    #[serde(
6256        default = "missing_task_payload_codec",
6257        deserialize_with = "deserialize_task_payload_codec"
6258    )]
6259    pub payload_codec: String,
6260    #[serde(default)]
6261    pub workflow_arguments: Option<Value>,
6262    #[serde(default)]
6263    pub query_arguments: Option<Value>,
6264    #[serde(default)]
6265    pub history_events: Vec<HistoryEvent>,
6266    #[serde(default)]
6267    pub history_export: Option<Value>,
6268    #[serde(default)]
6269    pub run_status: Option<String>,
6270}
6271
6272#[derive(Clone, Debug, Deserialize)]
6273pub struct WorkflowTask {
6274    pub task_id: String,
6275    #[serde(default)]
6276    pub workflow_command_id: Option<String>,
6277    #[serde(default)]
6278    pub workflow_id: Option<String>,
6279    #[serde(default)]
6280    pub run_id: Option<String>,
6281    pub workflow_type: String,
6282    #[serde(default)]
6283    pub cancel_requested: bool,
6284    #[serde(
6285        default = "missing_task_payload_codec",
6286        deserialize_with = "deserialize_task_payload_codec"
6287    )]
6288    pub payload_codec: String,
6289    #[serde(default)]
6290    pub arguments: Option<Value>,
6291    #[serde(default)]
6292    pub history_events: Vec<HistoryEvent>,
6293    #[serde(default)]
6294    pub total_history_events: Option<u64>,
6295    #[serde(default)]
6296    pub history_size_bytes: Option<u64>,
6297    #[serde(default)]
6298    pub continue_as_new_recommended: Option<bool>,
6299    #[serde(default)]
6300    pub history_budget_pressure: Option<String>,
6301    #[serde(default)]
6302    pub next_history_page_token: Option<String>,
6303    #[serde(default = "default_workflow_task_attempt")]
6304    pub workflow_task_attempt: u64,
6305    #[serde(default)]
6306    pub workflow_signal_id: Option<String>,
6307    #[serde(default)]
6308    pub signal_name: Option<String>,
6309    #[serde(default)]
6310    pub signal_arguments: Option<Value>,
6311    #[serde(default)]
6312    pub workflow_update_id: Option<String>,
6313    #[serde(default)]
6314    pub update_name: Option<String>,
6315    #[serde(default)]
6316    pub lease_owner: Option<String>,
6317}
6318
6319impl WorkflowTask {
6320    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6321        self.history_events.extend(page.history_events);
6322
6323        if page.total_history_events.is_some() {
6324            self.total_history_events = page.total_history_events;
6325        }
6326
6327        self.next_history_page_token = page
6328            .next_history_page_token
6329            .filter(|token| !token.is_empty());
6330    }
6331}
6332
6333#[derive(Clone, Debug, Deserialize)]
6334struct WorkflowTaskHistoryPage {
6335    #[serde(default)]
6336    history_events: Vec<HistoryEvent>,
6337    #[serde(default)]
6338    total_history_events: Option<u64>,
6339    #[serde(default)]
6340    next_history_page_token: Option<String>,
6341}
6342
6343#[derive(Clone, Debug, Deserialize)]
6344pub struct ActivityTask {
6345    pub task_id: String,
6346    #[serde(default)]
6347    pub activity_attempt_id: Option<String>,
6348    #[serde(default)]
6349    pub attempt_id: Option<String>,
6350    pub activity_type: String,
6351    #[serde(
6352        default = "missing_task_payload_codec",
6353        deserialize_with = "deserialize_task_payload_codec"
6354    )]
6355    pub payload_codec: String,
6356    #[serde(default)]
6357    pub arguments: Option<Value>,
6358    #[serde(default = "default_attempt_number")]
6359    pub attempt_number: u64,
6360    #[serde(default)]
6361    pub lease_owner: Option<String>,
6362}
6363
6364#[derive(Clone, Debug, Serialize, Deserialize)]
6365pub struct HistoryEvent {
6366    #[serde(alias = "type")]
6367    pub event_type: String,
6368    #[serde(default)]
6369    pub payload: Value,
6370    #[serde(flatten)]
6371    pub raw: HashMap<String, Value>,
6372}
6373
6374/// One decoded signal in the committed workflow-history snapshot.
6375#[derive(Clone, Debug, PartialEq)]
6376pub struct QuerySignal {
6377    pub id: Option<String>,
6378    pub name: String,
6379    pub arguments: Vec<Value>,
6380    avro_arguments: Vec<AvroValue>,
6381    pub workflow_sequence: Option<u64>,
6382}
6383
6384impl QuerySignal {
6385    /// Lossless fixed Avro Value arguments for this committed signal.
6386    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6387        &self.avro_arguments
6388    }
6389}
6390
6391/// Immutable state supplied to a registered query handler.
6392///
6393/// This context intentionally exposes no activity, signal-wait, or command
6394/// APIs. Query handlers inspect committed history and return a value; query
6395/// completion does not append an event or advance deterministic execution.
6396#[derive(Clone, Debug)]
6397pub struct QueryContext {
6398    pub workflow_id: Option<String>,
6399    pub run_id: Option<String>,
6400    pub workflow_type: String,
6401    pub run_status: Option<String>,
6402    workflow_input: Value,
6403    workflow_input_avro_value: AvroValue,
6404    history_events: Arc<Vec<HistoryEvent>>,
6405    signal_events: Arc<Vec<QuerySignal>>,
6406}
6407
6408impl QueryContext {
6409    /// The normalized argument list used to start the workflow.
6410    pub fn workflow_input(&self) -> &Value {
6411        &self.workflow_input
6412    }
6413
6414    /// The lossless fixed Avro Value argument list used to start the workflow.
6415    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6416        &self.workflow_input_avro_value
6417    }
6418
6419    /// The immutable committed history used for this query snapshot.
6420    pub fn history_events(&self) -> &[HistoryEvent] {
6421        self.history_events.as_slice()
6422    }
6423
6424    /// All decoded signals in committed workflow order.
6425    pub fn signal_events(&self) -> &[QuerySignal] {
6426        self.signal_events.as_slice()
6427    }
6428
6429    /// Decoded argument lists for each committed signal with `signal_name`.
6430    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6431        self.signal_events
6432            .iter()
6433            .filter(|signal| signal.name == signal_name)
6434            .map(|signal| signal.arguments.clone())
6435            .collect()
6436    }
6437
6438    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6439    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6440        self.signal_events
6441            .iter()
6442            .filter(|signal| signal.name == signal_name)
6443            .map(|signal| signal.avro_arguments.clone())
6444            .collect()
6445    }
6446}
6447
6448#[derive(Clone, Debug, Deserialize)]
6449pub struct ActivityHeartbeatResponse {
6450    #[serde(default)]
6451    pub cancel_requested: bool,
6452    #[serde(default)]
6453    pub heartbeat_recorded: bool,
6454    #[serde(default)]
6455    pub can_continue: Option<bool>,
6456    #[serde(default)]
6457    pub reason: Option<String>,
6458    #[serde(default)]
6459    pub run_closed_reason: Option<String>,
6460    #[serde(default)]
6461    pub run_closed_at: Option<String>,
6462    #[serde(default)]
6463    pub lease_expires_at: Option<String>,
6464    #[serde(default)]
6465    pub last_heartbeat_at: Option<String>,
6466}
6467
6468impl ActivityHeartbeatResponse {
6469    /// Whether the activity should stop instead of attempting completion.
6470    pub fn should_stop(&self) -> bool {
6471        self.cancel_requested || self.can_continue == Some(false)
6472    }
6473}
6474
6475fn missing_task_payload_codec() -> String {
6476    MISSING_TASK_PAYLOAD_CODEC.to_string()
6477}
6478
6479fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6480where
6481    D: Deserializer<'de>,
6482{
6483    Ok(match Value::deserialize(deserializer)? {
6484        Value::String(codec) => codec,
6485        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6486        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6487    })
6488}
6489
6490fn default_workflow_task_attempt() -> u64 {
6491    1
6492}
6493
6494fn default_attempt_number() -> u64 {
6495    1
6496}
6497
6498type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6499type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6500type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6501type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6502type ReplayedWorkflowHandler =
6503    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6504type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6505type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6506type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6507type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6508type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6509type ReplayedQueryHandler = Arc<
6510    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6511        + Send
6512        + Sync,
6513>;
6514type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6515
6516struct ReplayedWorkflowInvocation {
6517    future: WorkflowFuture,
6518    snapshot: WorkflowStateSnapshot,
6519}
6520
6521#[derive(Clone)]
6522struct RegisteredWorkflow {
6523    execute: WorkflowHandler,
6524    replay: Option<ReplayedWorkflowHandler>,
6525    state_type: Option<TypeId>,
6526    definition_fingerprint: Option<String>,
6527}
6528
6529fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6530    names
6531        .iter()
6532        .map(|name| {
6533            json!({
6534                "name": name,
6535                "parameters": [{
6536                    "name": "args",
6537                    "position": 0,
6538                    "required": false,
6539                    "variadic": true,
6540                    "type": null,
6541                    "allows_null": true,
6542                    "default_available": false,
6543                    "default": null,
6544                }],
6545            })
6546        })
6547        .collect()
6548}
6549
6550#[derive(Debug)]
6551struct WorkflowTaskDecision {
6552    commands: Vec<Value>,
6553    message_stream_cursors: Vec<Value>,
6554    message_stream_waits: Vec<Value>,
6555    cancellation_delivery: Option<CancellationDelivery>,
6556    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6557    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6558}
6559
6560enum PreparedWorkflowTask {
6561    Decision(WorkflowTaskDecision),
6562    Execution {
6563        task: WorkflowTask,
6564        context: WorkflowContext,
6565        future: WorkflowFuture,
6566    },
6567}
6568
6569impl WorkflowTaskDecision {
6570    fn without_message_streams(commands: Vec<Value>) -> Self {
6571        Self {
6572            commands,
6573            message_stream_cursors: Vec::new(),
6574            message_stream_waits: Vec::new(),
6575            cancellation_delivery: None,
6576            cancellation_scope_opening: None,
6577            cancellation_scope_delivery: None,
6578        }
6579    }
6580}
6581
6582#[derive(Clone)]
6583enum RegisteredQuery {
6584    Snapshot(QueryHandler),
6585    Replayed {
6586        state_type: TypeId,
6587        handler: ReplayedQueryHandler,
6588    },
6589}
6590
6591#[derive(Clone, Debug)]
6592pub struct WorkerHeartbeatObservation {
6593    pub worker_id: String,
6594    pub task_queue: String,
6595    pub acknowledged_at_unix_millis: u64,
6596    pub acknowledgement: Value,
6597}
6598
6599/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6600///
6601/// Expected empty long polls and explicit Server capacity backpressure are
6602/// normal worker states. Capacity backpressure honors the advertised retry
6603/// delay without consuming this retry budget. Other transport failures,
6604/// retryable HTTP 408/429 responses, and server errors are retried with capped
6605/// exponential backoff. Authentication, protocol, codec, and handler failures
6606/// are never retried by the worker.
6607/// Explicit storage admission pauses also preserve the already-serialized worker
6608/// request without consuming this budget or rerunning its handler. The delay is
6609/// capped by `max_backoff`, and shutdown interrupts storage waits.
6610/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6611/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6612/// and `max_retries = 0` disables ordinary retries in either mode.
6613#[derive(Clone, Copy, Debug)]
6614pub struct WorkerRetryPolicy {
6615    /// Number of retries after the initial request fails.
6616    pub max_retries: usize,
6617    /// Delay before the first retry.
6618    pub initial_backoff: Duration,
6619    /// Maximum delay between retries.
6620    pub max_backoff: Duration,
6621}
6622
6623impl Default for WorkerRetryPolicy {
6624    fn default() -> Self {
6625        Self {
6626            max_retries: 5,
6627            initial_backoff: Duration::from_millis(100),
6628            max_backoff: Duration::from_secs(5),
6629        }
6630    }
6631}
6632
6633#[derive(Clone, Debug)]
6634struct WorkerStorageAdmission {
6635    policy: WorkerRetryPolicy,
6636    stop: Arc<AtomicBool>,
6637}
6638
6639struct StopWorkerOnDrop(Arc<AtomicBool>);
6640
6641impl Drop for StopWorkerOnDrop {
6642    fn drop(&mut self) {
6643        self.0.store(true, Ordering::SeqCst);
6644    }
6645}
6646
6647async fn wait_for_worker_stop(stop: &AtomicBool) {
6648    while !stop.load(Ordering::SeqCst) {
6649        tokio::time::sleep(Duration::from_millis(100)).await;
6650    }
6651}
6652
6653#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6654enum ManagedPollOutcome {
6655    Idle,
6656    Handled,
6657    Stop,
6658}
6659
6660#[derive(Clone)]
6661pub struct Worker {
6662    client: Client,
6663    worker_id: String,
6664    task_queue: String,
6665    workflows: HashMap<String, RegisteredWorkflow>,
6666    activities: HashMap<String, ActivityHandler>,
6667    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6668    signals: HashMap<String, Vec<String>>,
6669    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6670    registration_definitions:
6671        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6672    registration_error: Option<DuplicateRegistrationError>,
6673    max_concurrent_workflow_tasks: usize,
6674    max_concurrent_activity_tasks: usize,
6675    poll_timeout: Duration,
6676    heartbeat_interval: Duration,
6677    retry_policy: WorkerRetryPolicy,
6678    recover_transient_outages: bool,
6679    run_stop: Option<Arc<AtomicBool>>,
6680    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6681    cooperative_cancellation_enabled: bool,
6682    allow_cancellation_scope_authoring: bool,
6683    allow_cancellation_scope_delivery: bool,
6684    cooperative_registration_confirmed: Arc<AtomicBool>,
6685    local_registration_confirmed: Arc<AtomicBool>,
6686    session_registration_confirmed: Arc<AtomicBool>,
6687    sticky_registration_confirmed: Arc<AtomicBool>,
6688    resource_capabilities: Vec<String>,
6689    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6690}
6691
6692impl Worker {
6693    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6694        Self {
6695            client,
6696            worker_id: default_worker_id(),
6697            task_queue: task_queue.into(),
6698            workflows: HashMap::new(),
6699            activities: HashMap::new(),
6700            queries: HashMap::new(),
6701            signals: HashMap::new(),
6702            updates: HashMap::new(),
6703            registration_definitions: HashMap::new(),
6704            registration_error: None,
6705            max_concurrent_workflow_tasks: 10,
6706            max_concurrent_activity_tasks: 10,
6707            poll_timeout: Duration::from_secs(30),
6708            heartbeat_interval: Duration::from_secs(60),
6709            retry_policy: WorkerRetryPolicy::default(),
6710            recover_transient_outages: false,
6711            run_stop: None,
6712            heartbeat_observer: None,
6713            cooperative_cancellation_enabled: false,
6714            allow_cancellation_scope_authoring: false,
6715            allow_cancellation_scope_delivery: false,
6716            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6717            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6718            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6719            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6720            resource_capabilities: Vec::new(),
6721            sessions: Arc::new(Mutex::new(HashMap::new())),
6722        }
6723    }
6724
6725    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6726        self.worker_id = worker_id.into();
6727        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6728        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6729        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6730        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6731        self.client.reset_sticky_cache();
6732        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6733        self
6734    }
6735
6736    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6737        self.poll_timeout = timeout;
6738        self
6739    }
6740
6741    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6742        self.heartbeat_interval = interval;
6743        self
6744    }
6745
6746    /// Explicitly enable inline local activities in this workflow worker.
6747    ///
6748    /// The worker advertises the capability to Server only when enabled.
6749    /// These callbacks must yield to Tokio and have idempotent side effects.
6750    /// Cooperative prepared local supervision is a separate capability.
6751    pub fn local_activities(mut self, enabled: bool) -> Self {
6752        self.client.local_activities_enabled = enabled;
6753        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6754        self
6755    }
6756
6757    /// Opt in to separate cooperative workflow cancellation requests.
6758    ///
6759    /// Registration requires the Server to acknowledge this exact worker,
6760    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6761    /// processing uses canonical delivery and activity ownership fences.
6762    /// Existing terminal cancel and terminate operations remain terminal.
6763    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6764    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6765    /// and [`Worker::run_until`] register automatically.
6766    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6767        self.cooperative_cancellation_enabled = enabled;
6768        self.client.cooperative_worker_protocol = enabled;
6769        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6770        self
6771    }
6772
6773    /// Enable candidate scope authoring without advertising scoped execution.
6774    #[doc(hidden)]
6775    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6776        self.allow_cancellation_scope_authoring = enabled;
6777        self
6778    }
6779
6780    /// Enable the candidate scoped call consumer with canonical authoring.
6781    #[doc(hidden)]
6782    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6783        self.allow_cancellation_scope_delivery = enabled;
6784        self
6785    }
6786
6787    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6788    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6789        self.retry_policy = policy;
6790        self
6791    }
6792
6793    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6794    ///
6795    /// Retries preserve the poll request identity and use capped exponential
6796    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6797    /// An in-flight poll is allowed to finish so leased work is not discarded.
6798    /// Authentication, protocol, codec, handler and task settlement failures
6799    /// remain errors. Registration and deregistration are not retried here.
6800    ///
6801    /// The default is disabled, preserving the bounded retry contract.
6802    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6803    /// even when this option is enabled.
6804    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6805        self.recover_transient_outages = enabled;
6806        self
6807    }
6808
6809    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6810    where
6811        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6812    {
6813        self.heartbeat_observer = Some(Arc::new(observer));
6814        self
6815    }
6816
6817    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6818        self.max_concurrent_workflow_tasks = count.max(1);
6819        self
6820    }
6821
6822    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6823        self.max_concurrent_activity_tasks = count.max(1);
6824        self
6825    }
6826
6827    /// Validate local handler admission without making a Server request.
6828    ///
6829    /// Registration methods retain their existing signatures. A duplicate keeps
6830    /// the original handler and makes this Worker invalid, including its clones.
6831    /// `register`, `run`, `run_until` and `run_once` enforce this check before
6832    /// any network request. Build a new Worker to correct an invalid configuration.
6833    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
6834        match &self.registration_error {
6835            Some(error) => Err(error.clone()),
6836            None => Ok(()),
6837        }
6838    }
6839
6840    #[track_caller]
6841    fn admit_registration<F>(
6842        &mut self,
6843        handler_kind: RegistrationKind,
6844        workflow_type: Option<&str>,
6845        handler_name: &str,
6846        method: &'static str,
6847    ) -> bool {
6848        let location = std::panic::Location::caller();
6849        let definition = HandlerRegistration {
6850            method,
6851            handler_type: type_name::<F>(),
6852            file: location.file(),
6853            line: location.line(),
6854            column: location.column(),
6855        };
6856        let key = (
6857            handler_kind,
6858            workflow_type.map(str::to_owned),
6859            handler_name.to_owned(),
6860        );
6861        if let Some(first_definition) = self.registration_definitions.get(&key) {
6862            if self.registration_error.is_none() {
6863                self.registration_error = Some(DuplicateRegistrationError {
6864                    handler_kind,
6865                    workflow_type: key.1.clone(),
6866                    handler_name: key.2.clone(),
6867                    first_definition: first_definition.clone(),
6868                    second_definition: definition,
6869                });
6870            }
6871            return false;
6872        }
6873        self.registration_definitions.insert(key, definition);
6874        true
6875    }
6876
6877    /// Register a workflow handler.
6878    ///
6879    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6880    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6881    /// while acquiring or decoding a worker task remain worker-operation
6882    /// failures and do not get converted into workflow outcomes.
6883    #[track_caller]
6884    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6885    where
6886        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6887        Fut: Future<Output = Result<Value>> + Send + 'static,
6888    {
6889        let workflow_type = workflow_type.into();
6890        if !self.admit_registration::<F>(
6891            RegistrationKind::Workflow,
6892            None,
6893            &workflow_type,
6894            "register_workflow",
6895        ) {
6896            return;
6897        }
6898        let handler = Arc::new(handler);
6899        self.workflows.insert(
6900            workflow_type,
6901            RegisteredWorkflow {
6902                execute: Arc::new(move |ctx, input| {
6903                    let handler = Arc::clone(&handler);
6904                    Box::pin(async move {
6905                        let result = handler(ctx, input.into_json()?).await?;
6906                        AvroValue::from_serialize(&result)
6907                    })
6908                }),
6909                replay: None,
6910                state_type: None,
6911                definition_fingerprint: None,
6912            },
6913        );
6914    }
6915
6916    /// Register a workflow with one Serde request value and a Serde result.
6917    ///
6918    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6919    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6920    /// workflow-specific schema. A task must contain zero arguments for a unit
6921    /// request or exactly one argument for every other request type.
6922    ///
6923    /// See the runnable
6924    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6925    /// for typed workflow and activity contracts with retry and timeout policy.
6926    #[track_caller]
6927    pub fn register_typed_workflow<I, O, F, Fut>(
6928        &mut self,
6929        workflow_type: impl Into<String>,
6930        handler: F,
6931    ) where
6932        I: DeserializeOwned + Send + 'static,
6933        O: Serialize + Send + 'static,
6934        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6935        Fut: Future<Output = Result<O>> + Send + 'static,
6936    {
6937        let workflow_type = workflow_type.into();
6938        if !self.admit_registration::<F>(
6939            RegistrationKind::Workflow,
6940            None,
6941            &workflow_type,
6942            "register_typed_workflow",
6943        ) {
6944            return;
6945        }
6946        let handler_name = workflow_type.clone();
6947        let handler = Arc::new(handler);
6948        self.workflows.insert(
6949            workflow_type,
6950            RegisteredWorkflow {
6951                execute: Arc::new(move |ctx, input| {
6952                    let handler = Arc::clone(&handler);
6953                    let handler_name = handler_name.clone();
6954                    Box::pin(async move {
6955                        let input =
6956                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6957                        let result = handler(ctx, input).await?;
6958                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6959                    })
6960                }),
6961                replay: None,
6962                state_type: None,
6963                definition_fingerprint: None,
6964            },
6965        );
6966    }
6967
6968    /// Register a workflow on the lossless fixed Avro Value surface.
6969    #[track_caller]
6970    pub fn register_workflow_avro_value<F, Fut>(
6971        &mut self,
6972        workflow_type: impl Into<String>,
6973        handler: F,
6974    ) where
6975        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6976        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6977    {
6978        let workflow_type = workflow_type.into();
6979        if !self.admit_registration::<F>(
6980            RegistrationKind::Workflow,
6981            None,
6982            &workflow_type,
6983            "register_workflow_avro_value",
6984        ) {
6985            return;
6986        }
6987        self.workflows.insert(
6988            workflow_type,
6989            RegisteredWorkflow {
6990                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6991                replay: None,
6992                state_type: None,
6993                definition_fingerprint: None,
6994            },
6995        );
6996    }
6997
6998    /// Register a workflow whose typed instance state can be reconstructed for queries.
6999    ///
7000    /// `state_factory` creates a fresh instance for every normal workflow task and
7001    /// query replay. The workflow handler is the single source of truth for state
7002    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7003    /// resolve. Query replay runs this same handler over committed history and
7004    /// discards any commands it would emit.
7005    #[track_caller]
7006    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7007        &mut self,
7008        workflow_type: impl Into<String>,
7009        state_factory: Factory,
7010        handler: F,
7011    ) where
7012        S: Clone + Send + Sync + 'static,
7013        Factory: Fn() -> S + Send + Sync + 'static,
7014        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7015        Fut: Future<Output = Result<Value>> + Send + 'static,
7016    {
7017        let workflow_type = workflow_type.into();
7018        if !self.admit_registration::<F>(
7019            RegistrationKind::Workflow,
7020            None,
7021            &workflow_type,
7022            "register_replayed_workflow",
7023        ) {
7024            return;
7025        }
7026        let state_factory = Arc::new(state_factory);
7027        let handler = Arc::new(handler);
7028
7029        let execute_factory = Arc::clone(&state_factory);
7030        let execute_handler = Arc::clone(&handler);
7031        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7032            let state = WorkflowInstance::new(execute_factory());
7033            let handler = Arc::clone(&execute_handler);
7034            Box::pin(async move {
7035                let result = handler(ctx, input.into_json()?, state).await?;
7036                AvroValue::from_serialize(&result)
7037            }) as WorkflowFuture
7038        });
7039
7040        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7041            let state = WorkflowInstance::new(state_factory());
7042            let snapshot_state = state.clone();
7043            let snapshot: WorkflowStateSnapshot =
7044                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7045            let replay_handler = Arc::clone(&handler);
7046            let future = async move {
7047                let result = replay_handler(ctx, input.into_json()?, state).await?;
7048                AvroValue::from_serialize(&result)
7049            };
7050            ReplayedWorkflowInvocation {
7051                future: Box::pin(future),
7052                snapshot,
7053            }
7054        });
7055
7056        self.workflows.insert(
7057            workflow_type,
7058            RegisteredWorkflow {
7059                execute,
7060                replay: Some(replay),
7061                state_type: Some(TypeId::of::<S>()),
7062                definition_fingerprint: None,
7063            },
7064        );
7065    }
7066
7067    /// Register a replayable workflow with one Serde request value and result.
7068    ///
7069    /// Normal task execution and instance-state query replay both decode and
7070    /// encode through the fixed Avro Value codec. The state factory and handler
7071    /// otherwise follow [`Worker::register_replayed_workflow`].
7072    #[track_caller]
7073    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7074        &mut self,
7075        workflow_type: impl Into<String>,
7076        state_factory: Factory,
7077        handler: F,
7078    ) where
7079        I: DeserializeOwned + Send + 'static,
7080        O: Serialize + Send + 'static,
7081        S: Clone + Send + Sync + 'static,
7082        Factory: Fn() -> S + Send + Sync + 'static,
7083        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7084        Fut: Future<Output = Result<O>> + Send + 'static,
7085    {
7086        let workflow_type = workflow_type.into();
7087        if !self.admit_registration::<F>(
7088            RegistrationKind::Workflow,
7089            None,
7090            &workflow_type,
7091            "register_typed_replayed_workflow",
7092        ) {
7093            return;
7094        }
7095        let state_factory = Arc::new(state_factory);
7096        let handler = Arc::new(handler);
7097
7098        let execute_name = workflow_type.clone();
7099        let execute_factory = Arc::clone(&state_factory);
7100        let execute_handler = Arc::clone(&handler);
7101        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7102            let state = WorkflowInstance::new(execute_factory());
7103            let handler = Arc::clone(&execute_handler);
7104            let handler_name = execute_name.clone();
7105            Box::pin(async move {
7106                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7107                let result = handler(ctx, input, state).await?;
7108                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7109            }) as WorkflowFuture
7110        });
7111
7112        let replay_name = workflow_type.clone();
7113        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7114            let state = WorkflowInstance::new(state_factory());
7115            let snapshot_state = state.clone();
7116            let snapshot: WorkflowStateSnapshot =
7117                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7118            let handler = Arc::clone(&handler);
7119            let handler_name = replay_name.clone();
7120            let future = async move {
7121                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7122                let result = handler(ctx, input, state).await?;
7123                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7124            };
7125            ReplayedWorkflowInvocation {
7126                future: Box::pin(future),
7127                snapshot,
7128            }
7129        });
7130
7131        self.workflows.insert(
7132            workflow_type,
7133            RegisteredWorkflow {
7134                execute,
7135                replay: Some(replay),
7136                state_type: Some(TypeId::of::<S>()),
7137                definition_fingerprint: None,
7138            },
7139        );
7140    }
7141
7142    /// Declare the signal names consumed by a registered workflow.
7143    ///
7144    /// Call this after registering the workflow and before starting the worker.
7145    /// Names read through `wait_signal` or `signals` need a declaration for
7146    /// Server command admission. Arguments remain arbitrary positional values,
7147    /// including lossless Avro values. This replaces the previous declaration;
7148    /// an empty slice declares no signals. Names are sorted and deduplicated.
7149    /// Existing runs retain the declarations captured when they started.
7150    pub fn declare_workflow_signals(
7151        &mut self,
7152        workflow_type: &str,
7153        signal_names: &[&str],
7154    ) -> Result<()> {
7155        if !self.workflows.contains_key(workflow_type) {
7156            return Err(Error::Codec(format!(
7157                "workflow type {workflow_type:?} is not registered"
7158            )));
7159        }
7160        if signal_names
7161            .iter()
7162            .any(|name| name.is_empty() || *name != name.trim())
7163        {
7164            return Err(Error::Codec(
7165                "signal names must be non-empty and have no surrounding whitespace".into(),
7166            ));
7167        }
7168        let mut names = signal_names
7169            .iter()
7170            .map(|name| (*name).to_string())
7171            .collect::<Vec<_>>();
7172        names.sort();
7173        names.dedup();
7174        self.signals.insert(workflow_type.to_string(), names);
7175        Ok(())
7176    }
7177
7178    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7179    ///
7180    /// Supply `include_str!` values for the workflow body and every helper whose
7181    /// behavior can affect replay. Register the workflow once, then set its
7182    /// identity before starting the worker. Duplicate registrations are invalid. The server
7183    /// rejects reusing a worker ID when its prior fingerprint disappears.
7184    /// Workflows without source identity remain runnable but cannot be safely redriven.
7185    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7186    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7187    pub fn set_workflow_definition_sources(
7188        &mut self,
7189        workflow_type: &str,
7190        sources: &[&str],
7191    ) -> Result<()> {
7192        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7193            return Err(Error::Codec(
7194                "workflow definition sources must be non-empty".to_string(),
7195            ));
7196        }
7197        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7198            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7199        })?;
7200        let mut hasher = Sha256::new();
7201        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7202        hasher.update((workflow_type.len() as u64).to_be_bytes());
7203        hasher.update(workflow_type.as_bytes());
7204        for source in sources {
7205            hasher.update((source.len() as u64).to_be_bytes());
7206            hasher.update(source.as_bytes());
7207        }
7208        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7209        Ok(())
7210    }
7211
7212    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7213    #[track_caller]
7214    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7215        &mut self,
7216        workflow_type: impl Into<String>,
7217        state_factory: Factory,
7218        handler: F,
7219    ) where
7220        S: Clone + Send + Sync + 'static,
7221        Factory: Fn() -> S + Send + Sync + 'static,
7222        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7223        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7224    {
7225        let workflow_type = workflow_type.into();
7226        if !self.admit_registration::<F>(
7227            RegistrationKind::Workflow,
7228            None,
7229            &workflow_type,
7230            "register_replayed_workflow_avro_value",
7231        ) {
7232            return;
7233        }
7234        let state_factory = Arc::new(state_factory);
7235        let handler = Arc::new(handler);
7236
7237        let execute_factory = Arc::clone(&state_factory);
7238        let execute_handler = Arc::clone(&handler);
7239        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7240            let state = WorkflowInstance::new(execute_factory());
7241            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
7242        });
7243
7244        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7245            let state = WorkflowInstance::new(state_factory());
7246            let snapshot_state = state.clone();
7247            let snapshot: WorkflowStateSnapshot =
7248                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7249            ReplayedWorkflowInvocation {
7250                future: Box::pin(handler(ctx, input, state)),
7251                snapshot,
7252            }
7253        });
7254
7255        self.workflows.insert(
7256            workflow_type,
7257            RegisteredWorkflow {
7258                execute,
7259                replay: Some(replay),
7260                state_type: Some(TypeId::of::<S>()),
7261                definition_fingerprint: None,
7262            },
7263        );
7264    }
7265
7266    #[track_caller]
7267    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7268    where
7269        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7270        Fut: Future<Output = Result<Value>> + Send + 'static,
7271    {
7272        let activity_type = activity_type.into();
7273        if !self.admit_registration::<F>(
7274            RegistrationKind::Activity,
7275            None,
7276            &activity_type,
7277            "register_activity",
7278        ) {
7279            return;
7280        }
7281        let handler = Arc::new(handler);
7282        self.activities.insert(
7283            activity_type,
7284            Arc::new(move |ctx, args| {
7285                let handler = Arc::clone(&handler);
7286                Box::pin(async move {
7287                    let result = handler(ctx, args.into_json()?).await?;
7288                    AvroValue::from_serialize(&result)
7289                })
7290            }),
7291        );
7292    }
7293
7294    /// Register an activity with one Serde request value and a Serde result.
7295    ///
7296    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7297    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7298    /// with the activity name and Rust type.
7299    #[track_caller]
7300    pub fn register_typed_activity<I, O, F, Fut>(
7301        &mut self,
7302        activity_type: impl Into<String>,
7303        handler: F,
7304    ) where
7305        I: DeserializeOwned + Send + 'static,
7306        O: Serialize + Send + 'static,
7307        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7308        Fut: Future<Output = Result<O>> + Send + 'static,
7309    {
7310        let activity_type = activity_type.into();
7311        if !self.admit_registration::<F>(
7312            RegistrationKind::Activity,
7313            None,
7314            &activity_type,
7315            "register_typed_activity",
7316        ) {
7317            return;
7318        }
7319        let handler_name = activity_type.clone();
7320        let handler = Arc::new(handler);
7321        self.activities.insert(
7322            activity_type,
7323            Arc::new(move |ctx, input| {
7324                let handler = Arc::clone(&handler);
7325                let handler_name = handler_name.clone();
7326                Box::pin(async move {
7327                    let input =
7328                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7329                    let result = handler(ctx, input).await?;
7330                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7331                })
7332            }),
7333        );
7334    }
7335
7336    /// Register an activity on the lossless fixed Avro Value surface.
7337    #[track_caller]
7338    pub fn register_activity_avro_value<F, Fut>(
7339        &mut self,
7340        activity_type: impl Into<String>,
7341        handler: F,
7342    ) where
7343        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7344        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7345    {
7346        let activity_type = activity_type.into();
7347        if !self.admit_registration::<F>(
7348            RegistrationKind::Activity,
7349            None,
7350            &activity_type,
7351            "register_activity_avro_value",
7352        ) {
7353            return;
7354        }
7355        self.activities.insert(
7356            activity_type,
7357            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7358        );
7359    }
7360
7361    /// Register a named, read-only query handler for a workflow type.
7362    ///
7363    /// The workflow type must also be registered with [`Worker::register_workflow`]
7364    /// before the worker runs. The handler receives only an immutable committed
7365    /// state snapshot and normalized query arguments.
7366    #[track_caller]
7367    pub fn register_query<F, Fut>(
7368        &mut self,
7369        workflow_type: impl Into<String>,
7370        query_name: impl Into<String>,
7371        handler: F,
7372    ) where
7373        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7374        Fut: Future<Output = Result<Value>> + Send + 'static,
7375    {
7376        let workflow_type = workflow_type.into();
7377        let query_name = query_name.into();
7378        if !self.admit_registration::<F>(
7379            RegistrationKind::Query,
7380            Some(&workflow_type),
7381            &query_name,
7382            "register_query",
7383        ) {
7384            return;
7385        }
7386        let handler = Arc::new(handler);
7387        self.queries.entry(workflow_type).or_default().insert(
7388            query_name,
7389            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7390                let handler = Arc::clone(&handler);
7391                Box::pin(async move {
7392                    let result = handler(ctx, args.into_json()?).await?;
7393                    AvroValue::from_serialize(&result)
7394                })
7395            })),
7396        );
7397    }
7398
7399    /// Register a query handler on the lossless fixed Avro Value surface.
7400    #[track_caller]
7401    pub fn register_query_avro_value<F, Fut>(
7402        &mut self,
7403        workflow_type: impl Into<String>,
7404        query_name: impl Into<String>,
7405        handler: F,
7406    ) where
7407        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7408        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7409    {
7410        let workflow_type = workflow_type.into();
7411        let query_name = query_name.into();
7412        if !self.admit_registration::<F>(
7413            RegistrationKind::Query,
7414            Some(&workflow_type),
7415            &query_name,
7416            "register_query_avro_value",
7417        ) {
7418            return;
7419        }
7420        self.queries.entry(workflow_type).or_default().insert(
7421            query_name,
7422            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7423        );
7424    }
7425
7426    /// Register a named query against deterministically replayed instance state.
7427    ///
7428    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7429    /// same state type `S`. The handler receives an immutable, detached state
7430    /// clone, so successful and failed queries cannot affect workflow execution
7431    /// or the state reconstructed by a later query.
7432    #[track_caller]
7433    pub fn register_replayed_query<S, F, Fut>(
7434        &mut self,
7435        workflow_type: impl Into<String>,
7436        query_name: impl Into<String>,
7437        handler: F,
7438    ) where
7439        S: Clone + Send + Sync + 'static,
7440        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7441        Fut: Future<Output = Result<Value>> + Send + 'static,
7442    {
7443        let workflow_type = workflow_type.into();
7444        let query_name = query_name.into();
7445        if !self.admit_registration::<F>(
7446            RegistrationKind::Query,
7447            Some(&workflow_type),
7448            &query_name,
7449            "register_replayed_query",
7450        ) {
7451            return;
7452        }
7453        let handler = Arc::new(handler);
7454        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7455            let state = state.downcast::<S>().map_err(|_| {
7456                "registered query state type does not match the replayed workflow state".to_string()
7457            })?;
7458            let handler = Arc::clone(&handler);
7459            Ok(Box::pin(async move {
7460                let result = handler(ctx, state, args.into_json()?).await?;
7461                AvroValue::from_serialize(&result)
7462            }))
7463        });
7464
7465        self.queries.entry(workflow_type).or_default().insert(
7466            query_name,
7467            RegisteredQuery::Replayed {
7468                state_type: TypeId::of::<S>(),
7469                handler: erased_handler,
7470            },
7471        );
7472    }
7473
7474    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7475    #[track_caller]
7476    pub fn register_replayed_query_avro_value<S, F, Fut>(
7477        &mut self,
7478        workflow_type: impl Into<String>,
7479        query_name: impl Into<String>,
7480        handler: F,
7481    ) where
7482        S: Clone + Send + Sync + 'static,
7483        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7484        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7485    {
7486        let workflow_type = workflow_type.into();
7487        let query_name = query_name.into();
7488        if !self.admit_registration::<F>(
7489            RegistrationKind::Query,
7490            Some(&workflow_type),
7491            &query_name,
7492            "register_replayed_query_avro_value",
7493        ) {
7494            return;
7495        }
7496        let handler = Arc::new(handler);
7497        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7498            let state = state.downcast::<S>().map_err(|_| {
7499                "registered query state type does not match the replayed workflow state".to_string()
7500            })?;
7501            Ok(Box::pin(handler(ctx, state, args)))
7502        });
7503
7504        self.queries.entry(workflow_type).or_default().insert(
7505            query_name,
7506            RegisteredQuery::Replayed {
7507                state_type: TypeId::of::<S>(),
7508                handler: erased_handler,
7509            },
7510        );
7511    }
7512
7513    /// Register a synchronous workflow update handler.
7514    #[track_caller]
7515    pub fn register_update<F, Fut>(
7516        &mut self,
7517        workflow_type: impl Into<String>,
7518        update_name: impl Into<String>,
7519        handler: F,
7520    ) where
7521        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7522        Fut: Future<Output = Result<Value>> + Send + 'static,
7523    {
7524        let workflow_type = workflow_type.into();
7525        let update_name = update_name.into();
7526        if !self.admit_registration::<F>(
7527            RegistrationKind::Update,
7528            Some(&workflow_type),
7529            &update_name,
7530            "register_update",
7531        ) {
7532            return;
7533        }
7534        let handler = Arc::new(handler);
7535        self.updates.entry(workflow_type).or_default().insert(
7536            update_name,
7537            Arc::new(move |ctx, args| {
7538                let handler = Arc::clone(&handler);
7539                Box::pin(async move {
7540                    let result = handler(ctx, args.into_json()?).await?;
7541                    AvroValue::from_serialize(&result)
7542                })
7543            }),
7544        );
7545    }
7546
7547    /// Register an update handler on the lossless fixed Avro Value surface.
7548    #[track_caller]
7549    pub fn register_update_avro_value<F, Fut>(
7550        &mut self,
7551        workflow_type: impl Into<String>,
7552        update_name: impl Into<String>,
7553        handler: F,
7554    ) where
7555        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7556        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7557    {
7558        let workflow_type = workflow_type.into();
7559        let update_name = update_name.into();
7560        if !self.admit_registration::<F>(
7561            RegistrationKind::Update,
7562            Some(&workflow_type),
7563            &update_name,
7564            "register_update_avro_value",
7565        ) {
7566            return;
7567        }
7568        self.updates.entry(workflow_type).or_default().insert(
7569            update_name,
7570            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7571        );
7572    }
7573
7574    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7575        self.validate_registration()?;
7576        self.sticky_registration_confirmed
7577            .store(false, Ordering::SeqCst);
7578        self.session_registration_confirmed
7579            .store(false, Ordering::SeqCst);
7580        for capability in &self.resource_capabilities {
7581            worker_session::validate_resource_capability(capability)?;
7582        }
7583        self.local_registration_confirmed
7584            .store(false, Ordering::SeqCst);
7585        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7586            return Err(Error::CooperativeCancellationUnavailable(
7587                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7588            ));
7589        }
7590        let mut command_contracts = serde_json::Map::new();
7591        for workflow_type in self.workflows.keys() {
7592            let mut queries = self
7593                .queries
7594                .get(workflow_type)
7595                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7596                .unwrap_or_default();
7597            queries.sort();
7598            let mut updates = self
7599                .updates
7600                .get(workflow_type)
7601                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7602                .unwrap_or_default();
7603            updates.sort();
7604            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7605            command_contracts.insert(
7606                workflow_type.clone(),
7607                json!({
7608                    "queries": queries,
7609                    "query_contracts": argument_vector_contracts(&queries),
7610                    "signals": signals,
7611                    "signal_contracts": argument_vector_contracts(&signals),
7612                    "updates": updates,
7613                    "update_contracts": argument_vector_contracts(&updates),
7614                    "update_validators": [],
7615                }),
7616            );
7617        }
7618
7619        self.cooperative_registration_confirmed
7620            .store(false, Ordering::SeqCst);
7621        let response = self
7622            .client
7623            .register_worker_with_definition_fingerprints(
7624                &self.worker_id,
7625                &self.task_queue,
7626                self.workflows.keys().cloned().collect(),
7627                self.activities.keys().cloned().collect(),
7628                self.max_concurrent_workflow_tasks,
7629                self.max_concurrent_activity_tasks,
7630                [
7631                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7632                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7633                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7634                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7635                    self.client
7636                        .local_activities_enabled
7637                        .then(|| "local_activities".to_string()),
7638                    self.client
7639                        .worker_sessions_enabled
7640                        .then(|| "worker_sessions".to_string()),
7641                    self.client
7642                        .sticky_cache
7643                        .is_some()
7644                        .then(|| "sticky_execution".to_string()),
7645                    self.cooperative_cancellation_enabled
7646                        .then(|| "cooperative_cancellation".to_string()),
7647                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7648                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7649                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7650                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7651                ]
7652                .into_iter()
7653                .flatten()
7654                .chain(self.resource_capabilities.iter().cloned())
7655                .collect(),
7656                Value::Object(command_contracts),
7657                Some(
7658                    self.workflows
7659                        .iter()
7660                        .filter_map(|(workflow_type, workflow)| {
7661                            workflow
7662                                .definition_fingerprint
7663                                .as_ref()
7664                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7665                        })
7666                        .collect(),
7667                ),
7668            )
7669            .await?;
7670        if self.cooperative_cancellation_enabled && response.registered {
7671            self.cooperative_registration_confirmed
7672                .store(true, Ordering::SeqCst);
7673        }
7674        if self.client.local_activities_enabled && response.registered {
7675            self.local_registration_confirmed
7676                .store(true, Ordering::SeqCst);
7677        }
7678        if self.client.worker_sessions_enabled && response.registered {
7679            self.session_registration_confirmed
7680                .store(true, Ordering::SeqCst);
7681        }
7682        if self.client.sticky_cache.is_some() && response.registered {
7683            self.sticky_registration_confirmed
7684                .store(true, Ordering::SeqCst);
7685        }
7686        Ok(response)
7687    }
7688
7689    /// Run until shutdown or a terminal worker error occurs.
7690    ///
7691    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7692    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7693    /// authentication, protocol, and other non-retryable failures are returned.
7694    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7695    /// poll and heartbeat outages beyond the ordinary retry budget.
7696    pub async fn run(&self) -> Result<()> {
7697        self.run_until(std::future::pending::<()>()).await
7698    }
7699
7700    /// Run until `shutdown` resolves or a terminal worker error occurs.
7701    ///
7702    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7703    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7704    where
7705        F: Future<Output = ()>,
7706    {
7707        let _clear_cache_on_drop =
7708            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7709        let stop = Arc::new(AtomicBool::new(false));
7710        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7711        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7712        worker.run_stop = Some(Arc::clone(&stop));
7713        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7714        tokio::pin!(run);
7715        tokio::pin!(shutdown);
7716        tokio::select! {
7717            result = &mut run => result,
7718            _ = &mut shutdown => {
7719                stop.store(true, Ordering::SeqCst);
7720                run.await
7721            }
7722        }
7723    }
7724
7725    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7726        let mut worker = self.clone();
7727        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7728            policy: self.retry_policy,
7729            stop,
7730        });
7731        worker
7732    }
7733
7734    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7735        let registration = self.register().await?;
7736        if !registration.registered {
7737            return Err(Error::WorkerLoop(format!(
7738                "worker registration for {:?} was not accepted",
7739                self.worker_id
7740            )));
7741        }
7742        let registered_worker_id = registration.worker_id.clone();
7743        let primary = self.run_registered_until(stop, registration).await;
7744        let primary = match (primary, self.close_worker_sessions().await) {
7745            (Ok(()), result) => result,
7746            (Err(error), Ok(())) => Err(error),
7747            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7748                primary: Box::new(primary),
7749                deregistration: Box::new(close),
7750            }),
7751        };
7752        self.session_registration_confirmed
7753            .store(false, Ordering::SeqCst);
7754        self.cooperative_registration_confirmed
7755            .store(false, Ordering::SeqCst);
7756        self.local_registration_confirmed
7757            .store(false, Ordering::SeqCst);
7758        let deregistration = self
7759            .client
7760            .deregister_worker_registration(&registered_worker_id)
7761            .await;
7762        self.sticky_registration_confirmed
7763            .store(false, Ordering::SeqCst);
7764        self.client.clear_sticky_cache()?;
7765
7766        match (primary, deregistration) {
7767            (Ok(()), Ok(_)) => Ok(()),
7768            (Ok(()), Err(deregistration)) => Err(deregistration),
7769            (Err(primary), Ok(_)) => Err(primary),
7770            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7771                primary: Box::new(primary),
7772                deregistration: Box::new(deregistration),
7773            }),
7774        }
7775    }
7776
7777    async fn run_registered_until(
7778        &self,
7779        stop: Arc<AtomicBool>,
7780        registration: RegisterWorkerResponse,
7781    ) -> Result<()> {
7782        let heartbeat_interval = Duration::from_secs(
7783            registration
7784                .heartbeat_interval_seconds
7785                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7786        );
7787        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7788        // from the completion of the preceding attempt, including its bounded
7789        // retries. A fixed-epoch interval can leave an already-due tick queued
7790        // while an acknowledgement is slow, producing a catch-up heartbeat as
7791        // soon as that request completes.
7792        let heartbeat = tokio::time::sleep(Duration::ZERO);
7793        tokio::pin!(heartbeat);
7794        // Poll responses may already have leased server-side work by the time
7795        // they become ready, so each poller owns its responses through
7796        // completion or failure instead of racing raw polls in this select.
7797        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7798            let worker = self.clone();
7799            let stop = Arc::clone(&stop);
7800            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7801        });
7802        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7803            let worker = self.clone();
7804            let stop = Arc::clone(&stop);
7805            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7806        });
7807        let mut query_poller = (!self.queries.is_empty()).then(|| {
7808            let worker = self.clone();
7809            let stop = Arc::clone(&stop);
7810            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7811        });
7812
7813        loop {
7814            tokio::select! {
7815                _ = wait_for_worker_stop(&stop) => {
7816                    stop.store(true, Ordering::SeqCst);
7817                    break;
7818                }
7819                _ = &mut heartbeat => {
7820                    let result = self.retry_worker_operation(|| {
7821                        self.client.heartbeat_worker_with_sessions(
7822                            &self.worker_id,
7823                            self.max_concurrent_workflow_tasks,
7824                            self.max_concurrent_activity_tasks,
7825                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7826                        )
7827                    }).await;
7828                    heartbeat
7829                        .as_mut()
7830                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7831                    match result {
7832                        Ok(Some(acknowledgement)) => {
7833                            if let Some(observer) = &self.heartbeat_observer {
7834                                observer(&WorkerHeartbeatObservation {
7835                                    worker_id: self.worker_id.clone(),
7836                                    task_queue: self.task_queue.clone(),
7837                                    acknowledged_at_unix_millis: SystemTime::now()
7838                                        .duration_since(UNIX_EPOCH)
7839                                        .unwrap_or_default()
7840                                        .as_millis()
7841                                        .min(u64::MAX as u128)
7842                                        as u64,
7843                                    acknowledgement,
7844                                });
7845                            }
7846                        }
7847                        Ok(None) => break,
7848                        Err(error) => {
7849                            stop.store(true, Ordering::SeqCst);
7850                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7851                            return Err(error);
7852                        }
7853                    }
7854                }
7855                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7856                    workflow_poller = None;
7857                    let stopped_by_server = stop.load(Ordering::SeqCst);
7858                    stop.store(true, Ordering::SeqCst);
7859                    let poller_result = optional_poller_result("workflow", result);
7860                    let join_result =
7861                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7862                    poller_result?;
7863                    join_result?;
7864                    if stopped_by_server {
7865                        return Ok(());
7866                    }
7867                    return Err(Error::WorkerLoop(
7868                        "workflow poller stopped unexpectedly".to_string(),
7869                    ));
7870                }
7871                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7872                    activity_poller = None;
7873                    let stopped_by_server = stop.load(Ordering::SeqCst);
7874                    stop.store(true, Ordering::SeqCst);
7875                    let poller_result = optional_poller_result("activity", result);
7876                    let join_result =
7877                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7878                    poller_result?;
7879                    join_result?;
7880                    if stopped_by_server {
7881                        return Ok(());
7882                    }
7883                    return Err(Error::WorkerLoop(
7884                        "activity poller stopped unexpectedly".to_string(),
7885                    ));
7886                }
7887                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7888                    query_poller = None;
7889                    let stopped_by_server = stop.load(Ordering::SeqCst);
7890                    stop.store(true, Ordering::SeqCst);
7891                    let poller_result = optional_poller_result("query", result);
7892                    let join_result =
7893                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7894                    poller_result?;
7895                    join_result?;
7896                    if stopped_by_server {
7897                        return Ok(());
7898                    }
7899                    return Err(Error::WorkerLoop(
7900                        "query poller stopped unexpectedly".to_string(),
7901                    ));
7902                }
7903            }
7904        }
7905
7906        join_pollers(
7907            workflow_poller.take(),
7908            activity_poller.take(),
7909            query_poller.take(),
7910        )
7911        .await
7912    }
7913
7914    /// Poll and settle at most one task from each enabled task family.
7915    ///
7916    /// A workflow may reach its server-enforced run deadline while this worker
7917    /// holds a task. When the completion endpoint authoritatively rejects that
7918    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7919    /// terminal `run_status=failed`, the workflow tick is considered settled:
7920    /// the late command was not recorded and cannot replace the terminal run.
7921    /// Every other completion rejection remains an error. This worker-level
7922    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7923    /// only bounds how long a client waits for a result.
7924    ///
7925    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7926    /// the original [`Error::Http`] status and response body.
7927    pub async fn run_once(&self) -> Result<usize> {
7928        self.validate_registration()?;
7929        if self.client.worker_sessions_enabled {
7930            self.require_session_registration()?;
7931        }
7932        if self.cooperative_cancellation_enabled
7933            && !self
7934                .cooperative_registration_confirmed
7935                .load(Ordering::SeqCst)
7936        {
7937            return Err(Error::CooperativeCancellationUnavailable(
7938                "register this cooperative worker before polling tasks".into(),
7939            ));
7940        }
7941        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7942        let mut handled = 0;
7943        match worker.poll_workflow_once().await? {
7944            ManagedPollOutcome::Handled => handled += 1,
7945            ManagedPollOutcome::Stop => return Ok(handled),
7946            ManagedPollOutcome::Idle => {}
7947        }
7948        match worker.poll_activity_once().await? {
7949            ManagedPollOutcome::Handled => handled += 1,
7950            ManagedPollOutcome::Stop => return Ok(handled),
7951            ManagedPollOutcome::Idle => {}
7952        }
7953        if !self.queries.is_empty() {
7954            match worker.poll_query_once().await? {
7955                ManagedPollOutcome::Handled => handled += 1,
7956                ManagedPollOutcome::Stop => return Ok(handled),
7957                ManagedPollOutcome::Idle => {}
7958            }
7959        }
7960        Ok(handled)
7961    }
7962
7963    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7964        if self.client.sticky_cache.is_some()
7965            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
7966        {
7967            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
7968        }
7969        if self.client.local_activities_enabled
7970            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7971        {
7972            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7973        }
7974        if self.cooperative_cancellation_enabled {
7975            return self.poll_cooperative_workflow_once().await;
7976        }
7977        let poll_request_id = unique_request_id("rust-workflow-poll");
7978        let response = self
7979            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
7980            .await;
7981        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
7982            return Ok(ManagedPollOutcome::Idle);
7983        };
7984        if response.outcome().should_stop() {
7985            return Ok(ManagedPollOutcome::Stop);
7986        }
7987        let memo_updates_supported =
7988            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7989        let Some(task) = response.task else {
7990            return Ok(ManagedPollOutcome::Idle);
7991        };
7992
7993        let task_id = task.task_id.clone();
7994        let attempt = task.workflow_task_attempt;
7995        let run_id = task.run_id.clone();
7996        let lease_owner = task
7997            .lease_owner
7998            .clone()
7999            .unwrap_or_else(|| self.worker_id.clone());
8000
8001        let decision = match self.execute_workflow_with_local_activities(task).await {
8002            Ok(Some(decision)) => Ok(decision),
8003            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8004            Err(error) => Err(error),
8005        };
8006        self.settle_workflow_task_decision(
8007            &task_id,
8008            &lease_owner,
8009            attempt,
8010            run_id.as_deref(),
8011            decision,
8012            memo_updates_supported,
8013            snapshot,
8014        )
8015        .await
8016    }
8017
8018    #[allow(clippy::too_many_arguments)]
8019    async fn settle_workflow_task_decision(
8020        &self,
8021        task_id: &str,
8022        lease_owner: &str,
8023        attempt: u64,
8024        run_id: Option<&str>,
8025        decision: Result<WorkflowTaskDecision>,
8026        memo_updates_supported: bool,
8027        snapshot: Option<sticky_worker::StickySnapshot>,
8028    ) -> Result<ManagedPollOutcome> {
8029        match decision {
8030            Ok(decision)
8031                if decision.cancellation_delivery.is_some()
8032                    || decision.cancellation_scope_delivery.is_some()
8033                    || decision.cancellation_scope_opening.is_some() =>
8034            {
8035                return Err(Error::CooperativeCancellationUnavailable(
8036                    "worker cancellation delivery has not been negotiated".into(),
8037                ));
8038            }
8039            Ok(decision)
8040                if commands_use_workflow_memo_updates(&decision.commands)
8041                    && !memo_updates_supported =>
8042            {
8043                self.client
8044                    .fail_workflow_task(
8045                        task_id,
8046                        lease_owner,
8047                        attempt,
8048                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8049                    )
8050                    .await?;
8051            }
8052            Ok(decision) if decision.commands.is_empty() => {
8053                // A replay can consume a recorded pending durable command
8054                // without producing a new command. The standalone protocol
8055                // acknowledges that state through the typed waiting outcome;
8056                // an empty completion is rejected by servers that require at
8057                // least one executable command.
8058                self.client
8059                    .fail_workflow_task_with_type(
8060                        task_id,
8061                        lease_owner,
8062                        attempt,
8063                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8064                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8065                    )
8066                    .await?;
8067            }
8068            Ok(decision) => {
8069                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8070                let completion = self
8071                    .client
8072                    .complete_workflow_task_with_message_streams(
8073                        task_id,
8074                        lease_owner,
8075                        attempt,
8076                        decision.commands,
8077                        decision.message_stream_cursors,
8078                        decision.message_stream_waits,
8079                        sticky_claim,
8080                    )
8081                    .await;
8082                if let Err(error) = completion {
8083                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8084                    if !workflow_task_completion_is_terminal_timeout(
8085                        &error, task_id, attempt, run_id,
8086                    ) {
8087                        return Err(error);
8088                    }
8089                }
8090            }
8091            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8092            Err(error) => {
8093                self.discard_sticky_snapshot(snapshot.as_ref())?;
8094                self.client
8095                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8096                    .await?;
8097            }
8098        }
8099
8100        Ok(ManagedPollOutcome::Handled)
8101    }
8102
8103    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8104        while !stop.load(Ordering::SeqCst) {
8105            match self.poll_workflow_once().await {
8106                Ok(ManagedPollOutcome::Stop) => {
8107                    stop.store(true, Ordering::SeqCst);
8108                    break;
8109                }
8110                Err(error) => {
8111                    stop.store(true, Ordering::SeqCst);
8112                    return Err(error);
8113                }
8114                _ => {}
8115            }
8116        }
8117
8118        Ok(())
8119    }
8120
8121    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8122        if self.client.worker_sessions_enabled {
8123            self.require_session_registration()?;
8124        }
8125        if self.cooperative_cancellation_enabled {
8126            return self.poll_cooperative_activity_once().await;
8127        }
8128        let poll_request_id = unique_request_id("rust-activity-poll");
8129        let response = self
8130            .retry_worker_operation(|| {
8131                self.client.poll_activity_task_response_with_request_id(
8132                    &self.worker_id,
8133                    &self.task_queue,
8134                    self.poll_timeout,
8135                    &poll_request_id,
8136                    0,
8137                )
8138            })
8139            .await;
8140        let response = match response {
8141            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8142            response => response,
8143        };
8144        let Some(response) = self.settle_worker_poll_response(response).await? else {
8145            return Ok(ManagedPollOutcome::Idle);
8146        };
8147        if response.outcome().should_stop() {
8148            return Ok(ManagedPollOutcome::Stop);
8149        }
8150        let Some(task) = response.task else {
8151            return Ok(ManagedPollOutcome::Idle);
8152        };
8153
8154        let session = self.track_session_task(task.worker_session.as_ref())?;
8155        let hydration_claim = task.hydration_claim;
8156        let task = task.task;
8157
8158        let task_id = task.task_id.clone();
8159        let attempt_id = task
8160            .activity_attempt_id
8161            .clone()
8162            .or(task.attempt_id.clone())
8163            .unwrap_or_default();
8164        let lease_owner = task
8165            .lease_owner
8166            .clone()
8167            .unwrap_or_else(|| self.worker_id.clone());
8168        let codec = task.payload_codec.clone();
8169        let result = self
8170            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8171            .await;
8172        match result {
8173            Err(Error::ActivityExecutionAbandoned(_)) => {}
8174            Err(error) if activity_hydration::stopped(&error) => {}
8175            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8176            Ok(value) => {
8177                let completion = self
8178                    .client
8179                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8180                    .await;
8181                if let Err(error) = completion {
8182                    if !activity_task_rejection_is_final(&error) {
8183                        return Err(error);
8184                    }
8185                }
8186            }
8187            Err(error) => {
8188                let failure = self
8189                    .client
8190                    .fail_activity_task(
8191                        &task_id,
8192                        &attempt_id,
8193                        &lease_owner,
8194                        error.to_string(),
8195                        false,
8196                    )
8197                    .await;
8198                if let Err(error) = failure {
8199                    if !activity_task_rejection_is_final(&error) {
8200                        return Err(error);
8201                    }
8202                }
8203            }
8204        }
8205
8206        Ok(ManagedPollOutcome::Handled)
8207    }
8208
8209    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8210        // Each lane retains its leased response through callback settlement.
8211        // A bounded independent activity must not occupy the cleanup lane too.
8212        // Preserve the existing serial loop unless cooperation is enabled.
8213        let lane_count = if self.cooperative_cancellation_enabled {
8214            self.max_concurrent_activity_tasks
8215        } else {
8216            1
8217        };
8218        let mut lanes = FuturesUnordered::new();
8219        for _ in 0..lane_count {
8220            let worker = self.clone();
8221            let stop = Arc::clone(&stop);
8222            lanes.push(async move {
8223                while !stop.load(Ordering::SeqCst) {
8224                    match worker.poll_activity_once().await {
8225                        Ok(ManagedPollOutcome::Stop) => {
8226                            stop.store(true, Ordering::SeqCst);
8227                            break;
8228                        }
8229                        Err(error) => {
8230                            stop.store(true, Ordering::SeqCst);
8231                            return Err(error);
8232                        }
8233                        _ => {}
8234                    }
8235                }
8236                Ok(())
8237            });
8238        }
8239        // Join every lane before deregistration, including after one fails.
8240        let mut first_error = None;
8241        while let Some(result) = lanes.next().await {
8242            if let Err(error) = result {
8243                first_error.get_or_insert(error);
8244            }
8245        }
8246        first_error.map_or(Ok(()), Err)
8247    }
8248
8249    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8250        let poll_request_id = unique_request_id("rust-query-poll");
8251        let response = self
8252            .retry_worker_operation(|| {
8253                self.client.poll_query_task_response_with_request_id(
8254                    &self.worker_id,
8255                    &self.task_queue,
8256                    self.poll_timeout,
8257                    &poll_request_id,
8258                    0,
8259                )
8260            })
8261            .await;
8262        let Some(response) = self.settle_worker_poll_response(response).await? else {
8263            return Ok(ManagedPollOutcome::Idle);
8264        };
8265        if response.outcome().should_stop() {
8266            return Ok(ManagedPollOutcome::Stop);
8267        }
8268        let Some(task) = response.task else {
8269            return Ok(ManagedPollOutcome::Idle);
8270        };
8271
8272        let query_task_id = task.query_task_id.clone();
8273        let attempt = task.query_task_attempt;
8274        let lease_owner = task
8275            .lease_owner
8276            .clone()
8277            .unwrap_or_else(|| self.worker_id.clone());
8278        let codec = task.payload_codec.clone();
8279
8280        match self.execute_query_task(task).await {
8281            Ok(value) => {
8282                let result_envelope = match encode_typed_envelope(&value, &codec) {
8283                    Ok(result_envelope) => result_envelope,
8284                    Err(error) => {
8285                        let failure = self
8286                            .client
8287                            .fail_query_task(
8288                                &query_task_id,
8289                                &lease_owner,
8290                                attempt,
8291                                error.to_string(),
8292                                "query_result_encode_failed",
8293                                "QueryResultEncodeFailed",
8294                            )
8295                            .await;
8296                        if let Err(error) = failure {
8297                            if !query_task_rejection_is_final(&error) {
8298                                return Err(error);
8299                            }
8300                        }
8301                        return Ok(ManagedPollOutcome::Handled);
8302                    }
8303                };
8304
8305                if let Err(error) = self
8306                    .client
8307                    .complete_query_task_with_envelope(
8308                        &query_task_id,
8309                        &lease_owner,
8310                        attempt,
8311                        value.clone().into_json()?,
8312                        result_envelope,
8313                    )
8314                    .await
8315                {
8316                    if !query_task_rejection_is_final(&error) {
8317                        return Err(error);
8318                    }
8319                }
8320            }
8321            Err(failure) => {
8322                let result = self
8323                    .client
8324                    .fail_query_task(
8325                        &query_task_id,
8326                        &lease_owner,
8327                        attempt,
8328                        failure.message,
8329                        failure.reason,
8330                        failure.failure_type,
8331                    )
8332                    .await;
8333                if let Err(error) = result {
8334                    if !query_task_rejection_is_final(&error) {
8335                        return Err(error);
8336                    }
8337                }
8338            }
8339        }
8340
8341        Ok(ManagedPollOutcome::Handled)
8342    }
8343
8344    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8345        while !stop.load(Ordering::SeqCst) {
8346            match self.poll_query_once().await {
8347                Ok(ManagedPollOutcome::Stop) => {
8348                    stop.store(true, Ordering::SeqCst);
8349                    break;
8350                }
8351                Err(error) => {
8352                    stop.store(true, Ordering::SeqCst);
8353                    return Err(error);
8354                }
8355                _ => {}
8356            }
8357        }
8358
8359        Ok(())
8360    }
8361
8362    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8363    where
8364        F: FnMut() -> Fut,
8365        Fut: Future<Output = Result<T>>,
8366    {
8367        let mut retries = 0;
8368
8369        loop {
8370            if self
8371                .run_stop
8372                .as_ref()
8373                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8374            {
8375                return Ok(None);
8376            }
8377            match operation().await {
8378                Err(error)
8379                    if (workflow_hydration::stopped(&error)
8380                        || activity_hydration::stopped(&error))
8381                        && self
8382                            .run_stop
8383                            .as_ref()
8384                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8385                {
8386                    return Ok(None);
8387                }
8388                Err(error)
8389                    if worker_operation_is_retryable(&error)
8390                        && (retries < self.retry_policy.max_retries
8391                            || (self.recover_transient_outages
8392                                && self.run_stop.is_some()
8393                                && self.retry_policy.max_retries > 0)) =>
8394                {
8395                    retries = retries.saturating_add(1);
8396                    let delay = worker_retry_delay(self.retry_policy, retries)
8397                        .max(Duration::from_millis(1));
8398                    if let Some(stop) = &self.run_stop {
8399                        tokio::select! {
8400                            _ = tokio::time::sleep(delay) => {}
8401                            _ = wait_for_worker_stop(stop) => return Ok(None),
8402                        }
8403                    } else {
8404                        tokio::time::sleep(delay).await;
8405                    }
8406                }
8407                result => return result.map(Some),
8408            }
8409        }
8410    }
8411
8412    async fn settle_worker_poll_response<T>(
8413        &self,
8414        response: Result<Option<T>>,
8415    ) -> Result<Option<T>> {
8416        match response {
8417            Ok(response) => Ok(response),
8418            Err(error) => {
8419                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8420                    return Err(error);
8421                };
8422                let minimum_delay = self
8423                    .retry_policy
8424                    .initial_backoff
8425                    .max(Duration::from_millis(1));
8426                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8427                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8428                Ok(None)
8429            }
8430        }
8431    }
8432
8433    async fn execute_query_task(
8434        &self,
8435        mut task: QueryTask,
8436    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8437        validate_query_task_payloads(&task).map_err(|error| {
8438            QueryTaskExecutionFailure::new(
8439                "query_payload_decode_failed",
8440                error.to_string(),
8441                "QueryPayloadDecodeFailed",
8442            )
8443        })?;
8444
8445        if !self.workflows.contains_key(&task.workflow_type) {
8446            return Err(QueryTaskExecutionFailure::new(
8447                "query_workflow_type_not_registered",
8448                format!("no workflow registered for type {:?}", task.workflow_type),
8449                "WorkflowTypeNotRegistered",
8450            ));
8451        }
8452
8453        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8454            return Err(QueryTaskExecutionFailure::new(
8455                "query_handler_unavailable",
8456                format!(
8457                    "query handlers are unavailable for workflow type {:?}",
8458                    task.workflow_type
8459                ),
8460                "QueryHandlerUnavailable",
8461            ));
8462        };
8463        let Some(query) = handlers.get(&task.query_name) else {
8464            return Err(QueryTaskExecutionFailure::new(
8465                "rejected_unknown_query",
8466                format!("unknown query {:?}", task.query_name),
8467                "QueryFailed",
8468            ));
8469        };
8470
8471        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8472            .map_err(|error| {
8473            QueryTaskExecutionFailure::new(
8474                "query_payload_decode_failed",
8475                format!("cannot decode query arguments: {error}"),
8476                "QueryPayloadDecodeFailed",
8477            )
8478        })?;
8479        let workflow_input_typed =
8480            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8481                .map_err(|error| {
8482                    QueryTaskExecutionFailure::new(
8483                        "query_workflow_state_unavailable",
8484                        format!("cannot decode workflow start input: {error}"),
8485                        "QueryWorkflowStateUnavailable",
8486                    )
8487                })?;
8488        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8489            QueryTaskExecutionFailure::new(
8490                "query_workflow_state_unavailable",
8491                format!("cannot project workflow start input: {error}"),
8492                "QueryWorkflowStateUnavailable",
8493            )
8494        })?;
8495        hydrate_query_history_from_export(&mut task).map_err(|error| {
8496            QueryTaskExecutionFailure::new(
8497                "query_workflow_state_unavailable",
8498                format!("cannot restore query history snapshot: {error}"),
8499                "QueryWorkflowStateUnavailable",
8500            )
8501        })?;
8502        enrich_query_history_from_export(&mut task).map_err(|error| {
8503            QueryTaskExecutionFailure::new(
8504                "query_workflow_state_unavailable",
8505                format!("cannot restore compact query history payloads: {error}"),
8506                "QueryWorkflowStateUnavailable",
8507            )
8508        })?;
8509        let signal_events = query_signal_events(&task).map_err(|error| {
8510            QueryTaskExecutionFailure::new(
8511                "query_workflow_state_unavailable",
8512                format!("cannot decode committed workflow signals: {error}"),
8513                "QueryWorkflowStateUnavailable",
8514            )
8515        })?;
8516        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8517        let context = QueryContext {
8518            workflow_id: task.workflow_id,
8519            run_id: task.run_id,
8520            workflow_type: task.workflow_type.clone(),
8521            run_status: task.run_status,
8522            workflow_input,
8523            workflow_input_avro_value: workflow_input_typed.clone(),
8524            history_events: Arc::clone(&history_events),
8525            signal_events: Arc::new(signal_events),
8526        };
8527
8528        let future = match query {
8529            RegisteredQuery::Snapshot(handler) => handler(context, args),
8530            RegisteredQuery::Replayed {
8531                state_type,
8532                handler,
8533            } => {
8534                let workflow = self
8535                    .workflows
8536                    .get(&task.workflow_type)
8537                    .expect("workflow registration was checked above");
8538                if workflow.state_type != Some(*state_type) {
8539                    return Err(QueryTaskExecutionFailure::new(
8540                        "query_workflow_state_unavailable",
8541                        "replayed query state type does not match its workflow registration",
8542                        "QueryWorkflowStateUnavailable",
8543                    ));
8544                }
8545                let replay = workflow.replay.as_ref().ok_or_else(|| {
8546                    QueryTaskExecutionFailure::new(
8547                        "query_workflow_state_unavailable",
8548                        format!(
8549                            "workflow type {:?} is not registered for instance-state replay",
8550                            task.workflow_type
8551                        ),
8552                        "QueryWorkflowStateUnavailable",
8553                    )
8554                })?;
8555                let workflow_state = Arc::new(Mutex::new(
8556                    WorkflowState::new_with_identity(
8557                        history_events.as_ref().clone(),
8558                        context.workflow_id.clone(),
8559                        context.run_id.clone(),
8560                        self.task_queue.clone(),
8561                        task.payload_codec,
8562                        None,
8563                    )
8564                    .map_err(|error| {
8565                        QueryTaskExecutionFailure::new(
8566                            "query_workflow_state_unavailable",
8567                            format!("workflow replay failed before query: {error}"),
8568                            "QueryWorkflowStateUnavailable",
8569                        )
8570                    })?,
8571                ));
8572                let workflow_context = WorkflowContext {
8573                    state: workflow_state,
8574                    cancellation_scope_id: "root".into(),
8575                };
8576                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8577                let mut cx = TaskContext::from_waker(noop_waker_ref());
8578                let outcome = {
8579                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8580                        .map_err(|error| {
8581                            QueryTaskExecutionFailure::new(
8582                                "query_workflow_state_unavailable",
8583                                error.to_string(),
8584                                "QueryWorkflowStateUnavailable",
8585                            )
8586                        })?;
8587                    invocation.future.as_mut().poll(&mut cx)
8588                };
8589                match outcome {
8590                    Poll::Ready(Ok(_)) => {
8591                        workflow_context
8592                            .ensure_history_consumed()
8593                            .map_err(|error| {
8594                                QueryTaskExecutionFailure::new(
8595                                    "query_workflow_state_unavailable",
8596                                    format!("workflow replay failed before query: {error}"),
8597                                    "QueryWorkflowStateUnavailable",
8598                                )
8599                            })?;
8600                    }
8601                    Poll::Ready(Err(error)) => {
8602                        return Err(QueryTaskExecutionFailure::new(
8603                            "query_workflow_state_unavailable",
8604                            format!("workflow replay failed before query: {error}"),
8605                            "QueryWorkflowStateUnavailable",
8606                        ));
8607                    }
8608                    Poll::Pending => {
8609                        let commands = workflow_context.take_commands().map_err(|error| {
8610                            QueryTaskExecutionFailure::new(
8611                                "query_workflow_state_unavailable",
8612                                format!("workflow replay failed before query: {error}"),
8613                                "QueryWorkflowStateUnavailable",
8614                            )
8615                        })?;
8616                        if commands.is_empty()
8617                            && !workflow_context
8618                                .matched_recorded_pending()
8619                                .map_err(|error| {
8620                                    QueryTaskExecutionFailure::new(
8621                                        "query_workflow_state_unavailable",
8622                                        format!("workflow replay failed before query: {error}"),
8623                                        "QueryWorkflowStateUnavailable",
8624                                    )
8625                                })?
8626                        {
8627                            return Err(QueryTaskExecutionFailure::new(
8628                                "query_workflow_state_unavailable",
8629                                "workflow replay yielded without a durable command",
8630                                "QueryWorkflowStateUnavailable",
8631                            ));
8632                        }
8633                    }
8634                }
8635                let state = (invocation.snapshot)().map_err(|error| {
8636                    QueryTaskExecutionFailure::new(
8637                        "query_workflow_state_unavailable",
8638                        format!("cannot snapshot replayed workflow state: {error}"),
8639                        "QueryWorkflowStateUnavailable",
8640                    )
8641                })?;
8642                handler(context, state, args).map_err(|message| {
8643                    QueryTaskExecutionFailure::new(
8644                        "query_workflow_state_unavailable",
8645                        message,
8646                        "QueryWorkflowStateUnavailable",
8647                    )
8648                })?
8649            }
8650        };
8651
8652        future.await.map_err(|error| {
8653            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8654        })
8655    }
8656
8657    #[cfg(test)]
8658    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8659        Ok(self.execute_workflow_task_decision(task)?.commands)
8660    }
8661
8662    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8663        self.execute_workflow_task_decision_with_cancellation(task, None)
8664    }
8665
8666    fn execute_workflow_task_decision_with_cancellation(
8667        &self,
8668        task: WorkflowTask,
8669        observation: Option<&CancellationRequest>,
8670    ) -> Result<WorkflowTaskDecision> {
8671        match self.prepare_workflow_task_execution(task, observation)? {
8672            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8673            PreparedWorkflowTask::Execution {
8674                task,
8675                context,
8676                mut future,
8677            } => {
8678                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8679                self.finish_workflow_task_execution(&task, &context, outcome)
8680            }
8681        }
8682    }
8683
8684    fn prepare_workflow_task_execution(
8685        &self,
8686        task: WorkflowTask,
8687        observation: Option<&CancellationRequest>,
8688    ) -> Result<PreparedWorkflowTask> {
8689        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8690            && !self.cooperative_cancellation_enabled
8691        {
8692            return Err(Error::CancellationScopeExecutionUnavailable);
8693        }
8694        validate_workflow_task_payloads(&task)?;
8695        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8696            &task.history_events,
8697            self.allow_cancellation_scope_authoring,
8698            self.allow_cancellation_scope_delivery,
8699        )?;
8700        let cancellation_history = if let Some(observation) = observation {
8701            observation.validate_observation()?;
8702            cooperative_cancellation::cancellation_claim(&task)?;
8703            let canonical = CancellationHistory::from_events(
8704                &task.history_events,
8705                task.run_id.as_deref().unwrap_or_default(),
8706                Some(observation),
8707            )?;
8708            if canonical.request_index >= task.history_events.len() {
8709                return Err(Error::InvalidCooperativeCancellation(
8710                    "workflow replay requires the observed canonical request".into(),
8711                ));
8712            }
8713            Some(canonical)
8714        } else {
8715            None
8716        };
8717        if let Some(update_id) = task
8718            .workflow_update_id
8719            .as_deref()
8720            .filter(|update_id| !update_id.is_empty())
8721        {
8722            if self.allow_cancellation_scope_delivery {
8723                return Err(Error::CancellationScopeExecutionUnavailable);
8724            }
8725            CancellationHistory::from_events(
8726                &task.history_events,
8727                task.run_id.as_deref().unwrap_or_default(),
8728                None,
8729            )?;
8730            return self
8731                .execute_update_task(&task, update_id)
8732                .map(WorkflowTaskDecision::without_message_streams)
8733                .map(PreparedWorkflowTask::Decision);
8734        }
8735
8736        let workflow = self
8737            .workflows
8738            .get(&task.workflow_type)
8739            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8740        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8741        let resume_signal = decode_resume_signal(&task)?;
8742        let history_budget = WorkflowHistoryBudget {
8743            event_count: task
8744                .total_history_events
8745                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8746            size_bytes: task.history_size_bytes,
8747            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8748            pressure: task.history_budget_pressure.clone(),
8749        };
8750        let workflow_command_identity = task
8751            .workflow_command_id
8752            .clone()
8753            .filter(|identity| !identity.is_empty())
8754            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8755            .unwrap_or_default();
8756        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8757            task.history_events.clone(),
8758            task.workflow_id.clone(),
8759            task.run_id.clone(),
8760            self.task_queue.clone(),
8761            task.payload_codec.clone(),
8762            resume_signal,
8763            self.allow_cancellation_scope_authoring,
8764            self.allow_cancellation_scope_delivery,
8765        )?;
8766        workflow_state.history_budget = history_budget;
8767        workflow_state.workflow_command_identity = workflow_command_identity;
8768        if let Some(canonical) = cancellation_history {
8769            workflow_state.cancellation_history = canonical;
8770            workflow_state.cancellation_delivery_enabled = true;
8771        }
8772        if workflow_state.cancellation_history.request.is_none() {
8773            workflow_state.cancel_requested = task.cancel_requested;
8774        }
8775        let state = Arc::new(Mutex::new(workflow_state));
8776        let ctx = WorkflowContext {
8777            state,
8778            cancellation_scope_id: "root".into(),
8779        };
8780        let future = (workflow.execute)(ctx.clone(), input);
8781        Ok(PreparedWorkflowTask::Execution {
8782            task,
8783            context: ctx,
8784            future,
8785        })
8786    }
8787
8788    fn poll_workflow_future(
8789        ctx: &WorkflowContext,
8790        future: &mut WorkflowFuture,
8791    ) -> Result<Poll<Result<AvroValue>>> {
8792        let mut cx = TaskContext::from_waker(noop_waker_ref());
8793        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8794        Ok(future.as_mut().poll(&mut cx))
8795    }
8796
8797    fn finish_workflow_task_execution(
8798        &self,
8799        task: &WorkflowTask,
8800        ctx: &WorkflowContext,
8801        outcome: Poll<Result<AvroValue>>,
8802    ) -> Result<WorkflowTaskDecision> {
8803        if !ctx
8804            .state
8805            .lock()
8806            .map_err(|_| Error::WorkflowStatePoisoned)?
8807            .local_activity_requests
8808            .is_empty()
8809        {
8810            return Err(Error::CooperativeCancellationUnavailable(
8811                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8812            ));
8813        }
8814        let awaiting_canonical_boundary = {
8815            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8816            state.cancellation_delivery_intent.is_some()
8817                || state.cancellation_scope_opening.is_some()
8818                || state
8819                    .scope_delivery
8820                    .as_ref()
8821                    .is_some_and(|replay| replay.intent.is_some())
8822        };
8823        if awaiting_canonical_boundary {
8824            // A private delivery intent never becomes an application error.
8825            // Even a custom future which ignores a pending durable call cannot
8826            // publish terminal commands before canonical delivery and replay.
8827            if let Poll::Ready(Err(error)) = outcome {
8828                if workflow_task_integrity_error(&error) {
8829                    return Err(error);
8830                }
8831            }
8832            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8833        }
8834
8835        match outcome {
8836            Poll::Ready(Ok(result)) => {
8837                ctx.ensure_history_consumed()?;
8838                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8839                let mut commands = ctx.take_commands()?;
8840                commands.push(json!({
8841                    "type": "complete_workflow",
8842                    "result": result
8843                }));
8844                self.message_stream_decision(&ctx, commands)
8845            }
8846            Poll::Ready(Err(error)) => {
8847                if let Error::ContinueAsNew(request) = error {
8848                    let mut commands = ctx.take_commands()?;
8849                    if let Some(command) = ctx.continue_as_new_command(request)? {
8850                        commands.push(command);
8851                    }
8852                    ctx.ensure_history_consumed()?;
8853                    return self.message_stream_decision(&ctx, commands);
8854                }
8855                if workflow_task_integrity_error(&error) {
8856                    // Replay and protocol failures describe the workflow-task
8857                    // decision itself. Preserve their specific failure reason
8858                    // instead of replacing it with the derivative fact that
8859                    // recorded commands remain unconsumed.
8860                    return Err(error);
8861                }
8862                // A handler error must not hide a committed durable command that
8863                // upgraded workflow code no longer consumes.
8864                ctx.ensure_history_consumed()?;
8865                let mut commands = ctx.take_commands()?;
8866                commands.push(workflow_failure_command(
8867                    &error,
8868                    recorded_activity_failure_boundary(&ctx, &error),
8869                ));
8870                self.message_stream_decision(&ctx, commands)
8871            }
8872            Poll::Pending => {
8873                let commands = ctx.take_commands()?;
8874                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8875                    Err(Error::WorkflowYieldedWithoutCommand)
8876                } else {
8877                    self.message_stream_decision(&ctx, commands)
8878                }
8879            }
8880        }
8881    }
8882
8883    fn message_stream_decision(
8884        &self,
8885        ctx: &WorkflowContext,
8886        commands: Vec<Value>,
8887    ) -> Result<WorkflowTaskDecision> {
8888        if !self.cooperative_cancellation_enabled
8889            && commands.iter().any(|command| {
8890                command["type"] == "schedule_activity"
8891                    && command.get("cancellation_policy").is_some()
8892            })
8893        {
8894            return Err(Error::CooperativeCancellationUnavailable(format!(
8895                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8896                self.worker_id,
8897            )));
8898        }
8899        if !self.cooperative_cancellation_enabled
8900            && commands.iter().any(|command| {
8901                command["type"] == "start_child_workflow"
8902                    && (command["parent_close_policy"] == "request_cancellation"
8903                        || matches!(
8904                            command["cancellation_policy"].as_str(),
8905                            Some("try_cancel" | "wait_cancellation_completed")
8906                        ))
8907            })
8908        {
8909            return Err(Error::CooperativeCancellationUnavailable(format!(
8910                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8911                self.worker_id,
8912            )));
8913        }
8914        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8915        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8916        let scope_delivery = state
8917            .scope_delivery
8918            .as_ref()
8919            .and_then(|replay| replay.intent.clone());
8920        if scope_delivery
8921            .as_ref()
8922            .is_some_and(|intent| commands.len() != intent.command_count)
8923        {
8924            return Err(invalid_recorded_history(
8925                "cancellation_scope_pending_call_escaped",
8926                scope_delivery.as_ref().unwrap().boundary.sequence,
8927                "commands preceding the pending scoped call",
8928                "commands after suspension",
8929                "workflow cannot publish beyond an uncommitted scope delivery",
8930            ));
8931        }
8932        if let Some(opening) = &state.cancellation_scope_opening {
8933            if commands.len() != opening.command_count {
8934                return Err(invalid_recorded_history(
8935                    "cancellation_scope_pending_call_escaped",
8936                    opening.sequence,
8937                    "commands before original scope opening",
8938                    "commands after suspended opening",
8939                    "workflow cannot publish beyond an uncommitted scope opening",
8940                ));
8941            }
8942        }
8943        if state.cancellation_delivery_intent.is_some()
8944            && commands.len() != state.cancellation_delivery_command_count
8945        {
8946            return Err(invalid_recorded_history(
8947                "cooperative_cancellation_pending_call_escaped",
8948                state
8949                    .cancellation_delivery_intent
8950                    .as_ref()
8951                    .expect("pending delivery")
8952                    .sequence,
8953                "only commands preceding the pending cancellation call",
8954                "commands authored after a suspended call",
8955                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8956            ));
8957        }
8958        Ok(WorkflowTaskDecision {
8959            commands,
8960            message_stream_cursors,
8961            message_stream_waits,
8962            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8963            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8964            cancellation_scope_delivery: scope_delivery,
8965        })
8966    }
8967
8968    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8969        if !self.workflows.contains_key(&task.workflow_type) {
8970            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8971        }
8972
8973        let accepted = task.history_events.iter().rev().find_map(|event| {
8974            (event.event_type == "UpdateAccepted"
8975                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8976            .then_some(&event.payload)
8977        });
8978        let update_name = accepted
8979            .and_then(|payload| payload.get("update_name"))
8980            .and_then(Value::as_str)
8981            .or(task.update_name.as_deref())
8982            .unwrap_or_default();
8983        let Some(handler) = self
8984            .updates
8985            .get(&task.workflow_type)
8986            .and_then(|handlers| handlers.get(update_name))
8987        else {
8988            return Ok(vec![json!({
8989                "type": "fail_update",
8990                "update_id": update_id,
8991                "message": format!(
8992                    "no update handler is registered for {}.{update_name}",
8993                    task.workflow_type
8994                ),
8995                "exception_type": "UnknownUpdate",
8996                "non_retryable": true,
8997            })]);
8998        };
8999        let arguments = accepted
9000            .and_then(|payload| payload.get("arguments"))
9001            .or(task.arguments.as_ref());
9002        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9003        let workflow_input_avro_value =
9004            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9005        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9006        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9007        let context = QueryContext {
9008            workflow_id: task.workflow_id.clone(),
9009            run_id: task.run_id.clone(),
9010            workflow_type: task.workflow_type.clone(),
9011            run_status: Some("running".to_string()),
9012            workflow_input,
9013            workflow_input_avro_value,
9014            history_events: Arc::new(task.history_events.clone()),
9015            signal_events: Arc::new(signal_events),
9016        };
9017        let mut future = handler(context, arguments);
9018        let mut cx = TaskContext::from_waker(noop_waker_ref());
9019
9020        match future.as_mut().poll(&mut cx) {
9021            Poll::Ready(Ok(result)) => Ok(vec![json!({
9022                "type": "complete_update",
9023                "update_id": update_id,
9024                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9025            })]),
9026            Poll::Ready(Err(error)) => Ok(vec![json!({
9027                "type": "fail_update",
9028                "update_id": update_id,
9029                "message": error.to_string(),
9030                "exception_type": "UpdateFailed",
9031                "non_retryable": true,
9032            })]),
9033            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9034        }
9035    }
9036
9037    #[cfg(test)]
9038    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9039        self.execute_session_activity_task(task, None, None).await
9040    }
9041
9042    async fn execute_session_activity_task(
9043        &self,
9044        task: ActivityTask,
9045        worker_session: Option<WorkerSession>,
9046        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9047    ) -> Result<AvroValue> {
9048        validate_activity_task_payloads(&task)?;
9049        if worker_session.is_some() {
9050            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9051                || task
9052                    .activity_attempt_id
9053                    .as_deref()
9054                    .or(task.attempt_id.as_deref())
9055                    .is_none_or(str::is_empty)
9056                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9057            {
9058                return Err(Error::ActivityExecutionAbandoned(
9059                    "session activity requires this worker's exact immutable claim".into(),
9060                ));
9061            }
9062        }
9063
9064        let handler = self
9065            .activities
9066            .get(&task.activity_type)
9067            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9068        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9069        let attempt_id = task
9070            .activity_attempt_id
9071            .clone()
9072            .or(task.attempt_id.clone())
9073            .unwrap_or_default();
9074        let lease_owner = task
9075            .lease_owner
9076            .clone()
9077            .unwrap_or_else(|| self.worker_id.clone());
9078        let session = worker_session.clone();
9079        let ctx = ActivityContext {
9080            client: self.client.clone(),
9081            task_id: task.task_id,
9082            activity_attempt_id: attempt_id,
9083            lease_owner,
9084            activity_type: task.activity_type,
9085            attempt_number: task.attempt_number,
9086            task_queue: self.task_queue.clone(),
9087            worker_id: self.worker_id.clone(),
9088            claim_guard: None,
9089            local_heartbeats: None,
9090            worker_session,
9091        };
9092
9093        if let Some(claim) = hydration_claim {
9094            claim.confirm(&self.client).await?;
9095        }
9096        let callback = handler(ctx, args);
9097        if let Some(session) = session {
9098            tokio::select! {
9099                biased;
9100                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9101                result = callback => if session.active() { result } else {
9102                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9103                },
9104            }
9105        } else {
9106            callback.await
9107        }
9108    }
9109}
9110
9111fn poller_result(
9112    kind: &str,
9113    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9114) -> Result<()> {
9115    match result {
9116        Ok(result) => result,
9117        Err(error) => Err(Error::WorkerLoop(format!(
9118            "{kind} poller join error: {error}"
9119        ))),
9120    }
9121}
9122
9123fn optional_poller_result(
9124    kind: &str,
9125    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9126) -> Result<()> {
9127    match result {
9128        Some(result) => poller_result(kind, result),
9129        None => Ok(()),
9130    }
9131}
9132
9133async fn join_pollers(
9134    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9135    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9136    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9137) -> Result<()> {
9138    let mut first_error = None;
9139
9140    if let Some(handle) = workflow_poller {
9141        if let Err(error) = poller_result("workflow", handle.await) {
9142            first_error.get_or_insert(error);
9143        }
9144    }
9145
9146    if let Some(handle) = activity_poller {
9147        if let Err(error) = poller_result("activity", handle.await) {
9148            first_error.get_or_insert(error);
9149        }
9150    }
9151
9152    if let Some(handle) = query_poller {
9153        if let Err(error) = poller_result("query", handle.await) {
9154            first_error.get_or_insert(error);
9155        }
9156    }
9157
9158    if let Some(error) = first_error {
9159        Err(error)
9160    } else {
9161        Ok(())
9162    }
9163}
9164
9165fn default_worker_id() -> String {
9166    let millis = SystemTime::now()
9167        .duration_since(UNIX_EPOCH)
9168        .unwrap_or_default()
9169        .as_millis();
9170    format!("rust-worker-{}-{millis}", std::process::id())
9171}
9172
9173fn percent_encode_path_segment(segment: &str) -> String {
9174    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9175    let mut encoded = String::with_capacity(segment.len());
9176
9177    for byte in segment.bytes() {
9178        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9179            encoded.push(char::from(byte));
9180        } else {
9181            encoded.push('%');
9182            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9183            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9184        }
9185    }
9186
9187    encoded
9188}
9189
9190fn unique_request_id(prefix: &str) -> String {
9191    let nanos = SystemTime::now()
9192        .duration_since(UNIX_EPOCH)
9193        .unwrap_or_default()
9194        .as_nanos();
9195    format!("{prefix}-{}-{nanos}", std::process::id())
9196}
9197
9198#[derive(Debug)]
9199struct QueryTaskExecutionFailure {
9200    reason: String,
9201    message: String,
9202    failure_type: String,
9203}
9204
9205impl QueryTaskExecutionFailure {
9206    fn new(
9207        reason: impl Into<String>,
9208        message: impl Into<String>,
9209        failure_type: impl Into<String>,
9210    ) -> Self {
9211        Self {
9212            reason: reason.into(),
9213            message: message.into(),
9214            failure_type: failure_type.into(),
9215        }
9216    }
9217}
9218
9219/// Typed local state owned by one deterministic workflow invocation.
9220///
9221/// Use [`WorkflowInstance::update`] for the same state transitions during
9222/// ordinary execution and replay. A replayed query receives a detached
9223/// immutable `Arc<S>` rather than this mutation-capable handle.
9224#[derive(Clone, Debug)]
9225pub struct WorkflowInstance<S> {
9226    state: Arc<Mutex<S>>,
9227}
9228
9229impl<S> WorkflowInstance<S> {
9230    fn new(state: S) -> Self {
9231        Self {
9232            state: Arc::new(Mutex::new(state)),
9233        }
9234    }
9235
9236    /// Read the current workflow-instance state without changing it.
9237    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9238        let state = self
9239            .state
9240            .lock()
9241            .map_err(|_| Error::WorkflowStatePoisoned)?;
9242        Ok(reader(&state))
9243    }
9244
9245    /// Apply one deterministic workflow-instance state transition.
9246    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9247        let mut state = self
9248            .state
9249            .lock()
9250            .map_err(|_| Error::WorkflowStatePoisoned)?;
9251        Ok(transition(&mut state))
9252    }
9253}
9254
9255impl<S: Clone> WorkflowInstance<S> {
9256    fn snapshot(&self) -> Result<S> {
9257        self.read(Clone::clone)
9258    }
9259}
9260
9261#[derive(Clone, Debug, PartialEq)]
9262pub struct MessageStreamMessage {
9263    pub stream_name: String,
9264    pub message_id: String,
9265    pub position: u64,
9266    pub arguments: Vec<AvroValue>,
9267}
9268
9269#[derive(Clone, Debug)]
9270pub struct MessageStream {
9271    ctx: WorkflowContext,
9272    name: String,
9273}
9274
9275impl MessageStream {
9276    /// Wait for one message, then return a bounded currently-available batch.
9277    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9278        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9279            return Err(Error::Codec(format!(
9280                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9281            )));
9282        }
9283        loop {
9284            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9285                return Ok(batch);
9286            }
9287
9288            self.ctx.record_message_stream_wait(&self.name)?;
9289            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9290            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9291            self.ctx.buffer_message_stream_delivery(arguments)?;
9292            if let Some(sequence) = replay_wait_sequence {
9293                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9294            }
9295        }
9296    }
9297
9298    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9299        self.receive(1)
9300            .await?
9301            .into_iter()
9302            .next()
9303            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9304    }
9305}
9306
9307#[derive(Clone, Debug)]
9308pub struct WorkflowContext {
9309    state: Arc<Mutex<WorkflowState>>,
9310    cancellation_scope_id: String,
9311}
9312
9313fn valid_memo_key(key: &str) -> bool {
9314    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9315
9316    !key.is_empty()
9317        && key.len() <= 64
9318        && (numeric_candidate.is_empty()
9319            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9320        && key
9321            .bytes()
9322            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9323}
9324
9325fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9326    BASE64
9327        .decode(encode_avro_value(value)?.blob)
9328        .map(|bytes| bytes.len())
9329        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9330}
9331
9332fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9333    let AvroValue::Map(entries) = value else {
9334        return Err(Error::InvalidMemoUpdate(
9335            "entries must serialize to an Avro string-keyed map".to_string(),
9336        ));
9337    };
9338    if require_entries && entries.is_empty() {
9339        return Err(Error::InvalidMemoUpdate(
9340            "at least one entry is required".to_string(),
9341        ));
9342    }
9343    if entries.len() > MAX_MEMO_ENTRIES {
9344        return Err(Error::InvalidMemoUpdate(format!(
9345            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9346        )));
9347    }
9348
9349    for (key, value) in &entries {
9350        if !valid_memo_key(&key) {
9351            return Err(Error::InvalidMemoUpdate(
9352                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9353            ));
9354        }
9355        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9356            return Err(Error::InvalidMemoUpdate(format!(
9357                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9358            )));
9359        }
9360    }
9361
9362    let value = AvroValue::Map(entries);
9363    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9364        return Err(Error::InvalidMemoUpdate(format!(
9365            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9366        )));
9367    }
9368    Ok(value)
9369}
9370
9371fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9372    let object = envelope.as_object().ok_or_else(|| {
9373        Error::InvalidMemoUpdate(
9374            "history field must use the public {codec, blob} payload envelope".to_string(),
9375        )
9376    })?;
9377    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9378        return Err(Error::InvalidMemoUpdate(
9379            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9380        ));
9381    }
9382
9383    canonical_memo_entries(
9384        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9385        require_entries,
9386    )
9387}
9388
9389impl WorkflowContext {
9390    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9391        let name = name.into();
9392        if name.is_empty()
9393            || name.len() > 128
9394            || !name.bytes().all(|byte| {
9395                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9396            })
9397        {
9398            return Err(Error::Codec(
9399                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9400                    .to_string(),
9401            ));
9402        }
9403        Ok(MessageStream {
9404            ctx: self.clone(),
9405            name,
9406        })
9407    }
9408
9409    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9410        let mut state = self
9411            .state
9412            .lock()
9413            .map_err(|_| Error::WorkflowStatePoisoned)?;
9414        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9415        state
9416            .message_stream_waits
9417            .insert(name.to_string(), position);
9418        Ok(())
9419    }
9420
9421    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9422        let mut state = self
9423            .state
9424            .lock()
9425            .map_err(|_| Error::WorkflowStatePoisoned)?;
9426        let cursor = state
9427            .message_stream_cursors
9428            .get(&message.stream_name)
9429            .copied()
9430            .unwrap_or(0);
9431        if message.position <= cursor {
9432            return Ok(());
9433        }
9434        let pending = state
9435            .message_stream_messages
9436            .entry(message.stream_name.clone())
9437            .or_default();
9438        if pending.iter().any(|candidate| {
9439            candidate.position == message.position || candidate.message_id == message.message_id
9440        }) {
9441            return Ok(());
9442        }
9443        pending.push(message);
9444        pending.sort_by_key(|candidate| candidate.position);
9445        Ok(())
9446    }
9447
9448    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9449        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9450            match delivery {
9451                MessageStreamDelivery::Message(message) => {
9452                    let stream_name = message.stream_name.clone();
9453                    self.buffer_message_stream(message)?;
9454                    return Ok(Some(stream_name));
9455                }
9456                MessageStreamDelivery::Cursor {
9457                    stream_name,
9458                    through_position,
9459                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9460            }
9461        }
9462        Ok(None)
9463    }
9464
9465    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9466        let state = self
9467            .state
9468            .lock()
9469            .map_err(|_| Error::WorkflowStatePoisoned)?;
9470        Ok(match state.recorded_commands.get(state.command_cursor) {
9471            Some(RecordedCommand::SignalWait {
9472                sequence,
9473                signal_name,
9474                ..
9475            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9476            _ => None,
9477        })
9478    }
9479
9480    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9481        let (history, payload_codec) = {
9482            let state = self
9483                .state
9484                .lock()
9485                .map_err(|_| Error::WorkflowStatePoisoned)?;
9486            (
9487                Arc::clone(&state.history_events),
9488                state.payload_codec.clone(),
9489            )
9490        };
9491
9492        let Some(opened_index) = history.iter().position(|event| {
9493            event.event_type == "SignalWaitOpened"
9494                && durable_event_sequence(event) == Some(wait_sequence)
9495                && event.payload.get("signal_name").and_then(Value::as_str)
9496                    == Some(MESSAGE_STREAM_SIGNAL)
9497        }) else {
9498            return Ok(());
9499        };
9500        let boundary_index = history
9501            .iter()
9502            .enumerate()
9503            .skip(opened_index + 1)
9504            .find_map(|(index, event)| {
9505                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9506                    && is_authored_command_open_event(event))
9507                .then_some(index)
9508            })
9509            .unwrap_or(history.len());
9510
9511        for event in history[opened_index + 1..boundary_index]
9512            .iter()
9513            .filter(|event| {
9514                event.event_type == "SignalReceived"
9515                    && event.payload.get("signal_name").and_then(Value::as_str)
9516                        == Some(MESSAGE_STREAM_SIGNAL)
9517            })
9518        {
9519            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9520                .into_iter()
9521                .map(AvroValue::into_json)
9522                .collect::<Result<Vec<_>>>()?;
9523            self.buffer_message_stream_delivery(arguments)?;
9524        }
9525        Ok(())
9526    }
9527
9528    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9529        let mut state = self
9530            .state
9531            .lock()
9532            .map_err(|_| Error::WorkflowStatePoisoned)?;
9533        let cursor = state
9534            .message_stream_cursors
9535            .entry(name.to_string())
9536            .or_default();
9537        *cursor = (*cursor).max(through_position);
9538        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9539            pending.retain(|message| message.position > through_position);
9540        }
9541        Ok(())
9542    }
9543
9544    fn take_message_stream_batch(
9545        &self,
9546        name: &str,
9547        max_items: usize,
9548    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9549        let mut state = self
9550            .state
9551            .lock()
9552            .map_err(|_| Error::WorkflowStatePoisoned)?;
9553        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9554        let pending = state
9555            .message_stream_messages
9556            .entry(name.to_string())
9557            .or_default();
9558        let count = contiguous_message_stream_count(pending, cursor, max_items);
9559        if count == 0 {
9560            return Ok(None);
9561        }
9562        let batch = pending.drain(..count).collect::<Vec<_>>();
9563        let position = batch.last().map(|message| message.position).unwrap_or(0);
9564        state
9565            .message_stream_cursors
9566            .insert(name.to_string(), position);
9567        state.message_stream_waits.remove(name);
9568        Ok(Some(batch))
9569    }
9570
9571    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9572        let state = self
9573            .state
9574            .lock()
9575            .map_err(|_| Error::WorkflowStatePoisoned)?;
9576        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9577        cursors.sort_by_key(|(name, _)| *name);
9578        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9579        waits.sort_by_key(|(name, _)| *name);
9580        Ok((
9581            cursors
9582                .into_iter()
9583                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9584                .collect(),
9585            waits
9586                .into_iter()
9587                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9588                .collect(),
9589        ))
9590    }
9591    /// Identity of the parent workflow currently being replayed.
9592    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9593        let state = self
9594            .state
9595            .lock()
9596            .map_err(|_| Error::WorkflowStatePoisoned)?;
9597        Ok(WorkflowIdentity {
9598            workflow_id: state.workflow_id.clone(),
9599            run_id: state.run_id.clone(),
9600        })
9601    }
9602
9603    /// Return the server-published history budget for this workflow task.
9604    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9605        let state = self
9606            .state
9607            .lock()
9608            .map_err(|_| Error::WorkflowStatePoisoned)?;
9609        Ok(state.history_budget.clone())
9610    }
9611
9612    /// Continue this workflow instance as a fresh run with replacement arguments.
9613    ///
9614    /// Return this value directly from the workflow handler. The worker converts
9615    /// it to the terminal protocol command only after replay has consumed every
9616    /// recorded durable command.
9617    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9618        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9619    }
9620
9621    /// Continue as new with optional workflow-type and task-queue overrides.
9622    pub fn continue_as_new_with_options<T: Serialize>(
9623        &self,
9624        options: ContinueAsNewOptions,
9625        args: T,
9626    ) -> Result<Value> {
9627        options.validate()?;
9628        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9629            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9630            options,
9631        }))
9632    }
9633
9634    pub fn activity<T: Serialize>(
9635        &self,
9636        activity_type: impl Into<String>,
9637        args: T,
9638    ) -> ActivityCall {
9639        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9640    }
9641
9642    pub fn activity_on_queue<T, Q>(
9643        &self,
9644        activity_type: impl Into<String>,
9645        task_queue: Option<Q>,
9646        args: T,
9647    ) -> ActivityCall
9648    where
9649        T: Serialize,
9650        Q: Into<String>,
9651    {
9652        let mut options = ActivityOptions::new();
9653        options.task_queue = task_queue.map(Into::into);
9654        self.activity_with_options(activity_type, options, args)
9655    }
9656
9657    /// Schedule one durable activity with retry, routing, and timeout options.
9658    ///
9659    /// Options are validated before the command is emitted. Once the command is
9660    /// recorded, replay consumes the same activity lifecycle at this command
9661    /// position and never emits a duplicate schedule.
9662    ///
9663    /// ```no_run
9664    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9665    /// # use std::time::Duration;
9666    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9667    /// let result = ctx
9668    ///     .activity_with_options(
9669    ///         "charge-card",
9670    ///         ActivityOptions::new()
9671    ///             .task_queue("payments")
9672    ///             .retry_policy(
9673    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9674    ///                     Duration::from_secs(1),
9675    ///                     2,
9676    ///                     Some(Duration::from_secs(30)),
9677    ///                 ),
9678    ///             )
9679    ///             .start_to_close_timeout(Duration::from_secs(60))
9680    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9681    ///             .heartbeat_timeout(Duration::from_secs(15)),
9682    ///         json!([{"order_id": "order-42"}]),
9683    ///     )
9684    ///     .await;
9685    /// match result {
9686    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9687    ///         "reason": failure.reason,
9688    ///         "timeout_kind": failure.timeout_kind,
9689    ///     })),
9690    ///     other => other,
9691    /// }
9692    /// # }
9693    /// ```
9694    pub fn activity_with_options<T: Serialize>(
9695        &self,
9696        activity_type: impl Into<String>,
9697        options: ActivityOptions,
9698        args: T,
9699    ) -> ActivityCall {
9700        ActivityCall {
9701            ctx: self.clone(),
9702            activity_type: activity_type.into(),
9703            options,
9704            worker_session: None,
9705            args: Some(AvroValue::from_serialize(&args)),
9706            scheduled: false,
9707            local: false,
9708            local_result: None,
9709            parallel_group_path: Vec::new(),
9710        }
9711    }
9712
9713    pub async fn activity_avro_value<T: Serialize>(
9714        &self,
9715        activity_type: impl Into<String>,
9716        args: T,
9717    ) -> Result<AvroValue> {
9718        let mut call = self.activity(activity_type, args);
9719        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9720    }
9721
9722    pub async fn activity_avro_value_with_options<T: Serialize>(
9723        &self,
9724        activity_type: impl Into<String>,
9725        options: ActivityOptions,
9726        args: T,
9727    ) -> Result<AvroValue> {
9728        let mut call = self.activity_with_options(activity_type, options, args);
9729        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9730    }
9731
9732    /// Schedule an activity with a Serde request and decode its Serde result.
9733    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9734    where
9735        I: Serialize,
9736        O: DeserializeOwned,
9737    {
9738        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9739            .await
9740    }
9741
9742    /// Schedule an activity with options and decode its result into `O`.
9743    ///
9744    /// Both directions use the fixed Avro Value codec. In particular, this
9745    /// method does not deserialize the JSON-safe inspection projection returned
9746    /// by the dynamic [`ActivityCall`] future.
9747    pub async fn activity_typed_with_options<I, O>(
9748        &self,
9749        activity_type: impl Into<String>,
9750        options: ActivityOptions,
9751        args: I,
9752    ) -> Result<O>
9753    where
9754        I: Serialize,
9755        O: DeserializeOwned,
9756    {
9757        let activity_type = activity_type.into();
9758        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9759            handler_type_error::<I>(
9760                HandlerKind::Activity,
9761                &activity_type,
9762                HandlerValueKind::Input,
9763                error.to_string(),
9764            )
9765        });
9766        let mut call = ActivityCall {
9767            ctx: self.clone(),
9768            activity_type: activity_type.clone(),
9769            options,
9770            worker_session: None,
9771            args: Some(encoded),
9772            scheduled: false,
9773            local: false,
9774            local_result: None,
9775            parallel_group_path: Vec::new(),
9776        };
9777        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9778        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9779    }
9780
9781    /// Schedule and join a deterministic activity/child/timer group.
9782    ///
9783    /// Nested groups retain their input shape. Every durable leaf is scheduled
9784    /// before this future yields, results are assembled by declaration order,
9785    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9786    /// declaration path, stable group metadata, and completed siblings.
9787    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9788        ParallelCall::new(self.clone(), operations)
9789    }
9790
9791    /// Alias for [`WorkflowContext::parallel`].
9792    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9793        self.parallel(operations)
9794    }
9795
9796    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9797    pub async fn parallel_avro_value(
9798        &self,
9799        operations: Vec<ParallelOperation>,
9800    ) -> Result<Vec<ParallelAvroResult>> {
9801        let mut call = self.parallel(operations);
9802        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9803    }
9804
9805    /// Start every durable operation and resume from the one winner persisted
9806    /// by Server. Non-winning operations continue and remain addressable.
9807    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9808        let operations = operations
9809            .into_iter()
9810            .enumerate()
9811            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9812            .collect();
9813        SelectCall::new(self.clone(), operations)
9814    }
9815
9816    /// Named-key variant of [`WorkflowContext::select`].
9817    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9818    where
9819        K: Into<SelectionKey>,
9820    {
9821        SelectCall::new(
9822            self.clone(),
9823            operations
9824                .into_iter()
9825                .map(|(key, operation)| (key.into(), operation))
9826                .collect(),
9827        )
9828    }
9829
9830    /// Create a workflow-local deterministic compensation registry.
9831    pub fn saga(&self) -> Saga {
9832        Saga::new(self.clone())
9833    }
9834
9835    /// Whether cancellation has reached this replay's authored boundary.
9836    ///
9837    /// Server's current `/cancel` route is terminal and does not set this flag.
9838    /// A canonical service request remains pending until its committed delivery
9839    /// is consumed. Request observation alone does not authorize an exception.
9840    pub fn is_cancellation_requested(&self) -> Result<bool> {
9841        let state = self
9842            .state
9843            .lock()
9844            .map_err(|_| Error::WorkflowStatePoisoned)?;
9845        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9846            return Ok(state
9847                .scope_delivery
9848                .as_ref()
9849                .unwrap()
9850                .contexts
9851                .contains_key(&self.cancellation_scope_id));
9852        }
9853        Ok(state.cancel_requested
9854            || state
9855                .scope_delivery
9856                .as_ref()
9857                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9858    }
9859
9860    /// Raise a typed cooperative cancellation at an author-controlled point.
9861    ///
9862    /// Passing this result to [`Saga::finish`] compensates already registered
9863    /// forward steps before the cancellation remains the initiating outcome.
9864    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9865        let mut state = self
9866            .state
9867            .lock()
9868            .map_err(|_| Error::WorkflowStatePoisoned)?;
9869        if state.cancellation_shield_depth == 0 {
9870            if let Some(replay) = &state.scope_delivery {
9871                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9872                    let delivered = replay
9873                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9874                        .ok_or_else(|| {
9875                            Error::InvalidCooperativeCancellation(
9876                                "scoped request lacks its consumed original delivery".into(),
9877                            )
9878                        })?;
9879                    return Err(Error::CancellationScopeRequested(
9880                        CancellationScopeRequested {
9881                            context: context
9882                                .clone()
9883                                .with_replay(Some(Arc::downgrade(&self.state))),
9884                            delivery: delivered.boundary.clone(),
9885                        },
9886                    ));
9887                }
9888            }
9889        }
9890        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9891            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9892                return Ok(());
9893            }
9894            return Err(state.cancellation_error());
9895        }
9896        Ok(())
9897    }
9898
9899    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9900        SignalCall {
9901            ctx: self.clone(),
9902            signal_name: signal_name.into(),
9903            runtime_reserved_allowed: false,
9904            opened_wait: false,
9905            matched_pending: false,
9906            parallel_group_path: Vec::new(),
9907        }
9908    }
9909
9910    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9911        SignalCall {
9912            ctx: self.clone(),
9913            signal_name: signal_name.into(),
9914            runtime_reserved_allowed: true,
9915            opened_wait: false,
9916            matched_pending: false,
9917            parallel_group_path: Vec::new(),
9918        }
9919    }
9920
9921    pub async fn wait_signal_avro_value(
9922        &self,
9923        signal_name: impl Into<String>,
9924    ) -> Result<Vec<AvroValue>> {
9925        let mut call = self.wait_signal(signal_name);
9926        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9927    }
9928
9929    /// Return every committed signal argument list with the given name.
9930    ///
9931    /// This history-backed view is deterministic and is intended for
9932    /// condition predicates that must be re-evaluated after a signal while the
9933    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9934    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9935        self.signals_avro_value(signal_name)?
9936            .into_iter()
9937            .map(|arguments| {
9938                arguments
9939                    .into_iter()
9940                    .map(AvroValue::into_json)
9941                    .collect::<Result<Vec<_>>>()
9942            })
9943            .collect()
9944    }
9945
9946    /// Lossless fixed Avro Value view of committed signals with the given name.
9947    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9948        let state = self
9949            .state
9950            .lock()
9951            .map_err(|_| Error::WorkflowStatePoisoned)?;
9952        state
9953            .history_events
9954            .iter()
9955            .filter(|event| {
9956                event.event_type == "SignalReceived"
9957                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9958            })
9959            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9960            .collect()
9961    }
9962
9963    /// Return every committed update argument list with the given name.
9964    ///
9965    /// Accepted and applied records for the same update ID are de-duplicated.
9966    /// A Server task created after an update therefore replays the workflow and
9967    /// re-evaluates an open condition without application polling.
9968    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9969        self.updates_avro_value(update_name)?
9970            .into_iter()
9971            .map(|arguments| {
9972                arguments
9973                    .into_iter()
9974                    .map(AvroValue::into_json)
9975                    .collect::<Result<Vec<_>>>()
9976            })
9977            .collect()
9978    }
9979
9980    /// Lossless fixed Avro Value view of committed updates with the given name.
9981    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9982        let state = self
9983            .state
9984            .lock()
9985            .map_err(|_| Error::WorkflowStatePoisoned)?;
9986        let mut seen = Vec::new();
9987        let mut updates = Vec::new();
9988        for event in state.history_events.iter() {
9989            if !matches!(
9990                event.event_type.as_str(),
9991                "UpdateAccepted" | "UpdateApplied"
9992            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9993                || event.payload.get("arguments").is_none()
9994            {
9995                continue;
9996            }
9997            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9998                if seen.iter().any(|recorded| recorded == update_id) {
9999                    continue;
10000                }
10001                seen.push(update_id.to_string());
10002            }
10003            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10004        }
10005        Ok(updates)
10006    }
10007
10008    /// Wait for a deterministic predicate to become true or for its durable
10009    /// timeout to elapse.
10010    ///
10011    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10012    /// predicate tokens automatically change the recorded definition
10013    /// fingerprint. Direct callers must provide an equally stable identity in
10014    /// [`ConditionWaitOptions`].
10015    pub fn wait_condition<F>(
10016        &self,
10017        options: ConditionWaitOptions,
10018        predicate: F,
10019    ) -> ConditionWaitCall
10020    where
10021        F: Fn() -> Result<bool> + Send + 'static,
10022    {
10023        ConditionWaitCall {
10024            ctx: self.clone(),
10025            options,
10026            predicate: Box::new(predicate),
10027            occurrence_id: None,
10028            opened_wait: false,
10029            parallel_group_path: Vec::new(),
10030        }
10031    }
10032
10033    /// Wait for server-backed durable time without blocking the worker executor.
10034    ///
10035    /// Polling this future emits one `start_timer` command and yields. The
10036    /// server records the deadline, so neither worker nor server restarts reset
10037    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10038    /// `TimerFired` pair at the same position in the shared durable-command
10039    /// stream, with matching sequence, timer identity, and delay. Sub-second
10040    /// durations round up because protocol deadlines use whole seconds.
10041    ///
10042    /// ```no_run
10043    /// # use durable_workflow::{json, Client, Worker};
10044    /// # use std::time::Duration;
10045    /// # fn configure(client: Client) {
10046    /// let mut worker = Worker::new(client, "rust-workers");
10047    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10048    ///     ctx.sleep(Duration::from_secs(5)).await?;
10049    ///     Ok(json!({"status": "timer fired"}))
10050    /// });
10051    /// # }
10052    /// ```
10053    pub fn sleep(&self, duration: Duration) -> TimerCall {
10054        let delay_seconds = duration
10055            .as_secs()
10056            .checked_add(u64::from(duration.subsec_nanos() > 0));
10057        TimerCall {
10058            ctx: self.clone(),
10059            delay_seconds,
10060            scheduled: false,
10061            matched_pending: false,
10062            parallel_group_path: Vec::new(),
10063        }
10064    }
10065
10066    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10067    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10068        self.sleep(duration)
10069    }
10070
10071    /// Evaluate a non-deterministic callback once and durably record its typed value.
10072    ///
10073    /// On replay the callback is not invoked: the value is decoded from the
10074    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10075    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10076    /// small values that must remain fixed for the lifetime of a workflow run.
10077    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10078    where
10079        T: Serialize + DeserializeOwned,
10080        F: FnOnce() -> T,
10081    {
10082        {
10083            let mut state = self
10084                .state
10085                .lock()
10086                .map_err(|_| Error::WorkflowStatePoisoned)?;
10087            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10088                return match recorded {
10089                    RecordedCommand::SideEffect { sequence, value } => {
10090                        state.command_cursor += 1;
10091                        value.deserialize().map_err(|error| {
10092                            Error::NonDeterministicReplay(ReplayFailure::new(
10093                                "side_effect_type_mismatch",
10094                                Some(sequence),
10095                                Some(std::any::type_name::<T>().to_string()),
10096                                Some(error.to_string()),
10097                                "recorded side-effect value is incompatible with the requested Rust type",
10098                            ))
10099                        })
10100                    }
10101                    other => Err(command_mismatch(&other, "side effect")),
10102                };
10103            }
10104        }
10105
10106        let value = callback();
10107        let avro_value = AvroValue::from_serialize(&value)?;
10108        let mut state = self
10109            .state
10110            .lock()
10111            .map_err(|_| Error::WorkflowStatePoisoned)?;
10112        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10113        state.commands.push(json!({
10114            "type": "record_side_effect",
10115            "result": result,
10116        }));
10117        Ok(value)
10118    }
10119
10120    /// Record or replay a lossless fixed Avro Value side effect.
10121    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10122    where
10123        F: FnOnce() -> AvroValue,
10124    {
10125        {
10126            let mut state = self
10127                .state
10128                .lock()
10129                .map_err(|_| Error::WorkflowStatePoisoned)?;
10130            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10131                return match recorded {
10132                    RecordedCommand::SideEffect { value, .. } => {
10133                        state.command_cursor += 1;
10134                        Ok(value)
10135                    }
10136                    other => Err(command_mismatch(&other, "side effect")),
10137                };
10138            }
10139        }
10140
10141        let value = callback();
10142        let mut state = self
10143            .state
10144            .lock()
10145            .map_err(|_| Error::WorkflowStatePoisoned)?;
10146        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10147        state.commands.push(json!({
10148            "type": "record_side_effect",
10149            "result": result,
10150        }));
10151        Ok(value)
10152    }
10153
10154    /// Append output items at a deterministic workflow command boundary.
10155    ///
10156    /// Stable idempotency keys are derived from the server-provided durable
10157    /// workflow command identity, command ordinal, and item index. Replay
10158    /// consumes the recorded side effect and never emits another append.
10159    pub fn append_workflow_stream(
10160        &self,
10161        stream_name: impl Into<String>,
10162        items: &[WorkflowStreamAppendItem],
10163        max_pending_items: Option<u64>,
10164    ) -> Result<()> {
10165        if items.is_empty() {
10166            return Err(Error::Codec(
10167                "workflow_stream_items_empty: append requires at least one item".to_string(),
10168            ));
10169        }
10170        if max_pending_items == Some(0) {
10171            return Err(Error::Codec(
10172                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10173                    .to_string(),
10174            ));
10175        }
10176        let stream_name = stream_name.into();
10177        if stream_name.is_empty() {
10178            return Err(Error::Codec(
10179                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10180            ));
10181        }
10182
10183        let mut state = self
10184            .state
10185            .lock()
10186            .map_err(|_| Error::WorkflowStatePoisoned)?;
10187        let command_ordinal = state.workflow_stream_command_counter;
10188        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10189            state.workflow_stream_command_counter += 1;
10190            return match recorded {
10191                RecordedCommand::SideEffect { .. } => {
10192                    state.command_cursor += 1;
10193                    Ok(())
10194                }
10195                other => Err(command_mismatch(&other, "workflow stream append")),
10196            };
10197        }
10198
10199        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10200        state.workflow_stream_command_counter += 1;
10201        let wire_items = items
10202            .iter()
10203            .enumerate()
10204            .map(|(item_index, item)| {
10205                item.wire_value(Some(format!(
10206                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10207                )))
10208            })
10209            .collect::<Vec<_>>();
10210        let mut directive = json!({
10211            "operation": "append",
10212            "stream_name": stream_name,
10213            "command_identity": identity,
10214            "command_ordinal": command_ordinal,
10215            "items": wire_items,
10216        });
10217        if let Some(max_pending_items) = max_pending_items {
10218            directive["max_pending_items"] = json!(max_pending_items);
10219        }
10220        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10221        state.commands.push(json!({
10222            "type": "record_side_effect",
10223            "result": result,
10224            "workflow_stream": directive,
10225        }));
10226        Ok(())
10227    }
10228
10229    /// Close a run-scoped output stream at a deterministic command boundary.
10230    pub fn close_workflow_stream(
10231        &self,
10232        stream_name: impl Into<String>,
10233        retention_seconds: Option<u64>,
10234    ) -> Result<()> {
10235        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10236    }
10237
10238    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10239    pub fn error_workflow_stream(
10240        &self,
10241        stream_name: impl Into<String>,
10242        error_reason: impl Into<String>,
10243        retention_seconds: Option<u64>,
10244    ) -> Result<()> {
10245        let error_reason = error_reason.into();
10246        if error_reason.is_empty() {
10247            return Err(Error::Codec(
10248                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10249            ));
10250        }
10251        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10252    }
10253
10254    fn finish_workflow_stream(
10255        &self,
10256        stream_name: String,
10257        error_reason: Option<String>,
10258        retention_seconds: Option<u64>,
10259    ) -> Result<()> {
10260        if stream_name.is_empty() {
10261            return Err(Error::Codec(
10262                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10263            ));
10264        }
10265        if retention_seconds == Some(0) {
10266            return Err(Error::Codec(
10267                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10268            ));
10269        }
10270        let mut state = self
10271            .state
10272            .lock()
10273            .map_err(|_| Error::WorkflowStatePoisoned)?;
10274        let command_ordinal = state.workflow_stream_command_counter;
10275        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10276            state.workflow_stream_command_counter += 1;
10277            return match recorded {
10278                RecordedCommand::SideEffect { .. } => {
10279                    state.command_cursor += 1;
10280                    Ok(())
10281                }
10282                other => Err(command_mismatch(&other, "workflow stream close")),
10283            };
10284        }
10285        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10286        state.workflow_stream_command_counter += 1;
10287        let mut directive = json!({
10288            "operation": if error_reason.is_some() { "error" } else { "close" },
10289            "stream_name": stream_name,
10290            "command_identity": identity,
10291            "command_ordinal": command_ordinal,
10292        });
10293        if let Some(error_reason) = error_reason {
10294            directive["error_reason"] = json!(error_reason);
10295        }
10296        if let Some(retention_seconds) = retention_seconds {
10297            directive["retention_seconds"] = json!(retention_seconds);
10298        }
10299        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10300        state.commands.push(json!({
10301            "type": "record_side_effect",
10302            "result": result,
10303            "workflow_stream": directive,
10304        }));
10305        Ok(())
10306    }
10307
10308    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10309        let identity = state.workflow_command_identity.as_str();
10310        if identity.is_empty() {
10311            return Err(Error::MissingWorkflowCommandIdentity);
10312        }
10313        Ok(identity)
10314    }
10315
10316    /// Validate, emit, or replay a typed workflow search-attribute update.
10317    ///
10318    /// The command is non-blocking within a workflow decision, but its
10319    /// `SearchAttributesUpserted` event occupies the same deterministic command
10320    /// stream as activities, timers, conditions, and other durable operations.
10321    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10322        update.validate()?;
10323        let (attributes, attribute_types) = update.into_wire_parts();
10324        let mut state = self
10325            .state
10326            .lock()
10327            .map_err(|_| Error::WorkflowStatePoisoned)?;
10328
10329        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10330            return match recorded {
10331                RecordedCommand::SearchAttributes {
10332                    sequence,
10333                    attributes: recorded_attributes,
10334                    attribute_types: recorded_attribute_types,
10335                } => {
10336                    if recorded_attributes != attributes {
10337                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10338                            "search_attribute_value_mismatch",
10339                            Some(sequence),
10340                            Some(recorded_attributes.to_string()),
10341                            Some(attributes.to_string()),
10342                            "search-attribute values differ from the recorded durable command",
10343                        )));
10344                    }
10345                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10346                        if recorded_types != attribute_types {
10347                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10348                                "search_attribute_type_mismatch",
10349                                Some(sequence),
10350                                Some(json!(recorded_types).to_string()),
10351                                Some(json!(attribute_types).to_string()),
10352                                "search-attribute declared types differ from the recorded durable command",
10353                            )));
10354                        }
10355                    }
10356                    state.command_cursor += 1;
10357                    Ok(())
10358                }
10359                other => Err(command_mismatch(&other, "search-attribute update")),
10360            };
10361        }
10362
10363        let mut command = serde_json::Map::from_iter([
10364            ("type".to_string(), json!("upsert_search_attributes")),
10365            ("attributes".to_string(), attributes),
10366        ]);
10367        if !attribute_types.is_empty() {
10368            command.insert("attribute_types".to_string(), json!(attribute_types));
10369        }
10370        state.commands.push(Value::Object(command));
10371        Ok(())
10372    }
10373
10374    /// Record a UUIDv4 once and return the same UUID on every replay.
10375    pub fn uuid_v4(&self) -> Result<Uuid> {
10376        self.side_effect(Uuid::new_v4)
10377    }
10378
10379    /// Select the newest supported version for a change, or replay the version
10380    /// already committed for that stable change ID.
10381    ///
10382    /// An unmarked old history that reached its next durable operation, or
10383    /// already completed, selects `-1` when that version is supported. This
10384    /// leaves the original operation available and writes no additional marker.
10385    /// Consistent markers written by older workers retain their original ordered
10386    /// positions. Repeated calls consume a matching marker at the current cursor.
10387    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10388    pub fn get_version(
10389        &self,
10390        change_id: impl Into<String>,
10391        min_supported: i32,
10392        max_supported: i32,
10393    ) -> Result<i32> {
10394        let change_id = change_id.into();
10395        if change_id.trim().is_empty() {
10396            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10397                "version_change_id_invalid",
10398                None,
10399                Some("non-empty change ID".to_string()),
10400                Some(change_id),
10401                "version markers require a stable non-empty change ID",
10402            )));
10403        }
10404        if min_supported > max_supported {
10405            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10406                "version_range_invalid",
10407                None,
10408                Some("min_supported <= max_supported".to_string()),
10409                Some(format!("{min_supported}..={max_supported}")),
10410                "version marker supported range is invalid",
10411            )));
10412        }
10413
10414        let mut state = self
10415            .state
10416            .lock()
10417            .map_err(|_| Error::WorkflowStatePoisoned)?;
10418        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10419            if let Some(RecordedCommand::VersionMarker {
10420                sequence: alias_sequence,
10421                change_id: alias_change_id,
10422                version: alias_version,
10423            }) = state.recorded_commands.get(state.command_cursor)
10424            {
10425                if alias_change_id == &change_id {
10426                    if *alias_version != version {
10427                        return Err(invalid_recorded_history(
10428                            "version_marker_conflict",
10429                            *alias_sequence,
10430                            &format!("selected version {version} for change ID {change_id:?}"),
10431                            &format!("recorded version {alias_version}"),
10432                            "recorded marker conflicts with the decision already selected during replay",
10433                        ));
10434                    }
10435                    ensure_version_supported(
10436                        &change_id,
10437                        version,
10438                        min_supported,
10439                        max_supported,
10440                        *alias_sequence,
10441                    )?;
10442                    // Older workers could record the same decision again. Keep
10443                    // each physical boundary without skipping intervening work.
10444                    state.command_cursor += 1;
10445                    return Ok(version);
10446                }
10447            }
10448            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10449            return Ok(version);
10450        }
10451
10452        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10453            return match recorded {
10454                RecordedCommand::VersionMarker {
10455                    sequence,
10456                    change_id: recorded_change_id,
10457                    version,
10458                    ..
10459                } => {
10460                    if recorded_change_id != change_id {
10461                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10462                            "version_change_id_mismatch",
10463                            Some(sequence),
10464                            Some(recorded_change_id),
10465                            Some(change_id),
10466                            "recorded version marker change ID differs from current workflow code",
10467                        )));
10468                    }
10469                    ensure_version_supported(
10470                        &change_id,
10471                        version,
10472                        min_supported,
10473                        max_supported,
10474                        sequence,
10475                    )?;
10476                    state.command_cursor += 1;
10477                    state.version_markers.insert(change_id, (version, sequence));
10478                    Ok(version)
10479                }
10480                other => {
10481                    let version = -1;
10482                    let sequence = other.sequence();
10483                    ensure_version_supported(
10484                        &change_id,
10485                        version,
10486                        min_supported,
10487                        max_supported,
10488                        sequence,
10489                    )?;
10490                    // The existing operation proves this patch site was reached
10491                    // before its marker existed. Keep its original cursor.
10492                    state.version_markers.insert(change_id, (version, sequence));
10493                    Ok(version)
10494                }
10495            };
10496        }
10497
10498        if state
10499            .history_events
10500            .iter()
10501            .any(|event| event.event_type == "WorkflowCompleted")
10502        {
10503            let version = -1;
10504            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10505            state.version_markers.insert(change_id, (version, 0));
10506            return Ok(version);
10507        }
10508
10509        let version = max_supported;
10510        state.commands.push(json!({
10511            "type": "record_version_marker",
10512            "change_id": change_id,
10513            "version": version,
10514            "min_supported": min_supported,
10515            "max_supported": max_supported,
10516        }));
10517        // Sequence numbers are assigned by the server. Zero identifies a marker
10518        // selected in this uncommitted decision batch for duplicate-call checks.
10519        state.version_markers.insert(change_id, (version, 0));
10520        Ok(version)
10521    }
10522
10523    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10524    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10525        Ok(self.get_version(change_id, -1, 1)? == 1)
10526    }
10527
10528    /// Keep a patch marker in history after the legacy branch has been removed.
10529    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10530        self.get_version(change_id, -1, 1).map(|_| ())
10531    }
10532
10533    /// Merge non-indexed workflow memo metadata through durable history.
10534    ///
10535    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10536    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10537    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10538        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10539        let mut state = self
10540            .state
10541            .lock()
10542            .map_err(|_| Error::WorkflowStatePoisoned)?;
10543
10544        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10545            return match recorded {
10546                RecordedCommand::Memo {
10547                    sequence,
10548                    entries: recorded_entries,
10549                } => {
10550                    if recorded_entries != entries {
10551                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10552                            "memo_update_mismatch",
10553                            Some(sequence),
10554                            Some(format!("{recorded_entries:?}")),
10555                            Some(format!("{entries:?}")),
10556                            "recorded memo entries differ from the current workflow update",
10557                        )));
10558                    }
10559                    state.command_cursor += 1;
10560                    Ok(())
10561                }
10562                other => Err(command_mismatch(&other, "memo upsert")),
10563            };
10564        }
10565
10566        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10567        state.commands.push(json!({
10568            "type": "upsert_memo",
10569            "entries": entries_envelope,
10570        }));
10571        Ok(())
10572    }
10573
10574    /// Start a named durable child on an explicit queue and await its result.
10575    ///
10576    /// The command is recorded in the parent's sequence-ordered durable command
10577    /// stream. Replay keeps a scheduled child pending without emitting another
10578    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10579    /// values preserve the history payload codec and include both sides of the
10580    /// durable relationship; failures are returned as
10581    /// [`Error::ChildWorkflowFailed`].
10582    ///
10583    /// ```no_run
10584    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10585    /// # fn configure(client: Client) {
10586    /// let mut worker = Worker::new(client, "parent-workers");
10587    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10588    ///     let child = ctx
10589    ///         .start_child_workflow(
10590    ///             "fulfil-order",
10591    ///             ChildWorkflowOptions::new("fulfilment-workers")
10592    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10593    ///             json!([{"order_id": "order-42"}]),
10594    ///         )
10595    ///         .await?;
10596    ///     Ok(child.result)
10597    /// });
10598    /// # }
10599    /// ```
10600    pub fn start_child_workflow<T: Serialize>(
10601        &self,
10602        workflow_type: impl Into<String>,
10603        options: ChildWorkflowOptions,
10604        args: T,
10605    ) -> ChildWorkflowCall {
10606        ChildWorkflowCall {
10607            ctx: self.clone(),
10608            workflow_type: workflow_type.into(),
10609            options,
10610            args: Some(AvroValue::from_serialize(&args)),
10611            scheduled: false,
10612            matched_pending: false,
10613            parallel_group_path: Vec::new(),
10614        }
10615    }
10616
10617    pub async fn start_child_workflow_avro_value<T: Serialize>(
10618        &self,
10619        workflow_type: impl Into<String>,
10620        options: ChildWorkflowOptions,
10621        args: T,
10622    ) -> Result<ChildWorkflowAvroResult> {
10623        let mut call = self.start_child_workflow(workflow_type, options, args);
10624        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10625    }
10626
10627    fn take_commands(&self) -> Result<Vec<Value>> {
10628        let mut state = self
10629            .state
10630            .lock()
10631            .map_err(|_| Error::WorkflowStatePoisoned)?;
10632        Ok(std::mem::take(&mut state.commands))
10633    }
10634
10635    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10636        let mut state = self
10637            .state
10638            .lock()
10639            .map_err(|_| Error::WorkflowStatePoisoned)?;
10640
10641        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10642            return Err(command_mismatch(&recorded, "continue as new"));
10643        }
10644        if state.recorded_continue_as_new_sequence.is_some() {
10645            state.continue_as_new_consumed = true;
10646            return Ok(None);
10647        }
10648
10649        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10650        let mut command = serde_json::Map::from_iter([
10651            ("type".to_string(), json!("continue_as_new")),
10652            ("arguments".to_string(), arguments),
10653            ("queue".to_string(), json!(state.task_queue.clone())),
10654        ]);
10655        if let Some(workflow_type) = request.options.workflow_type {
10656            command.insert("workflow_type".to_string(), json!(workflow_type));
10657        }
10658        if let Some(task_queue) = request.options.task_queue {
10659            command.insert("queue".to_string(), json!(task_queue));
10660        }
10661        Ok(Some(Value::Object(command)))
10662    }
10663
10664    fn matched_recorded_pending(&self) -> Result<bool> {
10665        let state = self
10666            .state
10667            .lock()
10668            .map_err(|_| Error::WorkflowStatePoisoned)?;
10669        Ok(state.matched_recorded_pending)
10670    }
10671
10672    fn ensure_history_consumed(&self) -> Result<()> {
10673        let state = self
10674            .state
10675            .lock()
10676            .map_err(|_| Error::WorkflowStatePoisoned)?;
10677        if let Some(replay) = &state.scope_delivery {
10678            if let Some((&sequence, _)) = replay
10679                .canonical
10680                .deliveries
10681                .iter()
10682                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10683            {
10684                return Err(invalid_recorded_history(
10685                    "cancellation_scope_delivery_unconsumed",
10686                    sequence,
10687                    "original scoped delivery",
10688                    "workflow completion",
10689                    "workflow completed without consuming its committed scope delivery",
10690                ));
10691            }
10692        }
10693        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10694            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10695                "recorded_commands_unconsumed",
10696                Some(command.sequence()),
10697                Some(command.shape().to_string()),
10698                Some("workflow completion".to_string()),
10699                "workflow completed before consuming all recorded durable commands",
10700            )));
10701        }
10702        if let Some(delivery) = state
10703            .cancellation_history
10704            .delivery
10705            .as_ref()
10706            .filter(|_| !state.cancellation_consumed)
10707        {
10708            return Err(invalid_recorded_history(
10709                "cooperative_cancellation_unconsumed",
10710                delivery.sequence,
10711                "committed cancellation call",
10712                "workflow completion",
10713                "workflow completed without reaching its committed cancellation boundary",
10714            ));
10715        }
10716        if let Some(sequence) = state
10717            .recorded_continue_as_new_sequence
10718            .filter(|_| !state.continue_as_new_consumed)
10719        {
10720            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10721                "recorded_continue_as_new_unconsumed",
10722                Some(sequence),
10723                Some("continue as new".to_string()),
10724                Some("workflow completion".to_string()),
10725                "workflow completed without consuming its recorded continue-as-new transition",
10726            )));
10727        }
10728        Ok(())
10729    }
10730}
10731
10732fn contiguous_message_stream_count(
10733    pending: &[MessageStreamMessage],
10734    cursor: u64,
10735    max_items: usize,
10736) -> usize {
10737    pending
10738        .iter()
10739        .take(max_items)
10740        .enumerate()
10741        .take_while(|(offset, message)| {
10742            u64::try_from(*offset)
10743                .ok()
10744                .and_then(|offset| cursor.checked_add(offset + 1))
10745                == Some(message.position)
10746        })
10747        .count()
10748}
10749
10750fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10751    matches!(
10752        event.event_type.as_str(),
10753        "ActivityScheduled"
10754            | "TimerScheduled"
10755            | "ChildWorkflowScheduled"
10756            | "SignalWaitOpened"
10757            | "ConditionWaitOpened"
10758            | "SearchAttributesUpserted"
10759            | "SideEffectRecorded"
10760            | "VersionMarkerRecorded"
10761            | "MemoUpserted"
10762            | "WorkflowContinuedAsNew"
10763    )
10764}
10765
10766#[derive(Debug)]
10767struct WorkflowState {
10768    workflow_id: Option<String>,
10769    run_id: Option<String>,
10770    task_queue: String,
10771    payload_codec: String,
10772    history_events: Arc<Vec<HistoryEvent>>,
10773    history_budget: WorkflowHistoryBudget,
10774    cancel_requested: bool,
10775    cancellation_history: CancellationHistory,
10776    cancellation_consumed: bool,
10777    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10778    cancellation_shield_depth: u64,
10779    cancellation_delivery_enabled: bool,
10780    cancellation_delivery_intent: Option<CancellationDelivery>,
10781    cancellation_delivery_command_count: usize,
10782    allow_cancellation_scope_authoring: bool,
10783    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10784    cancellation_scope_memberships: BTreeMap<u64, String>,
10785    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10786    resume_signal: Option<ResumeSignal>,
10787    recorded_commands: Vec<RecordedCommand>,
10788    selection_markers: Vec<SelectionMarker>,
10789    selection_marker_cursor: usize,
10790    cancelled_selection_members: Vec<SelectionCancellation>,
10791    recorded_continue_as_new_sequence: Option<u64>,
10792    continue_as_new_consumed: bool,
10793    command_cursor: usize,
10794    condition_wait_occurrence_counter: u64,
10795    matched_recorded_pending: bool,
10796    version_markers: HashMap<String, (i32, u64)>,
10797    workflow_command_identity: String,
10798    workflow_stream_command_counter: u64,
10799    commands: Vec<Value>,
10800    local_activity_requests: Vec<local_activity::Request>,
10801    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10802    message_stream_cursors: HashMap<String, u64>,
10803    message_stream_waits: HashMap<String, u64>,
10804}
10805
10806impl WorkflowState {
10807    #[cfg(test)]
10808    fn new(
10809        history: Vec<HistoryEvent>,
10810        task_queue: String,
10811        payload_codec: String,
10812        resume_signal: Option<ResumeSignal>,
10813    ) -> Result<Self> {
10814        Self::new_with_identity(
10815            history,
10816            None,
10817            None,
10818            task_queue,
10819            payload_codec,
10820            resume_signal,
10821        )
10822    }
10823
10824    fn new_with_identity(
10825        history: Vec<HistoryEvent>,
10826        workflow_id: Option<String>,
10827        run_id: Option<String>,
10828        task_queue: String,
10829        payload_codec: String,
10830        resume_signal: Option<ResumeSignal>,
10831    ) -> Result<Self> {
10832        Self::new_with_identity_and_scopes(
10833            history,
10834            workflow_id,
10835            run_id,
10836            task_queue,
10837            payload_codec,
10838            resume_signal,
10839            false,
10840        )
10841    }
10842
10843    fn new_with_identity_and_scopes(
10844        history: Vec<HistoryEvent>,
10845        workflow_id: Option<String>,
10846        run_id: Option<String>,
10847        task_queue: String,
10848        payload_codec: String,
10849        resume_signal: Option<ResumeSignal>,
10850        allow_cancellation_scope_authoring: bool,
10851    ) -> Result<Self> {
10852        Self::new_with_identity_and_scope_delivery(
10853            history,
10854            workflow_id,
10855            run_id,
10856            task_queue,
10857            payload_codec,
10858            resume_signal,
10859            allow_cancellation_scope_authoring,
10860            false,
10861        )
10862    }
10863
10864    fn new_with_identity_and_scope_delivery(
10865        history: Vec<HistoryEvent>,
10866        workflow_id: Option<String>,
10867        run_id: Option<String>,
10868        task_queue: String,
10869        payload_codec: String,
10870        resume_signal: Option<ResumeSignal>,
10871        allow_cancellation_scope_authoring: bool,
10872        allow_cancellation_scope_delivery: bool,
10873    ) -> Result<Self> {
10874        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10875            &history,
10876            allow_cancellation_scope_authoring,
10877            allow_cancellation_scope_delivery,
10878        )?;
10879        let scopes = if allow_cancellation_scope_authoring {
10880            cancellation_scope::CancellationScopeHistory::read(
10881                &history,
10882                run_id.as_deref().unwrap_or_default(),
10883            )?
10884        } else {
10885            cancellation_scope::CancellationScopeHistory::default()
10886        };
10887        let cancellation_history = CancellationHistory::from_events(
10888            &history,
10889            run_id.as_deref().unwrap_or_default(),
10890            None,
10891        )?;
10892        if allow_cancellation_scope_authoring
10893            && cancellation_history.request.is_some()
10894            && !allow_cancellation_scope_delivery
10895        {
10896            return Err(Error::CancellationScopeExecutionUnavailable);
10897        }
10898        let scope_delivery = if allow_cancellation_scope_delivery {
10899            Some(cancellation_scope_replay::ScopeReplay::read(
10900                &history,
10901                &scopes,
10902                run_id.as_deref().unwrap_or_default(),
10903                workflow_id.as_deref().unwrap_or_default(),
10904            )?)
10905        } else {
10906            None
10907        };
10908        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10909            &history,
10910            &payload_codec,
10911            WorkflowIdentity {
10912                workflow_id: workflow_id.clone(),
10913                run_id: run_id.clone(),
10914            },
10915        )?)?;
10916        for (sequence, opening) in &scopes.openings {
10917            if recorded_commands
10918                .iter()
10919                .any(|command| command.sequence() == *sequence)
10920            {
10921                return Err(invalid_recorded_history(
10922                    "invalid_cancellation_scope_history",
10923                    *sequence,
10924                    "distinct authored scope opening",
10925                    "operation collision",
10926                    "scope opening collides with a command",
10927                ));
10928            }
10929            recorded_commands.push(RecordedCommand::CancellationScope {
10930                sequence: *sequence,
10931                scope_id: opening.scope_id.clone(),
10932                parent_scope_id: opening.parent_scope_id.clone(),
10933                shield_parent: opening.shield_parent,
10934            });
10935        }
10936        recorded_commands.sort_by_key(RecordedCommand::sequence);
10937        if let Some(replay) = &scope_delivery {
10938            replay.bind_commands(&mut recorded_commands)?;
10939        }
10940        let selection_markers = recorded_selection_markers(&history)?;
10941        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10942        let recorded_continue_as_new = history
10943            .iter()
10944            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10945            .collect::<Vec<_>>();
10946        if recorded_continue_as_new.len() > 1 {
10947            return Err(invalid_recorded_history(
10948                "duplicate_continue_as_new_transition",
10949                recorded_continue_as_new
10950                    .last()
10951                    .and_then(|event| durable_event_sequence(event))
10952                    .unwrap_or(0),
10953                "one WorkflowContinuedAsNew event",
10954                &format!(
10955                    "{} WorkflowContinuedAsNew events",
10956                    recorded_continue_as_new.len()
10957                ),
10958                "workflow history records one continue-as-new transition more than once",
10959            ));
10960        }
10961        let recorded_continue_as_new_sequence = recorded_continue_as_new
10962            .first()
10963            .map(|event| {
10964                durable_event_sequence(event).ok_or_else(|| {
10965                    Error::NonDeterministicReplay(ReplayFailure::new(
10966                        "continue_as_new_sequence_missing",
10967                        None,
10968                        Some("recorded transition sequence".to_string()),
10969                        Some("missing sequence".to_string()),
10970                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10971                    ))
10972                })
10973            })
10974            .transpose()?;
10975        let mut message_stream_cursors = HashMap::new();
10976        for event in &history {
10977            if !matches!(
10978                event.event_type.as_str(),
10979                "SignalReceived" | "SignalApplied"
10980            ) || event.payload.get("signal_name").and_then(Value::as_str)
10981                != Some(MESSAGE_STREAM_SIGNAL)
10982            {
10983                continue;
10984            }
10985            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10986            if arguments.len() != 1 {
10987                continue;
10988            }
10989            let envelope = arguments[0].clone().into_json()?;
10990            let Some(envelope) = envelope.as_object() else {
10991                continue;
10992            };
10993            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10994            {
10995                continue;
10996            }
10997            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10998                continue;
10999            };
11000            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11001            else {
11002                continue;
11003            };
11004            let cursor = message_stream_cursors
11005                .entry(stream_name.to_string())
11006                .or_insert(0);
11007            *cursor = (*cursor).max(through_position);
11008        }
11009        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11010        let cancel_requested = history.iter().any(|event| {
11011            matches!(
11012                event.event_type.as_str(),
11013                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11014            )
11015        });
11016        let cancellation_clock = cancellation_history
11017            .request
11018            .as_ref()
11019            .and_then(|request| request.context.as_ref())
11020            .map(|_| {
11021                cancellation_replay_clock::ReplayClock::new(
11022                    &history,
11023                    &recorded_commands,
11024                    cancellation_history.delivery_index,
11025                )
11026            })
11027            .or_else(|| {
11028                scope_delivery.as_ref().map(|_| {
11029                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11030                })
11031            });
11032        Ok(Self {
11033            workflow_command_identity: String::new(),
11034            workflow_stream_command_counter: 0,
11035            workflow_id,
11036            run_id,
11037            task_queue,
11038            payload_codec,
11039            history_events: Arc::new(history),
11040            history_budget: WorkflowHistoryBudget {
11041                event_count,
11042                ..WorkflowHistoryBudget::default()
11043            },
11044            cancel_requested,
11045            cancellation_history,
11046            cancellation_consumed: false,
11047            cancellation_clock,
11048            cancellation_shield_depth: 0,
11049            cancellation_delivery_enabled: false,
11050            cancellation_delivery_intent: None,
11051            cancellation_delivery_command_count: 0,
11052            allow_cancellation_scope_authoring,
11053            cancellation_scope_opening: None,
11054            cancellation_scope_memberships: scopes.memberships,
11055            scope_delivery,
11056            resume_signal,
11057            recorded_commands,
11058            selection_markers,
11059            selection_marker_cursor: 0,
11060            cancelled_selection_members,
11061            recorded_continue_as_new_sequence,
11062            continue_as_new_consumed: false,
11063            command_cursor: 0,
11064            condition_wait_occurrence_counter: 0,
11065            matched_recorded_pending: false,
11066            version_markers: HashMap::new(),
11067            commands: Vec::new(),
11068            local_activity_requests: Vec::new(),
11069            message_stream_messages: HashMap::new(),
11070            message_stream_cursors,
11071            message_stream_waits: HashMap::new(),
11072        })
11073    }
11074}
11075
11076enum MessageStreamDelivery {
11077    Message(MessageStreamMessage),
11078    Cursor {
11079        stream_name: String,
11080        through_position: u64,
11081    },
11082}
11083
11084fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11085    if arguments.len() != 1 {
11086        return Ok(None);
11087    }
11088    let envelope = arguments
11089        .into_iter()
11090        .next()
11091        .expect("one argument was checked");
11092    let Some(envelope) = envelope.as_object() else {
11093        return Ok(None);
11094    };
11095    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11096        return Ok(None);
11097    };
11098    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11099        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11100        else {
11101            return Ok(None);
11102        };
11103        return Ok(Some(MessageStreamDelivery::Cursor {
11104            stream_name: stream_name.to_string(),
11105            through_position,
11106        }));
11107    }
11108    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11109        return Ok(None);
11110    }
11111    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11112        return Ok(None);
11113    };
11114    let Some(position) = envelope
11115        .get("position")
11116        .and_then(Value::as_u64)
11117        .filter(|value| *value > 0)
11118    else {
11119        return Ok(None);
11120    };
11121    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11122        return Ok(None);
11123    };
11124    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11125    else {
11126        return Ok(None);
11127    };
11128    let decoded = decode_avro_value(&payload_envelope)?;
11129    let AvroValue::Array(values) = decoded else {
11130        return Ok(None);
11131    };
11132    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11133        stream_name: stream_name.to_string(),
11134        message_id: message_id.to_string(),
11135        position,
11136        arguments: values,
11137    })))
11138}
11139
11140#[derive(Clone, Debug)]
11141enum RecordedCommand {
11142    CancellationScope {
11143        sequence: u64,
11144        scope_id: String,
11145        parent_scope_id: String,
11146        shield_parent: bool,
11147    },
11148    CancellationGroup {
11149        sequence: u64,
11150        span: u64,
11151        original: Vec<RecordedCommand>,
11152    },
11153    CancellationBoundary {
11154        sequence: u64,
11155        call_kind: CancellationCallKind,
11156        original: Option<Box<RecordedCommand>>,
11157    },
11158    Activity {
11159        sequence: u64,
11160        activity_type: Option<String>,
11161        cancellation_policy: String,
11162        options: Option<RecordedActivityOptions>,
11163        outcome: Option<ActivityOutcome>,
11164        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11165    },
11166    Timer {
11167        sequence: u64,
11168        delay_seconds: u64,
11169        fired: bool,
11170        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11171    },
11172    ChildWorkflow {
11173        sequence: u64,
11174        workflow_type: Option<String>,
11175        policies: RecordedChildPolicies,
11176        outcome: Option<ChildWorkflowOutcome>,
11177        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11178    },
11179    SignalWait {
11180        sequence: u64,
11181        signal_name: String,
11182        value: Option<Vec<AvroValue>>,
11183        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11184    },
11185    ConditionWait {
11186        sequence: u64,
11187        occurrence_id: String,
11188        condition_key: Option<String>,
11189        predicate_identity: String,
11190        timeout_seconds: Option<u64>,
11191        result: Option<ConditionWaitResult>,
11192        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11193    },
11194    SearchAttributes {
11195        sequence: u64,
11196        attributes: Value,
11197        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11198    },
11199    SideEffect {
11200        sequence: u64,
11201        value: AvroValue,
11202    },
11203    VersionMarker {
11204        sequence: u64,
11205        change_id: String,
11206        version: i32,
11207    },
11208    Memo {
11209        sequence: u64,
11210        entries: AvroValue,
11211    },
11212}
11213
11214#[derive(Clone, Debug, PartialEq, Eq)]
11215struct SelectionMarker {
11216    selection_group_id: String,
11217    selection_group_base_sequence: u64,
11218    selection_group_size: usize,
11219    member_key: SelectionKey,
11220    member_index: usize,
11221    member_base_sequence: u64,
11222    member_size: usize,
11223    operation_kind: String,
11224    operation_identity: String,
11225    outcome: String,
11226    resolution_event_id: String,
11227    resolution_event_type: String,
11228}
11229
11230#[derive(Clone, Debug, PartialEq, Eq)]
11231struct SelectionCancellation {
11232    selection_group_id: String,
11233    member_key: SelectionKey,
11234    member_index: usize,
11235    member_base_sequence: u64,
11236    member_size: usize,
11237    operation_kind: String,
11238    operation_identity: String,
11239}
11240
11241fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11242    let mut markers: Vec<SelectionMarker> = Vec::new();
11243    for event in events
11244        .iter()
11245        .filter(|event| event.event_type == "SelectionResolved")
11246    {
11247        let payload = &event.payload;
11248        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11249        let group_size = required_selection_usize(payload, "selection_group_size")?;
11250        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11251        let member_size = required_selection_usize(payload, "member_size")?;
11252        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11253        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11254            invalid_recorded_history(
11255                "selection_marker_invalid",
11256                base_sequence,
11257                "non-empty selection_group_id",
11258                &payload.to_string(),
11259                "selection winner history is missing its durable group identity",
11260            )
11261        })?;
11262        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11263        if group_id != expected_group_id {
11264            return Err(invalid_recorded_history(
11265                "selection_marker_invalid",
11266                base_sequence,
11267                &expected_group_id,
11268                &group_id,
11269                "selection winner history contains an incompatible group identity",
11270            ));
11271        }
11272        let group_end = base_sequence
11273            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11274            .unwrap_or(u64::MAX);
11275        let member_end = member_base_sequence
11276            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11277            .unwrap_or(u64::MAX);
11278        if member_index >= group_size
11279            || member_base_sequence < base_sequence
11280            || member_end > group_end
11281        {
11282            return Err(invalid_recorded_history(
11283                "selection_marker_invalid",
11284                base_sequence,
11285                "winner member within selection group bounds",
11286                &payload.to_string(),
11287                "selection winner history contains an invalid member range",
11288            ));
11289        }
11290        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11291            invalid_recorded_history(
11292                "selection_marker_invalid",
11293                base_sequence,
11294                "selection operation kind",
11295                &payload.to_string(),
11296                "selection winner history is missing its operation kind",
11297            )
11298        })?;
11299        if !matches!(
11300            operation_kind.as_str(),
11301            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11302        ) {
11303            return Err(invalid_recorded_history(
11304                "selection_marker_invalid",
11305                base_sequence,
11306                "activity, child, timer, signal, condition, or group",
11307                &operation_kind,
11308                "selection winner history contains an unsupported operation kind",
11309            ));
11310        }
11311        let operation_identity =
11312            payload_string(payload, "operation_identity").ok_or_else(|| {
11313                invalid_recorded_history(
11314                    "selection_marker_invalid",
11315                    base_sequence,
11316                    "non-empty operation identity",
11317                    &payload.to_string(),
11318                    "selection winner history is missing its durable operation identity",
11319                )
11320            })?;
11321        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11322            invalid_recorded_history(
11323                "selection_marker_invalid",
11324                base_sequence,
11325                "completed or failed selection outcome",
11326                &payload.to_string(),
11327                "selection winner history is missing its outcome",
11328            )
11329        })?;
11330        if !matches!(outcome.as_str(), "completed" | "failed") {
11331            return Err(invalid_recorded_history(
11332                "selection_marker_invalid",
11333                base_sequence,
11334                "completed or failed selection outcome",
11335                &outcome,
11336                "selection winner history contains an unsupported outcome",
11337            ));
11338        }
11339        let marker = SelectionMarker {
11340            selection_group_id: group_id,
11341            selection_group_base_sequence: base_sequence,
11342            selection_group_size: group_size,
11343            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11344            member_index,
11345            member_base_sequence,
11346            member_size,
11347            operation_kind,
11348            operation_identity,
11349            outcome,
11350            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11351                || {
11352                    invalid_recorded_history(
11353                        "selection_marker_invalid",
11354                        base_sequence,
11355                        "durable resolution_event_id",
11356                        &payload.to_string(),
11357                        "selection winner history is missing its terminal event identity",
11358                    )
11359                },
11360            )?,
11361            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11362                || {
11363                    invalid_recorded_history(
11364                        "selection_marker_invalid",
11365                        base_sequence,
11366                        "durable resolution_event_type",
11367                        &payload.to_string(),
11368                        "selection winner history is missing its terminal event type",
11369                    )
11370                },
11371            )?,
11372        };
11373        if let Some(existing) = markers
11374            .iter()
11375            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11376        {
11377            if existing != &marker {
11378                return Err(invalid_recorded_history(
11379                    "selection_marker_conflict",
11380                    base_sequence,
11381                    &format!("one winner for {}", marker.selection_group_id),
11382                    &payload.to_string(),
11383                    "selection history records conflicting winners for one durable group",
11384                ));
11385            }
11386            continue;
11387        }
11388        markers.push(marker);
11389    }
11390    Ok(markers)
11391}
11392
11393fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11394    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11395    for event in events
11396        .iter()
11397        .filter(|event| event.event_type == "SelectionOperationCancelled")
11398    {
11399        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11400            invalid_recorded_history(
11401                "selection_cancellation_invalid",
11402                0,
11403                "non-empty selection_group_id",
11404                &event.payload.to_string(),
11405                "selection cancellation history is missing its group identity",
11406            )
11407        })?;
11408        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11409        let marker = SelectionCancellation {
11410            selection_group_id: group_id,
11411            member_key: selection_key_from_value(
11412                event.payload.get("member_key"),
11413                member_base_sequence,
11414            )?,
11415            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11416            member_base_sequence,
11417            member_size: required_selection_usize(&event.payload, "member_size")?,
11418            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11419                invalid_recorded_history(
11420                    "selection_cancellation_invalid",
11421                    member_base_sequence,
11422                    "selection operation kind",
11423                    &event.payload.to_string(),
11424                    "selection cancellation is missing its operation kind",
11425                )
11426            })?,
11427            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11428                || {
11429                    invalid_recorded_history(
11430                        "selection_cancellation_invalid",
11431                        member_base_sequence,
11432                        "selection operation identity",
11433                        &event.payload.to_string(),
11434                        "selection cancellation is missing its operation identity",
11435                    )
11436                },
11437            )?,
11438        };
11439        if let Some(existing) = cancelled.iter().find(|recorded| {
11440            recorded.selection_group_id == marker.selection_group_id
11441                && recorded.member_base_sequence == marker.member_base_sequence
11442        }) {
11443            if existing != &marker {
11444                return Err(invalid_recorded_history(
11445                    "selection_cancellation_conflict",
11446                    member_base_sequence,
11447                    "one stable SelectionOperationCancelled marker",
11448                    &event.payload.to_string(),
11449                    "selection cancellation history contains conflicting member metadata",
11450                ));
11451            }
11452        } else {
11453            cancelled.push(marker);
11454        }
11455    }
11456    Ok(cancelled)
11457}
11458
11459fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11460    payload
11461        .get(field)
11462        .and_then(value_as_u64)
11463        .filter(|value| *value > 0)
11464        .ok_or_else(|| {
11465            invalid_recorded_history(
11466                "selection_marker_invalid",
11467                0,
11468                &format!("positive integer {field}"),
11469                &payload.to_string(),
11470                "selection history contains invalid durable identity metadata",
11471            )
11472        })
11473}
11474
11475fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11476    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11477        if value > 0 {
11478            Ok(value)
11479        } else {
11480            Err(invalid_recorded_history(
11481                "selection_marker_invalid",
11482                0,
11483                &format!("positive integer {field}"),
11484                &payload.to_string(),
11485                "selection history contains invalid durable identity metadata",
11486            ))
11487        }
11488    })
11489}
11490
11491fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11492    payload
11493        .get(field)
11494        .and_then(value_as_u64)
11495        .and_then(|value| usize::try_from(value).ok())
11496        .ok_or_else(|| {
11497            invalid_recorded_history(
11498                "selection_marker_invalid",
11499                0,
11500                &format!("non-negative integer {field}"),
11501                &payload.to_string(),
11502                "selection history contains invalid durable identity metadata",
11503            )
11504        })
11505}
11506
11507#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11508struct RecordedActivityOptions {
11509    task_queue: RecordedSnapshotValue<Option<String>>,
11510    execution_mode: RecordedSnapshotValue<Option<String>>,
11511    retry_policy: ActivityRetrySnapshot,
11512    worker_session: Option<Value>,
11513}
11514
11515#[derive(Clone, Debug)]
11516struct RecordedChildPolicies {
11517    parent_close_policy: String,
11518    cancellation_policy: String,
11519}
11520
11521fn recorded_activity_cancellation_policy(
11522    events: &[&HistoryEvent],
11523    sequence: u64,
11524) -> Result<String> {
11525    let mut policy: Option<String> = None;
11526    for event in events.iter().filter(|event| {
11527        matches!(
11528            event.event_type.as_str(),
11529            "ActivityScheduled"
11530                | "ActivityStarted"
11531                | "ActivityCompleted"
11532                | "ActivityFailed"
11533                | "ActivityTimedOut"
11534                | "ActivityCancelled"
11535        )
11536    }) {
11537        for source in [Some(&event.payload), event.payload.get("activity")]
11538            .into_iter()
11539            .flatten()
11540        {
11541            let Some(value) = source.get("cancellation_policy") else {
11542                continue;
11543            };
11544            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11545                value.as_str()
11546            else {
11547                return Err(invalid_recorded_history(
11548                    "invalid_activity_cancellation_policy_history",
11549                    sequence,
11550                    "supported Activity cancellation policy",
11551                    &value.to_string(),
11552                    "Activity history contains an invalid cancellation policy",
11553                ));
11554            };
11555            if let Some(previous) = policy.as_deref() {
11556                if previous != incoming {
11557                    return Err(invalid_recorded_history(
11558                        "activity_cancellation_policy_history_conflict",
11559                        sequence,
11560                        previous,
11561                        incoming,
11562                        "Activity cancellation policy changed between history events",
11563                    ));
11564                }
11565            }
11566            policy = Some(incoming.to_string());
11567        }
11568        policy.get_or_insert_with(|| "try_cancel".to_string());
11569    }
11570    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11571}
11572
11573fn recorded_child_policy_value<'a>(
11574    payload: &'a Value,
11575    field: &str,
11576    sequence: u64,
11577) -> Result<Option<&'a str>> {
11578    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11579        return Ok(None);
11580    };
11581    let valid = match (field, value.as_str()) {
11582        (
11583            "parent_close_policy",
11584            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11585        ) => true,
11586        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11587            true
11588        }
11589        _ => false,
11590    };
11591    if !valid {
11592        return Err(invalid_recorded_history(
11593            "invalid_child_workflow_policy_history",
11594            sequence,
11595            "supported child workflow policy",
11596            &value.to_string(),
11597            "child workflow history contains an invalid policy",
11598        ));
11599    }
11600    Ok(value.as_str())
11601}
11602
11603fn recorded_child_policies(
11604    events: &[&HistoryEvent],
11605    scheduled: &HistoryEvent,
11606    sequence: u64,
11607) -> Result<RecordedChildPolicies> {
11608    let parent_close_policy =
11609        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11610            .unwrap_or("abandon")
11611            .to_string();
11612    let cancellation_policy =
11613        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11614            .unwrap_or("abandon")
11615            .to_string();
11616    for event in events {
11617        for (field, expected) in [
11618            ("parent_close_policy", parent_close_policy.as_str()),
11619            ("cancellation_policy", cancellation_policy.as_str()),
11620        ] {
11621            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11622                if actual != expected {
11623                    return Err(invalid_recorded_history(
11624                        "child_workflow_policy_history_conflict",
11625                        sequence,
11626                        expected,
11627                        actual,
11628                        "child workflow policy changed between history events",
11629                    ));
11630                }
11631            }
11632        }
11633    }
11634    Ok(RecordedChildPolicies {
11635        parent_close_policy,
11636        cancellation_policy,
11637    })
11638}
11639
11640fn ensure_child_policies_match(
11641    sequence: u64,
11642    recorded: &RecordedChildPolicies,
11643    current: &ChildWorkflowOptions,
11644) -> Result<()> {
11645    for (field, expected, actual) in [
11646        (
11647            "parent_close_policy",
11648            recorded.parent_close_policy.as_str(),
11649            current.parent_close_policy.as_str(),
11650        ),
11651        (
11652            "cancellation_policy",
11653            recorded.cancellation_policy.as_str(),
11654            current.cancellation_policy.as_str(),
11655        ),
11656    ] {
11657        if expected != actual {
11658            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11659                "child_workflow_policy_changed",
11660                Some(sequence),
11661                Some(expected.to_string()),
11662                Some(actual.to_string()),
11663                format!("child workflow {field} changed during replay"),
11664            )));
11665        }
11666    }
11667    Ok(())
11668}
11669
11670#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11671enum RecordedSnapshotValue<T> {
11672    /// Older history did not persist this field, so it cannot constrain replay.
11673    Unknown,
11674    Known(T),
11675}
11676
11677impl<T: PartialEq> RecordedSnapshotValue<T> {
11678    fn matches_current(&self, current: &Self) -> bool {
11679        match self {
11680            Self::Unknown => true,
11681            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11682        }
11683    }
11684}
11685
11686#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11687struct ActivityRetrySnapshot {
11688    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11689    max_attempts: RecordedSnapshotValue<Option<u64>>,
11690    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11691    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11692    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11693    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11694    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11695    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11696}
11697
11698impl ActivityRetrySnapshot {
11699    fn matches_current(&self, current: &Self) -> bool {
11700        self.snapshot_version
11701            .matches_current(&current.snapshot_version)
11702            && self.max_attempts.matches_current(&current.max_attempts)
11703            && self
11704                .backoff_seconds
11705                .matches_current(&current.backoff_seconds)
11706            && self
11707                .start_to_close_timeout
11708                .matches_current(&current.start_to_close_timeout)
11709            && self
11710                .schedule_to_start_timeout
11711                .matches_current(&current.schedule_to_start_timeout)
11712            && self
11713                .schedule_to_close_timeout
11714                .matches_current(&current.schedule_to_close_timeout)
11715            && self
11716                .heartbeat_timeout
11717                .matches_current(&current.heartbeat_timeout)
11718            && self
11719                .non_retryable_error_types
11720                .matches_current(&current.non_retryable_error_types)
11721    }
11722}
11723
11724fn recorded_optional_u64(
11725    object: Option<&serde_json::Map<String, Value>>,
11726    field: &str,
11727) -> RecordedSnapshotValue<Option<u64>> {
11728    match object.and_then(|object| object.get(field)) {
11729        None => RecordedSnapshotValue::Unknown,
11730        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11731        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11732    }
11733}
11734
11735fn recorded_optional_string(
11736    object: &serde_json::Map<String, Value>,
11737    field: &str,
11738) -> RecordedSnapshotValue<Option<String>> {
11739    match object.get(field) {
11740        None => RecordedSnapshotValue::Unknown,
11741        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11742        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11743    }
11744}
11745
11746fn recorded_activity_execution_mode(
11747    events: &[&HistoryEvent],
11748    sequence: u64,
11749) -> Result<RecordedSnapshotValue<Option<String>>> {
11750    let mut recorded = RecordedSnapshotValue::Unknown;
11751    for event in events {
11752        for object in [
11753            event.payload.as_object(),
11754            event.payload.get("activity").and_then(Value::as_object),
11755        ]
11756        .into_iter()
11757        .flatten()
11758        {
11759            let mode = match object.get("execution_mode") {
11760                None => None,
11761                Some(Value::Null) => Some(None),
11762                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11763                Some(_) => {
11764                    return Err(invalid_recorded_history(
11765                        "activity_execution_mode_invalid",
11766                        sequence,
11767                        "null or a non-empty execution mode",
11768                        "invalid execution_mode",
11769                        "activity history contains an invalid execution mode",
11770                    ))
11771                }
11772            };
11773            let legacy_mode = match object.get("local_activity") {
11774                None => None,
11775                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11776                Some(_) => {
11777                    return Err(invalid_recorded_history(
11778                        "activity_execution_mode_invalid",
11779                        sequence,
11780                        "boolean local_activity",
11781                        "invalid local_activity",
11782                        "activity history contains an invalid local-activity marker",
11783                    ))
11784                }
11785            };
11786            for mode in [mode, legacy_mode].into_iter().flatten() {
11787                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11788                {
11789                    return Err(invalid_recorded_history(
11790                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11791                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11792                    ));
11793                }
11794                recorded = RecordedSnapshotValue::Known(mode);
11795            }
11796        }
11797    }
11798    Ok(recorded)
11799}
11800
11801fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11802    let policy = policy.and_then(Value::as_object);
11803    let backoff_seconds = policy
11804        .and_then(|policy| policy.get("backoff_seconds"))
11805        .and_then(Value::as_array)
11806        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11807        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11808    let mut non_retryable_error_types = Vec::new();
11809    for error_type in policy
11810        .and_then(|policy| policy.get("non_retryable_error_types"))
11811        .and_then(Value::as_array)
11812        .into_iter()
11813        .flatten()
11814        .filter_map(Value::as_str)
11815        .map(str::trim)
11816        .filter(|error_type| !error_type.is_empty())
11817    {
11818        if !non_retryable_error_types
11819            .iter()
11820            .any(|recorded| recorded == error_type)
11821        {
11822            non_retryable_error_types.push(error_type.to_string());
11823        }
11824    }
11825
11826    ActivityRetrySnapshot {
11827        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11828        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11829        backoff_seconds,
11830        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11831        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11832        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11833        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11834        non_retryable_error_types: if policy
11835            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11836        {
11837            RecordedSnapshotValue::Known(non_retryable_error_types)
11838        } else {
11839            RecordedSnapshotValue::Unknown
11840        },
11841    }
11842}
11843
11844fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11845    let policy = options.retry_policy.as_ref();
11846    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11847        Some(Value::Null) => None,
11848        Some(value) => value_as_u64(value),
11849        None => Some(1),
11850    };
11851    let backoff_seconds = policy
11852        .and_then(|policy| policy.get("backoff_seconds"))
11853        .and_then(Value::as_array)
11854        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11855        .unwrap_or_default();
11856    let non_retryable_error_types = policy
11857        .and_then(|policy| policy.get("non_retryable_error_types"))
11858        .and_then(Value::as_array)
11859        .into_iter()
11860        .flatten()
11861        .filter_map(Value::as_str)
11862        .map(str::to_string)
11863        .collect();
11864
11865    ActivityRetrySnapshot {
11866        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11867        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11868        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11869        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11870        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11871        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11872        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11873        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11874    }
11875}
11876
11877fn activity_options_description(options: &RecordedActivityOptions) -> String {
11878    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11879}
11880
11881impl RecordedCommand {
11882    fn sequence(&self) -> u64 {
11883        match self {
11884            Self::CancellationGroup { sequence, .. }
11885            | Self::CancellationScope { sequence, .. }
11886            | Self::CancellationBoundary { sequence, .. }
11887            | Self::Activity { sequence, .. }
11888            | Self::Timer { sequence, .. }
11889            | Self::ChildWorkflow { sequence, .. }
11890            | Self::SignalWait { sequence, .. }
11891            | Self::ConditionWait { sequence, .. }
11892            | Self::SearchAttributes { sequence, .. }
11893            | Self::SideEffect { sequence, .. }
11894            | Self::VersionMarker { sequence, .. }
11895            | Self::Memo { sequence, .. } => *sequence,
11896        }
11897    }
11898
11899    fn shape(&self) -> &'static str {
11900        match self {
11901            Self::CancellationScope { .. } => "cancellation scope",
11902            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11903                "cooperative cancellation"
11904            }
11905            Self::Activity { .. } => "activity",
11906            Self::Timer { .. } => "timer",
11907            Self::ChildWorkflow { .. } => "child workflow",
11908            Self::SignalWait { .. } => "signal wait",
11909            Self::ConditionWait { .. } => "condition wait",
11910            Self::SearchAttributes { .. } => "search-attribute update",
11911            Self::SideEffect { .. } => "side effect",
11912            Self::VersionMarker { .. } => "version marker",
11913            Self::Memo { .. } => "memo upsert",
11914        }
11915    }
11916}
11917
11918fn ensure_version_supported(
11919    change_id: &str,
11920    version: i32,
11921    min_supported: i32,
11922    max_supported: i32,
11923    sequence: u64,
11924) -> Result<()> {
11925    if (min_supported..=max_supported).contains(&version) {
11926        return Ok(());
11927    }
11928    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11929        "version_marker_incompatible_range",
11930        (sequence != 0).then_some(sequence),
11931        Some(format!("{min_supported}..={max_supported}")),
11932        Some(format!("{change_id}:{version}")),
11933        "recorded workflow version is outside the range supported by current code",
11934    )))
11935}
11936
11937#[derive(Clone, Debug)]
11938struct ResumeSignal {
11939    signal_name: String,
11940    arguments: Vec<AvroValue>,
11941}
11942
11943const MAX_PARALLEL_OPERATIONS: usize = 1000;
11944
11945fn parallel_group_prefix(kind: &str) -> &'static str {
11946    match kind {
11947        "activity" => "parallel-activities",
11948        "child" => "parallel-children",
11949        "timer" => "parallel-timers",
11950        _ => "parallel-calls",
11951    }
11952}
11953
11954fn parallel_group_entry(
11955    base_sequence: u64,
11956    size: usize,
11957    index: usize,
11958    kind: &str,
11959) -> ParallelGroupMetadata {
11960    ParallelGroupMetadata {
11961        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
11962        parallel_group_kind: kind.to_string(),
11963        parallel_group_base_sequence: base_sequence,
11964        parallel_group_size: size,
11965        parallel_group_index: index,
11966        parallel_group_mode: None,
11967        selection_member_key: None,
11968        selection_member_index: None,
11969        selection_member_base_sequence: None,
11970        selection_member_size: None,
11971        selection_member_kind: None,
11972    }
11973}
11974
11975struct SelectionMemberMetadata {
11976    key: SelectionKey,
11977    index: usize,
11978    base_sequence: u64,
11979    size: usize,
11980    kind: String,
11981}
11982
11983fn selection_group_entry(
11984    base_sequence: u64,
11985    size: usize,
11986    index: usize,
11987    kind: &str,
11988    member: &SelectionMemberMetadata,
11989) -> ParallelGroupMetadata {
11990    ParallelGroupMetadata {
11991        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11992        parallel_group_kind: kind.to_string(),
11993        parallel_group_base_sequence: base_sequence,
11994        parallel_group_size: size,
11995        parallel_group_index: index,
11996        parallel_group_mode: Some("select".to_string()),
11997        selection_member_key: Some(member.key.clone()),
11998        selection_member_index: Some(member.index),
11999        selection_member_base_sequence: Some(member.base_sequence),
12000        selection_member_size: Some(member.size),
12001        selection_member_kind: Some(member.kind.clone()),
12002    }
12003}
12004
12005fn apply_parallel_group_path(
12006    command: &mut serde_json::Map<String, Value>,
12007    path: &[ParallelGroupMetadata],
12008) {
12009    let Some(inner) = path.last() else {
12010        return;
12011    };
12012    command.insert(
12013        "parallel_group_id".to_string(),
12014        json!(inner.parallel_group_id),
12015    );
12016    command.insert(
12017        "parallel_group_kind".to_string(),
12018        json!(inner.parallel_group_kind),
12019    );
12020    command.insert(
12021        "parallel_group_base_sequence".to_string(),
12022        json!(inner.parallel_group_base_sequence),
12023    );
12024    command.insert(
12025        "parallel_group_size".to_string(),
12026        json!(inner.parallel_group_size),
12027    );
12028    command.insert(
12029        "parallel_group_index".to_string(),
12030        json!(inner.parallel_group_index),
12031    );
12032    if let Some(mode) = &inner.parallel_group_mode {
12033        command.insert("parallel_group_mode".to_string(), json!(mode));
12034    }
12035    if let Some(key) = &inner.selection_member_key {
12036        command.insert("selection_member_key".to_string(), json!(key));
12037    }
12038    if let Some(index) = inner.selection_member_index {
12039        command.insert("selection_member_index".to_string(), json!(index));
12040    }
12041    if let Some(base_sequence) = inner.selection_member_base_sequence {
12042        command.insert(
12043            "selection_member_base_sequence".to_string(),
12044            json!(base_sequence),
12045        );
12046    }
12047    if let Some(size) = inner.selection_member_size {
12048        command.insert("selection_member_size".to_string(), json!(size));
12049    }
12050    if let Some(kind) = &inner.selection_member_kind {
12051        command.insert("selection_member_kind".to_string(), json!(kind));
12052    }
12053    command.insert("parallel_group_path".to_string(), json!(path));
12054}
12055
12056fn ensure_parallel_path_matches(
12057    sequence: u64,
12058    recorded: Option<&[ParallelGroupMetadata]>,
12059    expected: &[ParallelGroupMetadata],
12060) -> Result<()> {
12061    match (recorded, expected.is_empty()) {
12062        (None, true) => Ok(()),
12063        (Some(recorded), false) if recorded == expected => Ok(()),
12064        (None, false) => Err(invalid_recorded_history(
12065            "parallel_group_metadata_missing",
12066            sequence,
12067            &serde_json::to_string(expected).unwrap_or_default(),
12068            "<missing>",
12069            "recorded parallel member is missing its durable group path",
12070        )),
12071        (Some(recorded), true) => Err(invalid_recorded_history(
12072            "parallel_group_shape_mismatch",
12073            sequence,
12074            "sequential command",
12075            &serde_json::to_string(recorded).unwrap_or_default(),
12076            "recorded command belonged to a parallel group but current code schedules it sequentially",
12077        )),
12078        (Some(recorded), false) => Err(invalid_recorded_history(
12079            "parallel_group_shape_mismatch",
12080            sequence,
12081            &serde_json::to_string(recorded).unwrap_or_default(),
12082            &serde_json::to_string(expected).unwrap_or_default(),
12083            "recorded parallel-group identity or path changed during replay",
12084        )),
12085    }
12086}
12087
12088#[derive(Clone, Debug)]
12089enum ParallelShape {
12090    Leaf,
12091    Group(Vec<ParallelShape>),
12092}
12093
12094struct ParallelDescriptor {
12095    operation: ParallelOperation,
12096    offset: usize,
12097    member_path: Vec<usize>,
12098    group_path: Vec<ParallelGroupMetadata>,
12099}
12100
12101fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12102    operations
12103        .iter()
12104        .map(|operation| match operation {
12105            ParallelOperation::Group(children) => parallel_leaf_count(children),
12106            _ => 1,
12107        })
12108        .sum()
12109}
12110
12111fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12112    match operation {
12113        ParallelOperation::Activity { .. } => Some("activity"),
12114        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12115        ParallelOperation::Timer(_) => Some("timer"),
12116        ParallelOperation::Signal(_) => Some("signal"),
12117        ParallelOperation::Condition { .. } => Some("condition"),
12118        ParallelOperation::Group(children) => parallel_group_kind(children),
12119    }
12120}
12121
12122fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12123    let mut kind = None;
12124    for operation in operations {
12125        let Some(operation_kind) = parallel_operation_kind(operation) else {
12126            continue;
12127        };
12128        match kind {
12129            None => kind = Some(operation_kind),
12130            Some(current) if current == operation_kind => {}
12131            Some(_) => return Some("mixed"),
12132        }
12133    }
12134    kind
12135}
12136
12137fn validate_parallel_operations(
12138    operations: &[ParallelOperation],
12139    member_path: &mut Vec<usize>,
12140    root: bool,
12141) -> Result<()> {
12142    let leaves = parallel_leaf_count(operations);
12143    if leaves > MAX_PARALLEL_OPERATIONS {
12144        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12145            reason: "fan_out_limit_exceeded",
12146            member_path: member_path.clone(),
12147            message: format!(
12148                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12149            ),
12150        }));
12151    }
12152    if !root && operations.is_empty() {
12153        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12154            reason: "nested_group_empty",
12155            member_path: member_path.clone(),
12156            message: "a nested group must contain at least one durable leaf".to_string(),
12157        }));
12158    }
12159
12160    for (index, operation) in operations.iter().enumerate() {
12161        member_path.push(index);
12162        match operation {
12163            ParallelOperation::Activity {
12164                options, arguments, ..
12165            } => {
12166                options
12167                    .validate()
12168                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12169                if let Err(error) = arguments {
12170                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12171                        reason: "arguments_invalid",
12172                        member_path: member_path.clone(),
12173                        message: error.to_string(),
12174                    }));
12175                }
12176            }
12177            ParallelOperation::ChildWorkflow {
12178                options, arguments, ..
12179            } => {
12180                validate_parallel_child_options(options)?;
12181                if let Err(error) = arguments {
12182                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12183                        reason: "arguments_invalid",
12184                        member_path: member_path.clone(),
12185                        message: error.to_string(),
12186                    }));
12187                }
12188            }
12189            ParallelOperation::Timer(duration)
12190                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12191            {
12192                return Err(Error::TimerDurationOverflow);
12193            }
12194            ParallelOperation::Timer(_) => {}
12195            ParallelOperation::Signal(signal_name) => {
12196                validate_user_signal_name(signal_name)?;
12197                if signal_name.trim().is_empty() {
12198                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12199                        reason: "signal_name_empty",
12200                        member_path: member_path.clone(),
12201                        message: "signal wait name must not be empty".to_string(),
12202                    }));
12203                }
12204            }
12205            ParallelOperation::Condition { options, .. } => {
12206                options.validate()?;
12207            }
12208            ParallelOperation::Group(children) => {
12209                validate_parallel_operations(children, member_path, false)?;
12210            }
12211        }
12212        member_path.pop();
12213    }
12214    Ok(())
12215}
12216
12217fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12218    if options.task_queue.trim().is_empty() {
12219        return Err(Error::InvalidChildWorkflowOptions(
12220            "task_queue must not be empty".to_string(),
12221        ));
12222    }
12223    for (name, value) in [
12224        (
12225            "execution_timeout_seconds",
12226            options.execution_timeout_seconds,
12227        ),
12228        ("run_timeout_seconds", options.run_timeout_seconds),
12229    ] {
12230        if value == Some(0) {
12231            return Err(Error::InvalidChildWorkflowOptions(format!(
12232                "{name} must be at least 1"
12233            )));
12234        }
12235    }
12236    if options
12237        .retry_policy
12238        .as_ref()
12239        .is_some_and(|policy| policy.max_attempts == Some(0))
12240    {
12241        return Err(Error::InvalidChildWorkflowOptions(
12242            "retry_policy.max_attempts must be at least 1".to_string(),
12243        ));
12244    }
12245    Ok(())
12246}
12247
12248fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12249    ParallelShape::Group(
12250        operations
12251            .iter()
12252            .map(|operation| match operation {
12253                ParallelOperation::Group(children) => parallel_shape(children),
12254                _ => ParallelShape::Leaf,
12255            })
12256            .collect(),
12257    )
12258}
12259
12260fn parallel_descriptors(
12261    operations: Vec<ParallelOperation>,
12262    base_sequence: u64,
12263) -> Result<Vec<ParallelDescriptor>> {
12264    let size = parallel_leaf_count(&operations);
12265    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12266    let mut descriptors = Vec::with_capacity(size);
12267    let mut cursor = 0;
12268
12269    for (index, operation) in operations.into_iter().enumerate() {
12270        match operation {
12271            ParallelOperation::Group(children) => {
12272                let child_base = base_sequence
12273                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12274                    .ok_or(Error::TimerDurationOverflow)?;
12275                for mut descriptor in parallel_descriptors(children, child_base)? {
12276                    let outer_index = cursor + descriptor.offset;
12277                    descriptor.group_path.insert(
12278                        0,
12279                        parallel_group_entry(base_sequence, size, outer_index, kind),
12280                    );
12281                    descriptor.member_path.insert(0, index);
12282                    descriptor.offset = outer_index;
12283                    descriptors.push(descriptor);
12284                }
12285                cursor = descriptors.len();
12286            }
12287            operation => {
12288                descriptors.push(ParallelDescriptor {
12289                    operation,
12290                    offset: cursor,
12291                    member_path: vec![index],
12292                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12293                });
12294                cursor += 1;
12295            }
12296        }
12297    }
12298    Ok(descriptors)
12299}
12300
12301enum ParallelLeafCall {
12302    Activity(ActivityCall),
12303    ChildWorkflow(ChildWorkflowCall),
12304    Timer(TimerCall),
12305    Signal(SignalCall),
12306    Condition(ConditionWaitCall),
12307}
12308
12309fn parallel_leaf_call(
12310    ctx: &WorkflowContext,
12311    operation: ParallelOperation,
12312    parallel_group_path: Vec<ParallelGroupMetadata>,
12313) -> ParallelLeafCall {
12314    match operation {
12315        ParallelOperation::Activity {
12316            activity_type,
12317            options,
12318            arguments,
12319        } => ParallelLeafCall::Activity(ActivityCall {
12320            ctx: ctx.clone(),
12321            activity_type,
12322            options,
12323            worker_session: None,
12324            args: Some(arguments),
12325            scheduled: false,
12326            local: false,
12327            local_result: None,
12328            parallel_group_path,
12329        }),
12330        ParallelOperation::ChildWorkflow {
12331            workflow_type,
12332            options,
12333            arguments,
12334        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12335            ctx: ctx.clone(),
12336            workflow_type,
12337            options,
12338            args: Some(arguments),
12339            scheduled: false,
12340            matched_pending: false,
12341            parallel_group_path,
12342        }),
12343        ParallelOperation::Timer(duration) => {
12344            let delay_seconds = duration
12345                .as_secs()
12346                .checked_add(u64::from(duration.subsec_nanos() > 0));
12347            ParallelLeafCall::Timer(TimerCall {
12348                ctx: ctx.clone(),
12349                delay_seconds,
12350                scheduled: false,
12351                matched_pending: false,
12352                parallel_group_path,
12353            })
12354        }
12355        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12356            ctx: ctx.clone(),
12357            signal_name,
12358            runtime_reserved_allowed: false,
12359            opened_wait: false,
12360            matched_pending: false,
12361            parallel_group_path,
12362        }),
12363        ParallelOperation::Condition { options, predicate } => {
12364            ParallelLeafCall::Condition(ConditionWaitCall {
12365                ctx: ctx.clone(),
12366                options,
12367                predicate,
12368                occurrence_id: None,
12369                opened_wait: false,
12370                parallel_group_path,
12371            })
12372        }
12373        ParallelOperation::Group(_) => {
12374            unreachable!("parallel descriptors contain only durable leaves")
12375        }
12376    }
12377}
12378
12379impl ParallelLeafCall {
12380    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12381        match self {
12382            Self::Activity(call) => Pin::new(call)
12383                .poll_avro_value(cx)
12384                .map_ok(ParallelAvroResult::Activity),
12385            Self::ChildWorkflow(call) => Pin::new(call)
12386                .poll_avro_value(cx)
12387                .map_ok(ParallelAvroResult::ChildWorkflow),
12388            Self::Timer(call) => Pin::new(call)
12389                .poll(cx)
12390                .map_ok(|()| ParallelAvroResult::Timer),
12391            Self::Signal(call) => Pin::new(call)
12392                .poll_avro_value(cx)
12393                .map_ok(ParallelAvroResult::Signal),
12394            Self::Condition(call) => Pin::new(call)
12395                .poll(cx)
12396                .map_ok(ParallelAvroResult::Condition),
12397        }
12398    }
12399}
12400
12401struct ParallelLeaf {
12402    call: ParallelLeafCall,
12403    sequence: u64,
12404    member_path: Vec<usize>,
12405    group_path: Vec<ParallelGroupMetadata>,
12406    result: Option<ParallelAvroResult>,
12407}
12408
12409/// Future returned by [`WorkflowContext::parallel`].
12410pub struct ParallelCall {
12411    ctx: WorkflowContext,
12412    operations: Option<Vec<ParallelOperation>>,
12413    shape: Option<ParallelShape>,
12414    leaves: Vec<ParallelLeaf>,
12415    pending_scope_delivery: bool,
12416    worker_session: Option<WorkerSessionOptions>,
12417}
12418
12419impl ParallelCall {
12420    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12421        Self {
12422            ctx,
12423            operations: Some(operations),
12424            shape: None,
12425            leaves: Vec::new(),
12426            pending_scope_delivery: false,
12427            worker_session: None,
12428        }
12429    }
12430
12431    fn initialize(&mut self) -> Result<()> {
12432        if let Some(session) = &self.worker_session {
12433            session.to_wire()?;
12434        }
12435        let operations = self.operations.take().unwrap_or_default();
12436        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12437        self.shape = Some(parallel_shape(&operations));
12438        if operations.is_empty() {
12439            return Ok(());
12440        }
12441
12442        let base_sequence = {
12443            let state = self
12444                .ctx
12445                .state
12446                .lock()
12447                .map_err(|_| Error::WorkflowStatePoisoned)?;
12448            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12449                recorded.sequence()
12450            } else {
12451                let last = state
12452                    .recorded_commands
12453                    .last()
12454                    .map(RecordedCommand::sequence)
12455                    .unwrap_or(0);
12456                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12457                    .and_then(|sequence| sequence.checked_add(1))
12458                    .ok_or_else(|| {
12459                        Error::InvalidParallelGroup(ParallelGroupError {
12460                            reason: "sequence_overflow",
12461                            member_path: Vec::new(),
12462                            message: "parallel group sequence identity overflowed u64".to_string(),
12463                        })
12464                    })?
12465            }
12466        };
12467
12468        let descriptors = parallel_descriptors(operations, base_sequence)?;
12469        {
12470            let mut state = self
12471                .ctx
12472                .state
12473                .lock()
12474                .map_err(|_| Error::WorkflowStatePoisoned)?;
12475            let cursor = state.command_cursor;
12476            self.ctx.validate_scope_membership(&mut state, cursor)?;
12477            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12478                self.pending_scope_delivery = true;
12479                return Ok(());
12480            }
12481            state.expand_cancellation_group(&descriptors)?;
12482            state.prepare_group_cancellation(&descriptors)?;
12483        }
12484        self.leaves = descriptors
12485            .into_iter()
12486            .map(|descriptor| {
12487                let mut call = parallel_leaf_call(
12488                    &self.ctx,
12489                    descriptor.operation,
12490                    descriptor.group_path.clone(),
12491                );
12492                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12493                    (&self.worker_session, &mut call)
12494                {
12495                    activity.worker_session = Some(session.clone());
12496                }
12497                ParallelLeaf {
12498                    call,
12499                    sequence: base_sequence + descriptor.offset as u64,
12500                    member_path: descriptor.member_path,
12501                    group_path: descriptor.group_path,
12502                    result: None,
12503                }
12504            })
12505            .collect();
12506        Ok(())
12507    }
12508
12509    fn poll_avro_value(
12510        mut self: Pin<&mut Self>,
12511        cx: &mut TaskContext<'_>,
12512    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12513        if self.operations.is_some() {
12514            if let Err(error) = self.initialize() {
12515                return Poll::Ready(Err(error));
12516            }
12517        }
12518        if self.pending_scope_delivery {
12519            return Poll::Pending;
12520        }
12521        if self.leaves.is_empty() {
12522            return Poll::Ready(Ok(Vec::new()));
12523        }
12524
12525        let mut failures = Vec::new();
12526        let mut pending = false;
12527        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12528            if leaf.result.is_some() {
12529                continue;
12530            }
12531            match leaf.call.poll_avro_value(cx) {
12532                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12533                Poll::Ready(Err(error)) => failures.push((index, error)),
12534                Poll::Pending => pending = true,
12535            }
12536        }
12537
12538        if !failures.is_empty() {
12539            if let Some(position) = failures
12540                .iter()
12541                .position(|(_, error)| workflow_task_integrity_error(error))
12542            {
12543                return Poll::Ready(Err(failures.remove(position).1));
12544            }
12545            if self
12546                .ctx
12547                .state
12548                .lock()
12549                .map_err(|_| Error::WorkflowStatePoisoned)?
12550                .cancellation_delivery_intent
12551                .is_some()
12552            {
12553                return Poll::Pending;
12554            }
12555            if let Some(position) = failures
12556                .iter()
12557                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12558            {
12559                return Poll::Ready(Err(failures.remove(position).1));
12560            }
12561            failures.sort_by_key(|(index, _)| *index);
12562            let (failed_index, cause) = failures.remove(0);
12563            let failed = &self.leaves[failed_index];
12564            let completed = self
12565                .leaves
12566                .iter()
12567                .filter_map(|leaf| {
12568                    leaf.result
12569                        .clone()
12570                        .and_then(|result| result.into_json_result().ok())
12571                        .map(|result| ParallelCompletion {
12572                            member_path: leaf.member_path.clone(),
12573                            result,
12574                        })
12575                })
12576                .collect();
12577            let group_id = failed
12578                .group_path
12579                .first()
12580                .map(|entry| entry.parallel_group_id.clone())
12581                .unwrap_or_default();
12582            let sequences = self
12583                .leaves
12584                .iter()
12585                .map(|leaf| leaf.sequence)
12586                .collect::<Vec<_>>();
12587            self.ctx
12588                .state
12589                .lock()
12590                .map_err(|_| Error::WorkflowStatePoisoned)?
12591                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12592            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12593                group_id,
12594                member_path: failed.member_path.clone(),
12595                group_path: failed.group_path.clone(),
12596                completed,
12597                cause: Box::new(cause),
12598            })));
12599        }
12600        if pending
12601            || self
12602                .ctx
12603                .state
12604                .lock()
12605                .map_err(|_| Error::WorkflowStatePoisoned)?
12606                .cancellation_delivery_intent
12607                .is_some()
12608        {
12609            return Poll::Pending;
12610        }
12611
12612        let mut flat_results = self
12613            .leaves
12614            .iter_mut()
12615            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12616            .collect::<Vec<_>>()
12617            .into_iter();
12618        let results = parallel_results_for_shape(
12619            self.shape.as_ref().expect("initialized parallel shape"),
12620            &mut flat_results,
12621        );
12622        let sequences = self
12623            .leaves
12624            .iter()
12625            .map(|leaf| leaf.sequence)
12626            .collect::<Vec<_>>();
12627        self.ctx
12628            .state
12629            .lock()
12630            .map_err(|_| Error::WorkflowStatePoisoned)?
12631            .advance_cancellation_sequences(&sequences, None);
12632        Poll::Ready(Ok(match results {
12633            ParallelAvroResult::Group(results) => results,
12634            ParallelAvroResult::Activity(_)
12635            | ParallelAvroResult::ChildWorkflow(_)
12636            | ParallelAvroResult::Timer
12637            | ParallelAvroResult::Signal(_)
12638            | ParallelAvroResult::Condition(_) => {
12639                unreachable!("root parallel shape is a group")
12640            }
12641        }))
12642    }
12643}
12644
12645fn parallel_results_for_shape(
12646    shape: &ParallelShape,
12647    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12648) -> ParallelAvroResult {
12649    match shape {
12650        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12651        ParallelShape::Group(children) => ParallelAvroResult::Group(
12652            children
12653                .iter()
12654                .map(|child| parallel_results_for_shape(child, flat_results))
12655                .collect(),
12656        ),
12657    }
12658}
12659
12660impl Future for ParallelCall {
12661    type Output = Result<Vec<ParallelResult>>;
12662
12663    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12664        self.poll_avro_value(cx)
12665            .map_ok(|results| {
12666                results
12667                    .into_iter()
12668                    .map(ParallelAvroResult::into_json_result)
12669                    .collect::<Result<Vec<_>>>()
12670            })
12671            .map_ok(|result| result)
12672            .flatten_result()
12673    }
12674}
12675
12676#[derive(Clone, Debug)]
12677struct SelectionMemberPlan {
12678    key: SelectionKey,
12679    index: usize,
12680    base_sequence: u64,
12681    size: usize,
12682    kind: String,
12683    shape: ParallelShape,
12684    leaf_start: usize,
12685}
12686
12687fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12688    match operation {
12689        ParallelOperation::Activity { .. } => "activity",
12690        ParallelOperation::ChildWorkflow { .. } => "child",
12691        ParallelOperation::Timer(_) => "timer",
12692        ParallelOperation::Signal(_) => "signal",
12693        ParallelOperation::Condition { .. } => "condition",
12694        ParallelOperation::Group(_) => "group",
12695    }
12696}
12697
12698fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12699    match operation {
12700        ParallelOperation::Group(children) => parallel_shape(children),
12701        _ => ParallelShape::Leaf,
12702    }
12703}
12704
12705fn selection_descriptors(
12706    operations: Vec<(SelectionKey, ParallelOperation)>,
12707    base_sequence: u64,
12708) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12709    if operations.is_empty() {
12710        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12711            reason: "selection_empty",
12712            member_path: Vec::new(),
12713            message: "durable selection requires at least one operation".to_string(),
12714        }));
12715    }
12716    let operation_refs = operations
12717        .iter()
12718        .map(|(_, operation)| operation)
12719        .collect::<Vec<_>>();
12720    let total_size = operation_refs
12721        .iter()
12722        .map(|operation| match operation {
12723            ParallelOperation::Group(children) => parallel_leaf_count(children),
12724            _ => 1,
12725        })
12726        .sum::<usize>();
12727    if total_size > MAX_PARALLEL_OPERATIONS {
12728        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12729            reason: "fan_out_limit_exceeded",
12730            member_path: Vec::new(),
12731            message: format!(
12732                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12733            ),
12734        }));
12735    }
12736    let group_kind = {
12737        let mut kind = None;
12738        for operation in &operation_refs {
12739            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12740            match kind {
12741                None => kind = Some(operation_kind),
12742                Some(current) if current == operation_kind => {}
12743                Some(_) => {
12744                    kind = Some("mixed");
12745                    break;
12746                }
12747            }
12748        }
12749        kind.unwrap_or("mixed")
12750    };
12751
12752    let mut descriptors = Vec::with_capacity(total_size);
12753    let mut members = Vec::with_capacity(operations.len());
12754    let mut cursor = 0usize;
12755    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12756    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12757        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12758            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12759                reason: "selection_key_invalid",
12760                member_path: vec![member_index],
12761                message: "selection member keys must be non-empty strings or non-negative integers"
12762                    .to_string(),
12763            }));
12764        }
12765        if seen_keys.contains(&key) {
12766            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12767                reason: "selection_key_duplicate",
12768                member_path: vec![member_index],
12769                message: format!("selection member key {key:?} is duplicated"),
12770            }));
12771        }
12772        seen_keys.push(key.clone());
12773        let member_size = match &operation {
12774            ParallelOperation::Group(children) => parallel_leaf_count(children),
12775            _ => 1,
12776        };
12777        if member_size == 0 {
12778            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12779                reason: "selection_member_empty",
12780                member_path: vec![member_index],
12781                message: "a selection member must contain at least one durable leaf".to_string(),
12782            }));
12783        }
12784        let member_base = base_sequence
12785            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12786            .ok_or(Error::TimerDurationOverflow)?;
12787        let member_kind = selection_operation_kind(&operation).to_string();
12788        let member_shape = selection_operation_shape(&operation);
12789        let leaf_start = descriptors.len();
12790        match operation {
12791            ParallelOperation::Group(children) => {
12792                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12793                for mut descriptor in parallel_descriptors(children, member_base)? {
12794                    let flat_index = cursor + descriptor.offset;
12795                    descriptor.group_path.insert(
12796                        0,
12797                        selection_group_entry(
12798                            base_sequence,
12799                            total_size,
12800                            flat_index,
12801                            group_kind,
12802                            &SelectionMemberMetadata {
12803                                key: key.clone(),
12804                                index: member_index,
12805                                base_sequence: member_base,
12806                                size: member_size,
12807                                kind: member_kind.clone(),
12808                            },
12809                        ),
12810                    );
12811                    descriptor.member_path.insert(0, member_index);
12812                    descriptor.offset = flat_index;
12813                    descriptors.push(descriptor);
12814                }
12815            }
12816            operation => {
12817                validate_parallel_operations(
12818                    std::slice::from_ref(&operation),
12819                    &mut Vec::new(),
12820                    true,
12821                )?;
12822                descriptors.push(ParallelDescriptor {
12823                    operation,
12824                    offset: cursor,
12825                    member_path: vec![member_index],
12826                    group_path: vec![selection_group_entry(
12827                        base_sequence,
12828                        total_size,
12829                        cursor,
12830                        group_kind,
12831                        &SelectionMemberMetadata {
12832                            key: key.clone(),
12833                            index: member_index,
12834                            base_sequence: member_base,
12835                            size: member_size,
12836                            kind: member_kind.clone(),
12837                        },
12838                    )],
12839                });
12840            }
12841        }
12842        members.push(SelectionMemberPlan {
12843            key,
12844            index: member_index,
12845            base_sequence: member_base,
12846            size: member_size,
12847            kind: member_kind,
12848            shape: member_shape,
12849            leaf_start,
12850        });
12851        cursor += member_size;
12852    }
12853    Ok((descriptors, members))
12854}
12855
12856struct SelectionLeaf {
12857    call: ParallelLeafCall,
12858    outcome: Option<Result<ParallelAvroResult>>,
12859}
12860
12861/// Stable reference to one member of a durable selection group.
12862#[derive(Clone)]
12863pub struct DurableOperationHandle {
12864    ctx: WorkflowContext,
12865    pub key: SelectionKey,
12866    pub index: usize,
12867    pub kind: String,
12868    pub identity: String,
12869    pub base_sequence: u64,
12870    pub size: usize,
12871    pub selection_group_id: String,
12872    shape: ParallelShape,
12873}
12874
12875impl std::fmt::Debug for DurableOperationHandle {
12876    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12877        formatter
12878            .debug_struct("DurableOperationHandle")
12879            .field("key", &self.key)
12880            .field("index", &self.index)
12881            .field("kind", &self.kind)
12882            .field("identity", &self.identity)
12883            .field("base_sequence", &self.base_sequence)
12884            .field("size", &self.size)
12885            .field("selection_group_id", &self.selection_group_id)
12886            .finish()
12887    }
12888}
12889
12890impl DurableOperationHandle {
12891    /// Await this member after another member has already won the selection.
12892    pub fn await_result(&self) -> DurableOperationAwaitCall {
12893        DurableOperationAwaitCall {
12894            handle: self.clone(),
12895        }
12896    }
12897
12898    /// Request cancellation without affecting siblings. The future resolves
12899    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12900    /// beat a concurrently committed terminal result.
12901    pub fn cancel(&self) -> CancelDurableOperationCall {
12902        CancelDurableOperationCall {
12903            handle: self.clone(),
12904            emitted: false,
12905        }
12906    }
12907}
12908
12909/// The one winner committed for a durable selection group.
12910#[derive(Debug)]
12911pub struct SelectionResult {
12912    pub key: SelectionKey,
12913    pub index: usize,
12914    pub kind: String,
12915    pub identity: String,
12916    pub value: Option<ParallelResult>,
12917    pub failure: Option<Error>,
12918    pub winner: DurableOperationHandle,
12919    pub handles: Vec<DurableOperationHandle>,
12920}
12921
12922impl SelectionResult {
12923    pub fn succeeded(&self) -> bool {
12924        self.failure.is_none()
12925    }
12926
12927    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12928        self.handles.iter().find(|handle| &handle.key == key)
12929    }
12930
12931    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12932        self.handles
12933            .iter()
12934            .filter(|handle| handle.index != self.index)
12935            .collect()
12936    }
12937
12938    pub fn into_result(self) -> Result<ParallelResult> {
12939        match (self.value, self.failure) {
12940            (Some(value), None) => Ok(value),
12941            (_, Some(error)) => Err(error),
12942            _ => Err(Error::WorkerLoop(
12943                "selection result contained neither a value nor a failure".to_string(),
12944            )),
12945        }
12946    }
12947}
12948
12949/// Future returned by [`WorkflowContext::select`].
12950pub struct SelectCall {
12951    ctx: WorkflowContext,
12952    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12953    members: Vec<SelectionMemberPlan>,
12954    leaves: Vec<SelectionLeaf>,
12955    group_id: Option<String>,
12956}
12957
12958impl SelectCall {
12959    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12960        Self {
12961            ctx,
12962            operations: Some(operations),
12963            members: Vec::new(),
12964            leaves: Vec::new(),
12965            group_id: None,
12966        }
12967    }
12968
12969    fn initialize(&mut self) -> Result<()> {
12970        let operations = self.operations.take().unwrap_or_default();
12971        let base_sequence = {
12972            let state = self
12973                .ctx
12974                .state
12975                .lock()
12976                .map_err(|_| Error::WorkflowStatePoisoned)?;
12977            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12978                state.recorded_commands.get(state.command_cursor)
12979            {
12980                *sequence
12981            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12982            {
12983                marker.selection_group_base_sequence
12984            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12985                recorded.sequence()
12986            } else {
12987                let last = state
12988                    .recorded_commands
12989                    .last()
12990                    .map(RecordedCommand::sequence)
12991                    .unwrap_or(0);
12992                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12993                    .and_then(|sequence| sequence.checked_add(1))
12994                    .ok_or(Error::TimerDurationOverflow)?
12995            }
12996        };
12997        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
12998        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
12999        {
13000            let mut state = self
13001                .ctx
13002                .state
13003                .lock()
13004                .map_err(|_| Error::WorkflowStatePoisoned)?;
13005            state.expand_cancellation_group(&descriptors)?;
13006            state.prepare_group_cancellation(&descriptors)?;
13007        }
13008        self.leaves = descriptors
13009            .into_iter()
13010            .map(|descriptor| SelectionLeaf {
13011                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13012                outcome: None,
13013            })
13014            .collect();
13015        self.members = members;
13016        self.group_id = Some(group_id);
13017        Ok(())
13018    }
13019}
13020
13021impl Future for SelectCall {
13022    type Output = Result<SelectionResult>;
13023
13024    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13025        if self.operations.is_some() {
13026            if let Err(error) = self.initialize() {
13027                return Poll::Ready(Err(error));
13028            }
13029        }
13030
13031        for leaf in &mut self.leaves {
13032            if leaf.outcome.is_some() {
13033                continue;
13034            }
13035            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13036                if outcome
13037                    .as_ref()
13038                    .err()
13039                    .is_some_and(workflow_task_integrity_error)
13040                {
13041                    return Poll::Ready(outcome.map(|_| unreachable!()));
13042                }
13043                leaf.outcome = Some(outcome);
13044            }
13045        }
13046
13047        if self
13048            .ctx
13049            .state
13050            .lock()
13051            .map_err(|_| Error::WorkflowStatePoisoned)?
13052            .cancellation_delivery_intent
13053            .is_some()
13054        {
13055            return Poll::Pending;
13056        }
13057
13058        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13059            matches!(
13060                leaf.outcome,
13061                Some(Err(Error::CooperativeCancellationRequested(_)))
13062            )
13063        }) {
13064            return Poll::Ready(
13065                leaf.outcome
13066                    .take()
13067                    .expect("matched cancellation")
13068                    .map(|_| unreachable!()),
13069            );
13070        }
13071
13072        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13073        let selection_member_range = self
13074            .members
13075            .first()
13076            .map(|member| member.base_sequence)
13077            .zip(self.leaves.len().try_into().ok())
13078            .map(|(base_sequence, size): (u64, u64)| {
13079                base_sequence..base_sequence.saturating_add(size)
13080            });
13081        let marker = {
13082            let mut state = match self.ctx.state.lock() {
13083                Ok(state) => state,
13084                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13085            };
13086            let marker = state
13087                .selection_markers
13088                .get(state.selection_marker_cursor)
13089                .cloned();
13090            if marker.is_none()
13091                && all_members_terminal
13092                && selection_member_range.as_ref().is_some_and(|member_range| {
13093                    state
13094                        .recorded_commands
13095                        .iter()
13096                        .any(|command| member_range.contains(&command.sequence()))
13097                })
13098            {
13099                // Terminal member history can be committed before the server's
13100                // SelectionResolved marker becomes visible to this task. That
13101                // marker is the durable barrier the selection is still waiting
13102                // on, so an otherwise commandless replay remains legitimately
13103                // pending instead of failing as an untracked yield.
13104                state.matched_recorded_pending = true;
13105            }
13106            marker
13107        };
13108        let Some(marker) = marker else {
13109            return Poll::Pending;
13110        };
13111        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13112            || marker.selection_group_size != self.leaves.len()
13113            || self.members.first().map(|member| member.base_sequence)
13114                != Some(marker.selection_group_base_sequence)
13115        {
13116            return Poll::Ready(Err(invalid_recorded_history(
13117                "selection_group_shape_mismatch",
13118                marker.selection_group_base_sequence,
13119                self.group_id
13120                    .as_deref()
13121                    .unwrap_or("initialized selection group"),
13122                &marker.selection_group_id,
13123                "recorded selection group differs from current workflow code",
13124            )));
13125        }
13126        let Some(member_position) = self.members.iter().position(|member| {
13127            member.key == marker.member_key
13128                && member.index == marker.member_index
13129                && member.base_sequence == marker.member_base_sequence
13130                && member.size == marker.member_size
13131                && member.kind == marker.operation_kind
13132        }) else {
13133            return Poll::Ready(Err(invalid_recorded_history(
13134                "selection_member_shape_mismatch",
13135                marker.member_base_sequence,
13136                "winner member matching current workflow code",
13137                &format!("{:?}", marker.member_key),
13138                "recorded selection winner differs from the authored member identity",
13139            )));
13140        };
13141        let member = self.members[member_position].clone();
13142        let (handles, resolution_sequence) = {
13143            let mut state = match self.ctx.state.lock() {
13144                Ok(state) => state,
13145                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13146            };
13147            let identities = self
13148                .members
13149                .iter()
13150                .map(|candidate| {
13151                    selection_operation_identity(
13152                        &state,
13153                        &candidate.kind,
13154                        candidate.base_sequence,
13155                        candidate.size,
13156                    )
13157                })
13158                .collect::<Vec<_>>();
13159            if let Some((position, missing)) = identities
13160                .iter()
13161                .enumerate()
13162                .find(|(_, identity)| identity.is_empty())
13163                .map(|(position, identity)| (position, identity.clone()))
13164            {
13165                let candidate = &self.members[position];
13166                return Poll::Ready(Err(invalid_recorded_history(
13167                    "selection_operation_identity_missing",
13168                    candidate.base_sequence,
13169                    &format!(
13170                        "durable {} resource identity from scheduled/open history",
13171                        candidate.kind
13172                    ),
13173                    &missing,
13174                    "selection member history is missing its canonical durable identity",
13175                )));
13176            }
13177            let expected_winner_identity = &identities[member_position];
13178            let resolution_sequence = match validated_selection_resolution_sequence(
13179                &state,
13180                &marker,
13181                &member,
13182                expected_winner_identity,
13183            ) {
13184                Ok(sequence) => sequence,
13185                Err(error) => return Poll::Ready(Err(error)),
13186            };
13187            let handles = self
13188                .members
13189                .iter()
13190                .zip(identities)
13191                .map(|(member, identity)| DurableOperationHandle {
13192                    ctx: self.ctx.clone(),
13193                    key: member.key.clone(),
13194                    index: member.index,
13195                    kind: member.kind.clone(),
13196                    identity,
13197                    base_sequence: member.base_sequence,
13198                    size: member.size,
13199                    selection_group_id: marker.selection_group_id.clone(),
13200                    shape: member.shape.clone(),
13201                })
13202                .collect::<Vec<_>>();
13203            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13204                return Poll::Ready(Err(error));
13205            }
13206            state.selection_marker_cursor += 1;
13207            (handles, resolution_sequence)
13208        };
13209
13210        let mut winner_failure = None;
13211        let mut flat_results = Vec::with_capacity(member.size);
13212        if marker.outcome == "failed" {
13213            let resolution_offset = match resolution_sequence
13214                .checked_sub(member.base_sequence)
13215                .and_then(|offset| usize::try_from(offset).ok())
13216            {
13217                Some(offset) if offset < member.size => offset,
13218                _ => {
13219                    return Poll::Ready(Err(invalid_recorded_history(
13220                        "selection_resolution_event_mismatch",
13221                        member.base_sequence,
13222                        "failure event within selected member bounds",
13223                        &resolution_sequence.to_string(),
13224                        "selection failure event is outside the authored member",
13225                    )))
13226                }
13227            };
13228            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13229            match leaf.outcome.take() {
13230                Some(Err(error)) => winner_failure = Some(error),
13231                _ => {
13232                    return Poll::Ready(Err(invalid_recorded_history(
13233                        "selection_winner_outcome_mismatch",
13234                        member.base_sequence,
13235                        "exact failed terminal history referenced by SelectionResolved",
13236                        "missing or successful resolution event",
13237                        "selection winner marker disagrees with terminal operation history",
13238                    )))
13239                }
13240            }
13241        } else {
13242            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13243                match leaf.outcome.take() {
13244                    Some(Ok(result)) => flat_results.push(result),
13245                    Some(Err(_)) => {
13246                        return Poll::Ready(Err(invalid_recorded_history(
13247                            "selection_winner_outcome_mismatch",
13248                            member.base_sequence,
13249                            "fully completed nested selection member",
13250                            "failed durable leaf",
13251                            "completed selection winner contains a failed leaf",
13252                        )))
13253                    }
13254                    None => {
13255                        return Poll::Ready(Err(invalid_recorded_history(
13256                            "selection_winner_unresolved",
13257                            member.base_sequence,
13258                            "terminal history for every completed winner leaf",
13259                            "pending member history",
13260                            "completed SelectionResolved member has an unfinished durable barrier",
13261                        )))
13262                    }
13263                }
13264            }
13265        }
13266        let value = if winner_failure.is_none() {
13267            let mut flat_results = flat_results.into_iter();
13268            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13269            match value.into_json_result() {
13270                Ok(value) => Some(value),
13271                Err(error) => return Poll::Ready(Err(error)),
13272            }
13273        } else {
13274            None
13275        };
13276        let winner = handles[member_position].clone();
13277        self.ctx
13278            .state
13279            .lock()
13280            .map_err(|_| Error::WorkflowStatePoisoned)?
13281            .advance_cancellation_selection(&marker.selection_group_id);
13282        Poll::Ready(Ok(SelectionResult {
13283            key: winner.key.clone(),
13284            index: winner.index,
13285            kind: winner.kind.clone(),
13286            identity: winner.identity.clone(),
13287            value,
13288            failure: winner_failure,
13289            winner,
13290            handles,
13291        }))
13292    }
13293}
13294
13295fn selection_operation_identity(
13296    state: &WorkflowState,
13297    kind: &str,
13298    base_sequence: u64,
13299    size: usize,
13300) -> String {
13301    if kind == "group" {
13302        return format!("group:{base_sequence}:{size}");
13303    }
13304    let fields: &[&str] = match kind {
13305        "activity" => &["activity_execution_id"],
13306        "child" => &["child_workflow_run_id"],
13307        "timer" => &["timer_id"],
13308        "signal" => &["signal_wait_id"],
13309        "condition" => &["condition_wait_id"],
13310        _ => &[],
13311    };
13312    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13313        for event in state
13314            .history_events
13315            .iter()
13316            .filter(|event| durable_event_sequence(event) == Some(sequence))
13317        {
13318            for field in fields {
13319                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13320                    if !identity.is_empty() {
13321                        return identity.to_string();
13322                    }
13323                }
13324            }
13325        }
13326    }
13327    String::new()
13328}
13329
13330fn validated_selection_resolution_sequence(
13331    state: &WorkflowState,
13332    marker: &SelectionMarker,
13333    member: &SelectionMemberPlan,
13334    expected_identity: &str,
13335) -> Result<u64> {
13336    if expected_identity.is_empty() {
13337        return Err(invalid_recorded_history(
13338            "selection_operation_identity_missing",
13339            member.base_sequence,
13340            &format!(
13341                "durable {} resource identity from scheduled/open history",
13342                member.kind
13343            ),
13344            "missing operation identity",
13345            "selection member history is missing its canonical durable identity",
13346        ));
13347    }
13348    if marker.operation_identity != expected_identity {
13349        return Err(invalid_recorded_history(
13350            "selection_operation_identity_mismatch",
13351            member.base_sequence,
13352            expected_identity,
13353            &marker.operation_identity,
13354            "selection winner identity does not match durable scheduled/open history",
13355        ));
13356    }
13357
13358    let failure_types = [
13359        "ActivityFailed",
13360        "ActivityCancelled",
13361        "ActivityTimedOut",
13362        "ChildRunFailed",
13363        "ChildRunCancelled",
13364        "ChildRunTerminated",
13365    ];
13366    let success_types = [
13367        "ActivityCompleted",
13368        "ChildRunCompleted",
13369        "TimerFired",
13370        "SignalApplied",
13371        "ConditionWaitSatisfied",
13372        "ConditionWaitTimedOut",
13373    ];
13374    let terminal_types: &[&str] = if marker.outcome == "failed" {
13375        &failure_types
13376    } else {
13377        &success_types
13378    };
13379    let mut candidates = Vec::new();
13380    let member_commands = (member.base_sequence
13381        ..member.base_sequence.saturating_add(member.size as u64))
13382        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13383        .map(|command| (command.sequence(), command))
13384        .collect::<BTreeMap<_, _>>();
13385    let mut resolved_conditions = BTreeSet::new();
13386    for event in state.history_events.iter() {
13387        let Some(sequence) = durable_event_sequence(event) else {
13388            continue;
13389        };
13390        let Some(command) = member_commands.get(&sequence) else {
13391            continue;
13392        };
13393        if !terminal_types.contains(&event.event_type.as_str()) {
13394            continue;
13395        }
13396        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13397            if !matches!(
13398                event.event_type.as_str(),
13399                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13400            ) && !(event.event_type == "TimerFired"
13401                && event.payload.get("timer_kind").and_then(Value::as_str)
13402                    == Some("condition_timeout"))
13403            {
13404                continue;
13405            }
13406            if !resolved_conditions.insert(sequence) {
13407                continue;
13408            }
13409        }
13410        let event_id = event
13411            .raw
13412            .get("id")
13413            .or_else(|| event.raw.get("event_id"))
13414            .and_then(Value::as_str)
13415            .filter(|value| !value.is_empty())
13416            .ok_or_else(|| {
13417                invalid_recorded_history(
13418                    "selection_resolution_event_id_missing",
13419                    member.base_sequence,
13420                    "terminal selection history with a durable event id",
13421                    &event.payload.to_string(),
13422                    "selection terminal history cannot be bound to its winner marker",
13423                )
13424            })?;
13425        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13426    }
13427    let resolution = if marker.outcome == "failed" {
13428        candidates.first()
13429    } else {
13430        candidates.last()
13431    };
13432    let Some((event_id, event_type, sequence)) = resolution else {
13433        return Err(invalid_recorded_history(
13434            "selection_resolution_event_missing",
13435            member.base_sequence,
13436            "terminal history for the selected member",
13437            &format!("{:?}", marker.member_key),
13438            "selection winner marker has no matching durable terminal event",
13439        ));
13440    };
13441    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13442        return Err(invalid_recorded_history(
13443            "selection_resolution_event_mismatch",
13444            member.base_sequence,
13445            &format!("{event_type}:{event_id}"),
13446            &format!(
13447                "{}:{}",
13448                marker.resolution_event_type, marker.resolution_event_id
13449            ),
13450            "selection winner marker does not reference the event that made its member terminal",
13451        ));
13452    }
13453    Ok(*sequence)
13454}
13455
13456fn selection_member_recorded_command(
13457    state: &WorkflowState,
13458    authored_sequence: u64,
13459) -> Option<&RecordedCommand> {
13460    let original = state
13461        .recorded_commands
13462        .iter()
13463        .find(|command| command.sequence() == authored_sequence)?;
13464    let RecordedCommand::ConditionWait {
13465        occurrence_id,
13466        parallel_group_path: Some(_),
13467        ..
13468    } = original
13469    else {
13470        return Some(original);
13471    };
13472    // Decoding proves each physical reopen has the same authored identity and
13473    // group path after a satisfied predecessor. Only its latest wait can make
13474    // this logical member terminal.
13475    state
13476        .recorded_commands
13477        .iter()
13478        .filter(|command| {
13479            matches!(command, RecordedCommand::ConditionWait {
13480                occurrence_id: candidate, ..
13481            } if candidate == occurrence_id)
13482        })
13483        .max_by_key(|command| command.sequence())
13484}
13485
13486fn recorded_selection_member_outcome(
13487    state: &WorkflowState,
13488    handle: &DurableOperationHandle,
13489) -> Result<Option<ParallelResult>> {
13490    for event in state.history_events.iter() {
13491        let Some(sequence) = durable_event_sequence(event) else {
13492            continue;
13493        };
13494        if sequence < handle.base_sequence
13495            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13496            || !matches!(
13497                event.event_type.as_str(),
13498                "ActivityFailed"
13499                    | "ActivityCancelled"
13500                    | "ActivityTimedOut"
13501                    | "ChildRunFailed"
13502                    | "ChildRunCancelled"
13503                    | "ChildRunTerminated"
13504            )
13505        {
13506            continue;
13507        }
13508        let Some(command) = state
13509            .recorded_commands
13510            .iter()
13511            .find(|command| command.sequence() == sequence)
13512        else {
13513            continue;
13514        };
13515        match command {
13516            RecordedCommand::Activity {
13517                outcome: Some(Err(failure)),
13518                ..
13519            } => return Err(Error::ActivityFailed(failure.clone())),
13520            RecordedCommand::ChildWorkflow {
13521                outcome: Some(Err(failure)),
13522                ..
13523            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13524            _ => {}
13525        }
13526    }
13527
13528    let mut results = Vec::with_capacity(handle.size);
13529    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13530        let Some(command) = selection_member_recorded_command(state, sequence) else {
13531            return Ok(None);
13532        };
13533        let result = match command {
13534            RecordedCommand::Activity { outcome, .. } => match outcome {
13535                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13536                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13537                None => return Ok(None),
13538            },
13539            RecordedCommand::Timer { fired, .. } => {
13540                if !fired {
13541                    return Ok(None);
13542                }
13543                ParallelAvroResult::Timer
13544            }
13545            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13546                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13547                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13548                None => return Ok(None),
13549            },
13550            RecordedCommand::SignalWait { value, .. } => match value {
13551                Some(value) => ParallelAvroResult::Signal(value.clone()),
13552                None => return Ok(None),
13553            },
13554            RecordedCommand::ConditionWait { result, .. } => match result {
13555                Some(result) => ParallelAvroResult::Condition(*result),
13556                None => return Ok(None),
13557            },
13558            other => {
13559                return Err(command_mismatch(
13560                    other,
13561                    format!("selected {} member", handle.kind),
13562                ))
13563            }
13564        };
13565        results.push(result);
13566    }
13567    let mut results = results.into_iter();
13568    parallel_results_for_shape(&handle.shape, &mut results)
13569        .into_json_result()
13570        .map(Some)
13571}
13572
13573fn recorded_selection_member_is_terminal(
13574    state: &WorkflowState,
13575    handle: &DurableOperationHandle,
13576) -> bool {
13577    let mut completed = 0usize;
13578    let mut all_completed = true;
13579    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13580        let Some(command) = selection_member_recorded_command(state, sequence) else {
13581            all_completed = false;
13582            continue;
13583        };
13584        let terminal = match command {
13585            RecordedCommand::Activity {
13586                outcome: Some(Err(_)),
13587                ..
13588            }
13589            | RecordedCommand::ChildWorkflow {
13590                outcome: Some(Err(_)),
13591                ..
13592            } => return true,
13593            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13594            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13595            RecordedCommand::Timer { fired, .. } => *fired,
13596            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13597            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13598            RecordedCommand::SearchAttributes { .. }
13599            | RecordedCommand::CancellationScope { .. }
13600            | RecordedCommand::SideEffect { .. }
13601            | RecordedCommand::VersionMarker { .. }
13602            | RecordedCommand::Memo { .. }
13603            | RecordedCommand::CancellationBoundary { .. }
13604            | RecordedCommand::CancellationGroup { .. } => false,
13605        };
13606        if !terminal {
13607            all_completed = false;
13608            continue;
13609        }
13610        completed += 1;
13611    }
13612    all_completed && completed == handle.size
13613}
13614
13615fn selection_cancellation_for_handle(
13616    state: &WorkflowState,
13617    handle: &DurableOperationHandle,
13618) -> Result<bool> {
13619    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13620        recorded.selection_group_id == handle.selection_group_id
13621            && recorded.member_base_sequence == handle.base_sequence
13622    }) else {
13623        return Ok(false);
13624    };
13625    validate_selection_cancellation_marker(marker, handle)?;
13626    Ok(true)
13627}
13628
13629fn validate_selection_cancellations_for_handles(
13630    state: &WorkflowState,
13631    handles: &[DurableOperationHandle],
13632) -> Result<()> {
13633    let Some(group_id) = handles
13634        .first()
13635        .map(|handle| handle.selection_group_id.as_str())
13636    else {
13637        return Ok(());
13638    };
13639    for marker in state
13640        .cancelled_selection_members
13641        .iter()
13642        .filter(|marker| marker.selection_group_id == group_id)
13643    {
13644        let Some(handle) = handles
13645            .iter()
13646            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13647        else {
13648            return Err(invalid_recorded_history(
13649                "selection_cancellation_member_mismatch",
13650                marker.member_base_sequence,
13651                "SelectionOperationCancelled matching an authored selection handle",
13652                &format!("{marker:?}"),
13653                "selection cancellation member base does not name an authored member",
13654            ));
13655        };
13656        validate_selection_cancellation_marker(marker, handle)?;
13657    }
13658    Ok(())
13659}
13660
13661fn validate_selection_cancellation_marker(
13662    marker: &SelectionCancellation,
13663    handle: &DurableOperationHandle,
13664) -> Result<()> {
13665    if marker.selection_group_id != handle.selection_group_id
13666        || marker.member_key != handle.key
13667        || marker.member_index != handle.index
13668        || marker.member_base_sequence != handle.base_sequence
13669        || marker.member_size != handle.size
13670        || marker.operation_kind != handle.kind
13671        || marker.operation_identity != handle.identity
13672    {
13673        return Err(invalid_recorded_history(
13674            "selection_cancellation_member_mismatch",
13675            handle.base_sequence,
13676            "SelectionOperationCancelled matching the authored selection handle",
13677            &format!("{marker:?}"),
13678            "selection cancellation history targets different authored member metadata",
13679        ));
13680    }
13681    Ok(())
13682}
13683
13684/// Future returned by [`DurableOperationHandle::await_result`].
13685pub struct DurableOperationAwaitCall {
13686    handle: DurableOperationHandle,
13687}
13688
13689impl Future for DurableOperationAwaitCall {
13690    type Output = Result<ParallelResult>;
13691
13692    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13693        let mut state = match self.handle.ctx.state.lock() {
13694            Ok(state) => state,
13695            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13696        };
13697        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13698            return Poll::Ready(Err(error));
13699        }
13700        match state.prepare_selection_handle_cancellation(&self.handle) {
13701            Ok(true) => return Poll::Pending,
13702            Ok(false) => {}
13703            Err(error) => return Poll::Ready(Err(error)),
13704        }
13705        match selection_cancellation_for_handle(&state, &self.handle) {
13706            Err(error) => return Poll::Ready(Err(error)),
13707            Ok(false) => {}
13708            Ok(true) => {
13709                state.advance_cancellation_receipt(
13710                    &self.handle.selection_group_id,
13711                    self.handle.base_sequence,
13712                );
13713                return Poll::Ready(Err(Error::DurableOperationCancelled(
13714                    DurableOperationCancelled {
13715                        selection_group_id: self.handle.selection_group_id.clone(),
13716                        member_key: self.handle.key.clone(),
13717                        member_index: self.handle.index,
13718                        operation_kind: self.handle.kind.clone(),
13719                        operation_identity: self.handle.identity.clone(),
13720                    },
13721                )));
13722            }
13723        }
13724        match recorded_selection_member_outcome(&state, &self.handle) {
13725            Ok(Some(result)) => {
13726                state.advance_cancellation_handle(&self.handle, false);
13727                Poll::Ready(Ok(result))
13728            }
13729            Ok(None) => Poll::Pending,
13730            Err(error) => {
13731                if !workflow_task_integrity_error(&error) {
13732                    state.advance_cancellation_handle(&self.handle, true);
13733                }
13734                Poll::Ready(Err(error))
13735            }
13736        }
13737    }
13738}
13739
13740fn validate_selection_delivery_handle(
13741    state: &WorkflowState,
13742    handle: &DurableOperationHandle,
13743) -> Result<()> {
13744    let path = state
13745        .recorded_commands
13746        .iter()
13747        .find(|command| command.sequence() == handle.base_sequence)
13748        .and_then(|command| match command {
13749            RecordedCommand::Activity {
13750                parallel_group_path,
13751                ..
13752            }
13753            | RecordedCommand::ChildWorkflow {
13754                parallel_group_path,
13755                ..
13756            }
13757            | RecordedCommand::Timer {
13758                parallel_group_path,
13759                ..
13760            }
13761            | RecordedCommand::SignalWait {
13762                parallel_group_path,
13763                ..
13764            }
13765            | RecordedCommand::ConditionWait {
13766                parallel_group_path,
13767                ..
13768            } => parallel_group_path.as_ref(),
13769            _ => None,
13770        })
13771        .and_then(|path| path.first());
13772    let matches = path.is_some_and(|entry| {
13773        entry.parallel_group_mode.as_deref() == Some("select")
13774            && entry.parallel_group_id == handle.selection_group_id
13775            && entry.selection_member_key.as_ref() == Some(&handle.key)
13776            && entry.selection_member_index == Some(handle.index)
13777            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13778            && entry.selection_member_size == Some(handle.size)
13779            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13780    });
13781    if !matches
13782        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13783            != handle.identity
13784    {
13785        return Err(invalid_recorded_history(
13786            "cooperative_cancellation_call_mismatch",
13787            handle.base_sequence,
13788            "selection handle matching its authored durable identity",
13789            &format!("{handle:?}"),
13790            "selection handle identity or member metadata changed before cancellation replay",
13791        ));
13792    }
13793    Ok(())
13794}
13795
13796/// Future returned by [`DurableOperationHandle::cancel`].
13797pub struct CancelDurableOperationCall {
13798    handle: DurableOperationHandle,
13799    emitted: bool,
13800}
13801
13802impl Future for CancelDurableOperationCall {
13803    type Output = Result<()>;
13804
13805    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13806        let ctx = self.handle.ctx.clone();
13807        let mut state = match ctx.state.lock() {
13808            Ok(state) => state,
13809            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13810        };
13811        match selection_cancellation_for_handle(&state, &self.handle) {
13812            Err(error) => return Poll::Ready(Err(error)),
13813            Ok(true) => {
13814                state.advance_cancellation_receipt(
13815                    &self.handle.selection_group_id,
13816                    self.handle.base_sequence,
13817                );
13818                return Poll::Ready(Ok(()));
13819            }
13820            Ok(false) => {}
13821        }
13822        if recorded_selection_member_is_terminal(&state, &self.handle) {
13823            return Poll::Ready(Ok(()));
13824        }
13825        if !self.emitted {
13826            state.commands.push(json!({
13827                "type": "cancel_selection_operation",
13828                "selection_group_id": self.handle.selection_group_id,
13829                "member_key": self.handle.key,
13830                "member_index": self.handle.index,
13831                "member_base_sequence": self.handle.base_sequence,
13832                "member_size": self.handle.size,
13833                "operation_kind": self.handle.kind,
13834                "operation_identity": self.handle.identity,
13835            }));
13836            self.emitted = true;
13837        }
13838        // The cancellation command is only a request. Do not expose workflow
13839        // state after cancel until committed SelectionOperationCancelled
13840        // history proves that the request won the race with member completion.
13841        Poll::Pending
13842    }
13843}
13844
13845trait PollNestedResultExt<T> {
13846    fn flatten_result(self) -> Poll<Result<T>>;
13847}
13848
13849impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13850    fn flatten_result(self) -> Poll<Result<T>> {
13851        match self {
13852            Poll::Ready(Ok(result)) => Poll::Ready(result),
13853            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13854            Poll::Pending => Poll::Pending,
13855        }
13856    }
13857}
13858
13859struct SagaCompensation {
13860    activity_type: String,
13861    options: ActivityOptions,
13862    arguments: AvroValue,
13863    registration_order: usize,
13864}
13865
13866/// Workflow-local deterministic saga compensation helper.
13867///
13868/// Register each compensation only after its forward step succeeds. Passing
13869/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13870/// reverse registration order after any failure, including cooperative
13871/// cancellation. Each compensation is an ordinary durable activity, so replay,
13872/// duplicate delivery, and worker restart use existing history semantics.
13873pub struct Saga {
13874    ctx: WorkflowContext,
13875    compensations: Vec<SagaCompensation>,
13876}
13877
13878impl Saga {
13879    fn new(ctx: WorkflowContext) -> Self {
13880        Self {
13881            ctx,
13882            compensations: Vec::new(),
13883        }
13884    }
13885
13886    pub fn add_compensation<T: Serialize>(
13887        &mut self,
13888        activity_type: impl Into<String>,
13889        args: T,
13890    ) -> Result<&mut Self> {
13891        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13892    }
13893
13894    pub fn add_compensation_with_options<T: Serialize>(
13895        &mut self,
13896        activity_type: impl Into<String>,
13897        options: ActivityOptions,
13898        args: T,
13899    ) -> Result<&mut Self> {
13900        let activity_type = activity_type.into();
13901        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13902            return Err(Error::Codec(
13903                "saga compensation activity type must be non-empty without surrounding whitespace"
13904                    .to_string(),
13905            ));
13906        }
13907        options.validate().map_err(Error::InvalidActivityOptions)?;
13908        let arguments = AvroValue::from_serialize(&args)?;
13909        let registration_order = self.compensations.len() + 1;
13910        self.compensations.push(SagaCompensation {
13911            activity_type,
13912            options,
13913            arguments,
13914            registration_order,
13915        });
13916        Ok(self)
13917    }
13918
13919    /// Compensate `initiating_failure` and return the failure that must remain.
13920    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13921        let _shield = match self.ctx.cancellation_shield() {
13922            Ok(shield) => shield,
13923            Err(error) => return error,
13924        };
13925        while let Some(compensation) = self.compensations.pop() {
13926            if let Err(compensation_failure) = self
13927                .ctx
13928                .activity_with_options(
13929                    compensation.activity_type.clone(),
13930                    compensation.options,
13931                    compensation.arguments,
13932                )
13933                .await
13934            {
13935                if workflow_task_integrity_error(&compensation_failure) {
13936                    return compensation_failure;
13937                }
13938                return Error::SagaCompensationFailed(SagaCompensationFailure {
13939                    initiating_failure: Box::new(initiating_failure),
13940                    compensation_failure: Box::new(compensation_failure),
13941                    compensation_activity_type: compensation.activity_type,
13942                    compensation_registration_order: compensation.registration_order,
13943                });
13944            }
13945        }
13946        initiating_failure
13947    }
13948
13949    /// Return a successful forward value or compensate and preserve its failure.
13950    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13951        match outcome {
13952            Ok(value) => Ok(value),
13953            Err(error) => Err(self.compensate(error).await),
13954        }
13955    }
13956}
13957
13958pub struct ActivityCall {
13959    ctx: WorkflowContext,
13960    activity_type: String,
13961    options: ActivityOptions,
13962    worker_session: Option<WorkerSessionOptions>,
13963    args: Option<Result<AvroValue>>,
13964    scheduled: bool,
13965    local: bool,
13966    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13967    parallel_group_path: Vec<ParallelGroupMetadata>,
13968}
13969
13970impl ActivityCall {
13971    fn poll_avro_value(
13972        mut self: Pin<&mut Self>,
13973        _cx: &mut TaskContext<'_>,
13974    ) -> Poll<Result<AvroValue>> {
13975        let ctx = self.ctx.clone();
13976        let mut state = match ctx.state.lock() {
13977            Ok(state) => state,
13978            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13979        };
13980
13981        if let Some(result) = &self.local_result {
13982            return match result.lock() {
13983                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13984                    Poll::Ready(result.map_err(Error::ActivityFailed))
13985                }),
13986                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13987            };
13988        }
13989        if self.scheduled {
13990            return Poll::Pending;
13991        }
13992
13993        let options = match self.options.validate() {
13994            Ok(options) => options,
13995            Err(error) => {
13996                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
13997            }
13998        };
13999        if self.local {
14000            if self.worker_session.is_some() {
14001                return Poll::Ready(Err(Error::WorkerLoop(
14002                    "local activities cannot use worker-session routing".into(),
14003                )));
14004            }
14005            if let Err(error) = local_activity::validate(&options) {
14006                return Poll::Ready(Err(error));
14007            }
14008        }
14009        let session = match self
14010            .worker_session
14011            .as_ref()
14012            .map(WorkerSessionOptions::to_wire)
14013            .transpose()
14014        {
14015            Ok(value) => value,
14016            Err(error) => return Poll::Ready(Err(error)),
14017        };
14018        let session_queue = session
14019            .as_ref()
14020            .and_then(|session| session["queue"].as_str());
14021        let task_queue = options
14022            .task_queue
14023            .clone()
14024            .or_else(|| session_queue.map(str::to_owned))
14025            .unwrap_or_else(|| state.task_queue.clone());
14026        if session_queue.is_some_and(|queue| queue != task_queue) {
14027            return Poll::Ready(Err(Error::WorkerLoop(
14028                "worker-session queue must match the activity task queue".into(),
14029            )));
14030        }
14031        let current_recorded_options = RecordedActivityOptions {
14032            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14033            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14034            retry_policy: current_activity_retry_snapshot(&options),
14035            worker_session: session,
14036        };
14037
14038        let cursor = state.command_cursor;
14039        let call_kind = if self.local {
14040            CancellationCallKind::LocalActivity
14041        } else {
14042            CancellationCallKind::Activity
14043        };
14044        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14045            return Poll::Ready(Err(error));
14046        }
14047        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14048            Ok(recorded) => recorded,
14049            Err(error) => return Poll::Ready(Err(error)),
14050        };
14051        if let Some(recorded) = recorded {
14052            let sequence = recorded.sequence();
14053            match recorded {
14054                RecordedCommand::Activity {
14055                    activity_type,
14056                    cancellation_policy,
14057                    options: recorded_options,
14058                    outcome,
14059                    parallel_group_path,
14060                    ..
14061                } => {
14062                    let current_policy = options
14063                        .cancellation_policy
14064                        .unwrap_or(CancellationPolicy::TryCancel)
14065                        .as_str();
14066                    if cancellation_policy != current_policy {
14067                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14068                            ReplayFailure::new(
14069                                "activity_cancellation_policy_changed",
14070                                Some(sequence),
14071                                Some(cancellation_policy),
14072                                Some(current_policy.to_string()),
14073                                "Activity cancellation policy changed during replay",
14074                            ),
14075                        )));
14076                    }
14077                    if let Err(error) = ensure_parallel_path_matches(
14078                        sequence,
14079                        parallel_group_path.as_deref(),
14080                        &self.parallel_group_path,
14081                    ) {
14082                        return Poll::Ready(Err(error));
14083                    }
14084                    if let Some(recorded_type) = activity_type {
14085                        if recorded_type != self.activity_type {
14086                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14087                                ReplayFailure::new(
14088                                    "recorded_command_detail_mismatch",
14089                                    Some(sequence),
14090                                    Some(format!("activity:{recorded_type}")),
14091                                    Some(format!("activity:{}", self.activity_type)),
14092                                    "recorded activity type differs from the current workflow command",
14093                                ),
14094                            )));
14095                        }
14096                    }
14097                    if let Some(recorded_options) = recorded_options {
14098                        if recorded_options.worker_session
14099                            != current_recorded_options.worker_session
14100                        {
14101                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14102                                "activity_worker_session_mismatch", Some(sequence),
14103                                Some(activity_options_description(&recorded_options)),
14104                                Some(activity_options_description(&current_recorded_options)),
14105                                "recorded worker-session routing differs from the current activity",
14106                            ))));
14107                        }
14108                        if !recorded_options
14109                            .task_queue
14110                            .matches_current(&current_recorded_options.task_queue)
14111                        {
14112                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14113                                ReplayFailure::new(
14114                                    "activity_task_queue_mismatch",
14115                                    Some(sequence),
14116                                    Some(activity_options_description(&recorded_options)),
14117                                    Some(activity_options_description(&current_recorded_options)),
14118                                    "recorded activity task queue differs from the current workflow command",
14119                                ),
14120                            )));
14121                        }
14122                        if (self.local
14123                            && matches!(
14124                                recorded_options.execution_mode,
14125                                RecordedSnapshotValue::Unknown
14126                            ))
14127                            || !recorded_options
14128                                .execution_mode
14129                                .matches_current(&current_recorded_options.execution_mode)
14130                        {
14131                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14132                                ReplayFailure::new(
14133                                    "activity_execution_mode_mismatch",
14134                                    Some(sequence),
14135                                    Some(activity_options_description(&recorded_options)),
14136                                    Some(activity_options_description(&current_recorded_options)),
14137                                    "recorded activity execution mode differs from the current workflow command",
14138                                ),
14139                            )));
14140                        }
14141                        if !recorded_options
14142                            .retry_policy
14143                            .matches_current(&current_recorded_options.retry_policy)
14144                        {
14145                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14146                                ReplayFailure::new(
14147                                    "activity_retry_policy_mismatch",
14148                                    Some(sequence),
14149                                    Some(activity_options_description(&recorded_options)),
14150                                    Some(activity_options_description(&current_recorded_options)),
14151                                    "recorded activity retry policy differs from the current workflow command",
14152                                ),
14153                            )));
14154                        }
14155                    }
14156                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14157                        return Poll::Ready(Err(error));
14158                    }
14159                    match state.prepare_scalar_cancellation(
14160                        cursor,
14161                        call_kind,
14162                        &self.parallel_group_path,
14163                    ) {
14164                        Ok(true) => {
14165                            self.scheduled = true;
14166                            return Poll::Pending;
14167                        }
14168                        Ok(false) => {}
14169                        Err(error) => return Poll::Ready(Err(error)),
14170                    }
14171                    state.command_cursor += 1;
14172                    if let Some(outcome) = outcome {
14173                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14174                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
14175                    }
14176                    state.matched_recorded_pending = true;
14177                    self.scheduled = true;
14178                    return Poll::Pending;
14179                }
14180                other => {
14181                    return Poll::Ready(Err(command_mismatch(
14182                        &other,
14183                        format!("activity:{}", self.activity_type),
14184                    )));
14185                }
14186            }
14187        }
14188
14189        if !self.scheduled {
14190            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14191                Ok(args) => args,
14192                Err(error) => return Poll::Ready(Err(error)),
14193            };
14194            let arguments = normalize_avro_arguments(args);
14195            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14196                Ok(envelope) => envelope,
14197                Err(error) => return Poll::Ready(Err(error)),
14198            };
14199
14200            let mut command = serde_json::Map::from_iter([
14201                (
14202                    "type".to_string(),
14203                    json!(if self.local {
14204                        "record_local_activity"
14205                    } else {
14206                        "schedule_activity"
14207                    }),
14208                ),
14209                (
14210                    "activity_type".to_string(),
14211                    json!(self.activity_type.clone()),
14212                ),
14213                ("queue".to_string(), json!(task_queue)),
14214                ("arguments".to_string(), envelope),
14215            ]);
14216            for (field, value) in [
14217                ("start_to_close_timeout", options.start_to_close_timeout),
14218                (
14219                    "schedule_to_start_timeout",
14220                    options.schedule_to_start_timeout,
14221                ),
14222                (
14223                    "schedule_to_close_timeout",
14224                    options.schedule_to_close_timeout,
14225                ),
14226                ("heartbeat_timeout", options.heartbeat_timeout),
14227            ] {
14228                if let Some(value) = value {
14229                    command.insert(field.to_string(), json!(value));
14230                }
14231            }
14232            if let Some(retry_policy) = &options.retry_policy {
14233                command.insert("retry_policy".to_string(), retry_policy.clone());
14234            }
14235            if let Some(policy) = options.cancellation_policy {
14236                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14237            }
14238            if let Some(session) = current_recorded_options.worker_session {
14239                command.insert("worker_session".into(), session);
14240            }
14241            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14242            ctx.apply_scope_membership(&mut command);
14243            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14244                Ok(true) => {
14245                    self.scheduled = true;
14246                    return Poll::Pending;
14247                }
14248                Ok(false) => {}
14249                Err(error) => return Poll::Ready(Err(error)),
14250            }
14251            if self.local {
14252                command.remove("queue");
14253                command.insert("execution_mode".into(), json!("local"));
14254                let result = Arc::new(Mutex::new(None));
14255                let command_index = state.commands.len();
14256                state.local_activity_requests.push(local_activity::Request {
14257                    command_index,
14258                    options,
14259                    arguments,
14260                    result: result.clone(),
14261                });
14262                self.local_result = Some(result);
14263            }
14264            state.commands.push(Value::Object(command));
14265            self.scheduled = true;
14266        }
14267
14268        Poll::Pending
14269    }
14270}
14271
14272impl Future for ActivityCall {
14273    type Output = Result<Value>;
14274
14275    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14276        match self.poll_avro_value(cx) {
14277            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14278            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14279            Poll::Pending => Poll::Pending,
14280        }
14281    }
14282}
14283
14284/// Future returned by [`WorkflowContext::sleep`].
14285pub struct TimerCall {
14286    ctx: WorkflowContext,
14287    delay_seconds: Option<u64>,
14288    scheduled: bool,
14289    matched_pending: bool,
14290    parallel_group_path: Vec<ParallelGroupMetadata>,
14291}
14292
14293impl Future for TimerCall {
14294    type Output = Result<()>;
14295
14296    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14297        if self.matched_pending {
14298            return Poll::Pending;
14299        }
14300
14301        let ctx = self.ctx.clone();
14302        let Some(requested_delay) = self.delay_seconds else {
14303            return Poll::Ready(Err(Error::TimerDurationOverflow));
14304        };
14305        let mut state = match ctx.state.lock() {
14306            Ok(state) => state,
14307            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14308        };
14309
14310        let cursor = state.command_cursor;
14311        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14312            return Poll::Ready(Err(error));
14313        }
14314        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14315        {
14316            Ok(recorded) => recorded,
14317            Err(error) => return Poll::Ready(Err(error)),
14318        };
14319        if let Some(recorded) = recorded {
14320            match recorded {
14321                RecordedCommand::Timer {
14322                    sequence,
14323                    delay_seconds,
14324                    fired,
14325                    parallel_group_path,
14326                    ..
14327                } => {
14328                    if let Err(error) =
14329                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14330                    {
14331                        return Poll::Ready(Err(error));
14332                    }
14333                    if let Err(error) = ensure_parallel_path_matches(
14334                        sequence,
14335                        parallel_group_path.as_deref(),
14336                        &self.parallel_group_path,
14337                    ) {
14338                        return Poll::Ready(Err(error));
14339                    }
14340                    if delay_seconds != requested_delay {
14341                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14342                            ReplayFailure::new(
14343                                "timer_delay_mismatch",
14344                                Some(sequence),
14345                                Some(format!("timer:{delay_seconds}s")),
14346                                Some(format!("timer:{requested_delay}s")),
14347                                "recorded timer delay differs from the current workflow command",
14348                            ),
14349                        )));
14350                    }
14351                    if let Err(error) =
14352                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14353                    {
14354                        return Poll::Ready(Err(error));
14355                    }
14356                    match state.prepare_scalar_cancellation(
14357                        cursor,
14358                        CancellationCallKind::Timer,
14359                        &self.parallel_group_path,
14360                    ) {
14361                        Ok(true) => {
14362                            self.scheduled = true;
14363                            self.matched_pending = true;
14364                            return Poll::Pending;
14365                        }
14366                        Ok(false) => {}
14367                        Err(error) => return Poll::Ready(Err(error)),
14368                    }
14369                    state.command_cursor += 1;
14370                    if fired {
14371                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14372                        return Poll::Ready(Ok(()));
14373                    }
14374                    state.matched_recorded_pending = true;
14375                    self.scheduled = true;
14376                    self.matched_pending = true;
14377                    return Poll::Pending;
14378                }
14379                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14380            }
14381        }
14382
14383        if !self.scheduled {
14384            let mut command = serde_json::Map::from_iter([
14385                ("type".to_string(), json!("start_timer")),
14386                ("delay_seconds".to_string(), json!(requested_delay)),
14387            ]);
14388            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14389                Ok(Some(proof)) => {
14390                    command.insert("cancellation_cleanup".into(), proof);
14391                }
14392                Ok(None) => {}
14393                Err(error) => return Poll::Ready(Err(error)),
14394            }
14395            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14396            ctx.apply_scope_membership(&mut command);
14397            match state.prepare_scalar_cancellation(
14398                cursor,
14399                CancellationCallKind::Timer,
14400                &self.parallel_group_path,
14401            ) {
14402                Ok(true) => {
14403                    self.scheduled = true;
14404                    self.matched_pending = true;
14405                    return Poll::Pending;
14406                }
14407                Ok(false) => {}
14408                Err(error) => return Poll::Ready(Err(error)),
14409            }
14410            state.commands.push(Value::Object(command));
14411            self.scheduled = true;
14412        }
14413
14414        Poll::Pending
14415    }
14416}
14417
14418/// Future returned by [`WorkflowContext::wait_condition`].
14419pub struct ConditionWaitCall {
14420    ctx: WorkflowContext,
14421    options: ConditionWaitOptions,
14422    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14423    occurrence_id: Option<String>,
14424    opened_wait: bool,
14425    parallel_group_path: Vec<ParallelGroupMetadata>,
14426}
14427
14428impl Future for ConditionWaitCall {
14429    type Output = Result<ConditionWaitResult>;
14430
14431    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14432        if self.opened_wait {
14433            return Poll::Pending;
14434        }
14435
14436        let options = match self.options.validate() {
14437            Ok(options) => options,
14438            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14439        };
14440        let ctx = self.ctx.clone();
14441        let occurrence_id = match self.occurrence_id.as_ref() {
14442            Some(occurrence_id) => occurrence_id.clone(),
14443            None => {
14444                let mut state = match ctx.state.lock() {
14445                    Ok(state) => state,
14446                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14447                };
14448                let ordinal = state.condition_wait_occurrence_counter;
14449                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14450                    Some(next) => next,
14451                    None => {
14452                        return Poll::Ready(Err(Error::WorkerLoop(
14453                            "condition wait occurrence counter overflowed".to_string(),
14454                        )))
14455                    }
14456                };
14457                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14458                drop(state);
14459                self.occurrence_id = Some(occurrence_id.clone());
14460                occurrence_id
14461            }
14462        };
14463
14464        let recorded_result = {
14465            let mut state = match ctx.state.lock() {
14466                Ok(state) => state,
14467                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14468            };
14469            let initial_cursor = state.command_cursor;
14470            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14471                return Poll::Ready(Err(error));
14472            }
14473            let recorded = match state
14474                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14475            {
14476                Ok(recorded) => recorded,
14477                Err(error) => return Poll::Ready(Err(error)),
14478            };
14479            let Some(recorded) = recorded else {
14480                drop(state);
14481                return self.poll_new_condition(options);
14482            };
14483            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14484                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14485            }
14486
14487            let mut cursor = state.command_cursor;
14488            let mut result = None;
14489            let mut pending_delivery = false;
14490            loop {
14491                if cursor > initial_cursor
14492                    && matches!(
14493                        state.recorded_commands.get(cursor),
14494                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14495                    )
14496                {
14497                    break;
14498                }
14499                let recorded = match state
14500                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14501                {
14502                    Ok(recorded) => recorded,
14503                    Err(error) => return Poll::Ready(Err(error)),
14504                };
14505                let Some(RecordedCommand::ConditionWait {
14506                    sequence,
14507                    occurrence_id: ref recorded_occurrence_id,
14508                    ref condition_key,
14509                    ref predicate_identity,
14510                    timeout_seconds,
14511                    result: recorded_result,
14512                    ref parallel_group_path,
14513                    ..
14514                }) = recorded
14515                else {
14516                    break;
14517                };
14518
14519                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14520                    break;
14521                }
14522                if let Err(error) = ensure_parallel_path_matches(
14523                    sequence,
14524                    parallel_group_path.as_deref(),
14525                    &self.parallel_group_path,
14526                ) {
14527                    return Poll::Ready(Err(error));
14528                }
14529                if let Err(error) = validate_recorded_condition_wait(
14530                    sequence,
14531                    recorded_occurrence_id,
14532                    condition_key.as_deref(),
14533                    predicate_identity,
14534                    timeout_seconds,
14535                    &occurrence_id,
14536                    &options,
14537                ) {
14538                    return Poll::Ready(Err(error));
14539                }
14540                if result == Some(ConditionWaitResult::TimedOut) {
14541                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14542                        "condition_wait_reopened_after_timeout",
14543                        Some(sequence),
14544                        Some("timed-out condition is terminal".to_string()),
14545                        Some("another physical wait-open".to_string()),
14546                        "condition history reopened one logical wait after its durable timeout",
14547                    ))));
14548                }
14549                if let Err(error) =
14550                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14551                {
14552                    return Poll::Ready(Err(error));
14553                }
14554                match state.prepare_scalar_cancellation(
14555                    cursor,
14556                    CancellationCallKind::Condition,
14557                    &self.parallel_group_path,
14558                ) {
14559                    Ok(pending) => pending_delivery |= pending,
14560                    Err(error) => return Poll::Ready(Err(error)),
14561                }
14562                result = recorded_result;
14563                if result.is_some() {
14564                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14565                }
14566                cursor += 1;
14567            }
14568            state.command_cursor = cursor;
14569            if pending_delivery {
14570                self.opened_wait = true;
14571                return Poll::Pending;
14572            }
14573            result
14574        };
14575
14576        if let Some(result) = recorded_result {
14577            return Poll::Ready(Ok(result));
14578        }
14579
14580        self.poll_open_condition(options, true)
14581    }
14582}
14583
14584impl ConditionWaitCall {
14585    fn poll_new_condition(
14586        self: Pin<&mut Self>,
14587        options: ValidatedConditionWaitOptions,
14588    ) -> Poll<Result<ConditionWaitResult>> {
14589        self.poll_open_condition(options, false)
14590    }
14591
14592    fn poll_open_condition(
14593        mut self: Pin<&mut Self>,
14594        options: ValidatedConditionWaitOptions,
14595        recorded_wait: bool,
14596    ) -> Poll<Result<ConditionWaitResult>> {
14597        {
14598            let ctx = self.ctx.clone();
14599            let mut state = match ctx.state.lock() {
14600                Ok(state) => state,
14601                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14602            };
14603            let cursor = state.command_cursor;
14604            match state.prepare_scalar_cancellation(
14605                cursor,
14606                CancellationCallKind::Condition,
14607                &self.parallel_group_path,
14608            ) {
14609                Ok(true) => {
14610                    self.opened_wait = true;
14611                    return Poll::Pending;
14612                }
14613                Ok(false) => {}
14614                Err(error) => return Poll::Ready(Err(error)),
14615            }
14616        }
14617        let selection_member = self
14618            .parallel_group_path
14619            .first()
14620            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14621        match (self.predicate)() {
14622            Ok(true) if !selection_member || recorded_wait => {
14623                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14624            }
14625            Ok(_) => {}
14626            Err(error) => return Poll::Ready(Err(error)),
14627        }
14628        if options.timeout_seconds == Some(0) && !selection_member {
14629            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14630        }
14631
14632        let ctx = self.ctx.clone();
14633        let mut state = match ctx.state.lock() {
14634            Ok(state) => state,
14635            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14636        };
14637        let mut command = serde_json::Map::from_iter([
14638            ("type".to_string(), json!("open_condition_wait")),
14639            (
14640                "condition_wait_occurrence_id".to_string(),
14641                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14642            ),
14643            ("condition_key".to_string(), json!(options.condition_key)),
14644            (
14645                "condition_definition_fingerprint".to_string(),
14646                json!(options.predicate_identity),
14647            ),
14648        ]);
14649        if let Some(timeout_seconds) = options.timeout_seconds {
14650            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14651        }
14652        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14653        ctx.apply_scope_membership(&mut command);
14654        state.commands.push(Value::Object(command));
14655        drop(state);
14656        self.opened_wait = true;
14657        Poll::Pending
14658    }
14659}
14660
14661fn validate_recorded_condition_wait(
14662    sequence: u64,
14663    recorded_occurrence_id: &str,
14664    recorded_key: Option<&str>,
14665    recorded_predicate_identity: &str,
14666    recorded_timeout_seconds: Option<u64>,
14667    current_occurrence_id: &str,
14668    current: &ValidatedConditionWaitOptions,
14669) -> Result<()> {
14670    if recorded_occurrence_id != current_occurrence_id {
14671        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14672            "condition_wait_occurrence_mismatch",
14673            Some(sequence),
14674            Some(recorded_occurrence_id.to_string()),
14675            Some(current_occurrence_id.to_string()),
14676            "recorded condition occurrence differs from the current authored wait position",
14677        )));
14678    }
14679    if recorded_key != Some(current.condition_key.as_str()) {
14680        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14681            "condition_wait_key_mismatch",
14682            Some(sequence),
14683            recorded_key.map(str::to_string),
14684            Some(current.condition_key.clone()),
14685            "recorded condition identity differs from the current workflow wait",
14686        )));
14687    }
14688    if recorded_predicate_identity != current.predicate_identity {
14689        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14690            "condition_wait_predicate_mismatch",
14691            Some(sequence),
14692            Some(recorded_predicate_identity.to_string()),
14693            Some(current.predicate_identity.clone()),
14694            "recorded condition predicate behavior differs from current workflow code",
14695        )));
14696    }
14697    if recorded_timeout_seconds != current.timeout_seconds {
14698        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14699            "condition_wait_timeout_mismatch",
14700            Some(sequence),
14701            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14702            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14703            "recorded condition timeout differs from the current workflow wait",
14704        )));
14705    }
14706    Ok(())
14707}
14708
14709/// Future returned by [`WorkflowContext::start_child_workflow`].
14710pub struct ChildWorkflowCall {
14711    ctx: WorkflowContext,
14712    workflow_type: String,
14713    options: ChildWorkflowOptions,
14714    args: Option<Result<AvroValue>>,
14715    scheduled: bool,
14716    matched_pending: bool,
14717    parallel_group_path: Vec<ParallelGroupMetadata>,
14718}
14719
14720impl ChildWorkflowCall {
14721    fn poll_avro_value(
14722        mut self: Pin<&mut Self>,
14723        _cx: &mut TaskContext<'_>,
14724    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14725        if self.matched_pending {
14726            return Poll::Pending;
14727        }
14728
14729        let ctx = self.ctx.clone();
14730        let mut state = match ctx.state.lock() {
14731            Ok(state) => state,
14732            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14733        };
14734
14735        let cursor = state.command_cursor;
14736        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14737            return Poll::Ready(Err(error));
14738        }
14739        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14740        {
14741            Ok(recorded) => recorded,
14742            Err(error) => return Poll::Ready(Err(error)),
14743        };
14744        if let Some(recorded) = recorded {
14745            let sequence = recorded.sequence();
14746            match recorded {
14747                RecordedCommand::ChildWorkflow {
14748                    workflow_type,
14749                    policies,
14750                    outcome,
14751                    parallel_group_path,
14752                    ..
14753                } => {
14754                    if let Err(error) = ensure_parallel_path_matches(
14755                        sequence,
14756                        parallel_group_path.as_deref(),
14757                        &self.parallel_group_path,
14758                    ) {
14759                        return Poll::Ready(Err(error));
14760                    }
14761                    if let Some(recorded_type) = workflow_type {
14762                        if recorded_type != self.workflow_type {
14763                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14764                                ReplayFailure::new(
14765                                    "recorded_command_detail_mismatch",
14766                                    Some(sequence),
14767                                    Some(format!("child workflow:{recorded_type}")),
14768                                    Some(format!("child workflow:{}", self.workflow_type)),
14769                                    "recorded child workflow type differs from the current workflow command",
14770                                ),
14771                            )));
14772                        }
14773                    }
14774                    if let Err(error) =
14775                        ensure_child_policies_match(sequence, &policies, &self.options)
14776                    {
14777                        return Poll::Ready(Err(error));
14778                    }
14779                    if let Err(error) =
14780                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14781                    {
14782                        return Poll::Ready(Err(error));
14783                    }
14784                    match state.prepare_scalar_cancellation(
14785                        cursor,
14786                        CancellationCallKind::Child,
14787                        &self.parallel_group_path,
14788                    ) {
14789                        Ok(true) => {
14790                            self.scheduled = true;
14791                            self.matched_pending = true;
14792                            return Poll::Pending;
14793                        }
14794                        Ok(false) => {}
14795                        Err(error) => return Poll::Ready(Err(error)),
14796                    }
14797                    state.command_cursor += 1;
14798                    if let Some(outcome) = outcome {
14799                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14800                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14801                    }
14802                    state.matched_recorded_pending = true;
14803                    self.scheduled = true;
14804                    self.matched_pending = true;
14805                    return Poll::Pending;
14806                }
14807                other => {
14808                    return Poll::Ready(Err(command_mismatch(
14809                        &other,
14810                        format!("child workflow:{}", self.workflow_type),
14811                    )));
14812                }
14813            }
14814        }
14815
14816        if !self.scheduled {
14817            if self.options.task_queue.trim().is_empty() {
14818                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14819                    "task_queue must not be empty".to_string(),
14820                )));
14821            }
14822            for (name, value) in [
14823                (
14824                    "execution_timeout_seconds",
14825                    self.options.execution_timeout_seconds,
14826                ),
14827                ("run_timeout_seconds", self.options.run_timeout_seconds),
14828            ] {
14829                if value == Some(0) {
14830                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14831                        "{name} must be at least 1"
14832                    ))));
14833                }
14834            }
14835
14836            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14837                Ok(args) => args,
14838                Err(error) => return Poll::Ready(Err(error)),
14839            };
14840            let arguments = match encode_typed_envelope(
14841                &normalize_avro_arguments(args),
14842                &state.payload_codec,
14843            ) {
14844                Ok(arguments) => arguments,
14845                Err(error) => return Poll::Ready(Err(error)),
14846            };
14847            let mut command = json!({
14848                "type": "start_child_workflow",
14849                "workflow_type": self.workflow_type,
14850                "queue": self.options.task_queue,
14851                "parent_close_policy": self.options.parent_close_policy.as_str(),
14852                "arguments": arguments,
14853            });
14854            let object = command
14855                .as_object_mut()
14856                .expect("child workflow command is always an object");
14857            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14858                object.insert(
14859                    "cancellation_policy".to_string(),
14860                    json!(self.options.cancellation_policy.as_str()),
14861                );
14862            }
14863            if let Some(policy) = &self.options.retry_policy {
14864                let mut retry_policy = serde_json::Map::new();
14865                if let Some(max_attempts) = policy.max_attempts {
14866                    if max_attempts == 0 {
14867                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14868                            "retry_policy.max_attempts must be at least 1".to_string(),
14869                        )));
14870                    }
14871                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14872                }
14873                if !policy.backoff_seconds.is_empty() {
14874                    retry_policy
14875                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14876                }
14877                if !policy.non_retryable_error_types.is_empty() {
14878                    retry_policy.insert(
14879                        "non_retryable_error_types".to_string(),
14880                        json!(policy.non_retryable_error_types),
14881                    );
14882                }
14883                if retry_policy.is_empty() {
14884                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14885                        "retry_policy must configure at least one field".to_string(),
14886                    )));
14887                }
14888                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14889            }
14890            if let Some(seconds) = self.options.execution_timeout_seconds {
14891                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14892            }
14893            if let Some(seconds) = self.options.run_timeout_seconds {
14894                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14895            }
14896            apply_parallel_group_path(object, &self.parallel_group_path);
14897            ctx.apply_scope_membership(object);
14898            match state.prepare_scalar_cancellation(
14899                cursor,
14900                CancellationCallKind::Child,
14901                &self.parallel_group_path,
14902            ) {
14903                Ok(true) => {
14904                    self.scheduled = true;
14905                    self.matched_pending = true;
14906                    return Poll::Pending;
14907                }
14908                Ok(false) => {}
14909                Err(error) => return Poll::Ready(Err(error)),
14910            }
14911            state.commands.push(command);
14912            self.scheduled = true;
14913        }
14914
14915        Poll::Pending
14916    }
14917}
14918
14919impl Future for ChildWorkflowCall {
14920    type Output = Result<ChildWorkflowResult>;
14921
14922    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14923        match self.poll_avro_value(cx) {
14924            Poll::Ready(Ok(result)) => match result.result.into_json() {
14925                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14926                    parent: result.parent,
14927                    child: result.child,
14928                    child_workflow_type: result.child_workflow_type,
14929                    result: projected,
14930                })),
14931                Err(error) => Poll::Ready(Err(error)),
14932            },
14933            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14934            Poll::Pending => Poll::Pending,
14935        }
14936    }
14937}
14938
14939fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14940    Error::NonDeterministicReplay(ReplayFailure::new(
14941        "recorded_command_mismatch",
14942        Some(recorded.sequence()),
14943        Some(recorded.shape().to_string()),
14944        Some(actual.into()),
14945        "current workflow command does not match the recorded durable command sequence",
14946    ))
14947}
14948
14949pub struct SignalCall {
14950    ctx: WorkflowContext,
14951    signal_name: String,
14952    runtime_reserved_allowed: bool,
14953    opened_wait: bool,
14954    matched_pending: bool,
14955    parallel_group_path: Vec<ParallelGroupMetadata>,
14956}
14957
14958impl SignalCall {
14959    fn poll_avro_value(
14960        mut self: Pin<&mut Self>,
14961        _cx: &mut TaskContext<'_>,
14962    ) -> Poll<Result<Vec<AvroValue>>> {
14963        if self.matched_pending {
14964            return Poll::Pending;
14965        }
14966        if !self.runtime_reserved_allowed {
14967            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14968                return Poll::Ready(Err(error));
14969            }
14970        }
14971
14972        let ctx = self.ctx.clone();
14973        let mut state = match ctx.state.lock() {
14974            Ok(state) => state,
14975            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14976        };
14977
14978        let cursor = state.command_cursor;
14979        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14980            return Poll::Ready(Err(error));
14981        }
14982        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14983        {
14984            Ok(recorded) => recorded,
14985            Err(error) => return Poll::Ready(Err(error)),
14986        };
14987        if let Some(recorded) = recorded {
14988            match recorded {
14989                RecordedCommand::SignalWait {
14990                    sequence,
14991                    signal_name,
14992                    value,
14993                    parallel_group_path,
14994                } => {
14995                    if let Err(error) = ensure_parallel_path_matches(
14996                        sequence,
14997                        parallel_group_path.as_deref(),
14998                        &self.parallel_group_path,
14999                    ) {
15000                        return Poll::Ready(Err(error));
15001                    }
15002                    if signal_name != self.signal_name {
15003                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15004                            ReplayFailure::new(
15005                                "recorded_command_detail_mismatch",
15006                                Some(sequence),
15007                                Some(format!("signal wait:{signal_name}")),
15008                                Some(format!("signal wait:{}", self.signal_name)),
15009                                "recorded signal name differs from the current workflow command",
15010                            ),
15011                        )));
15012                    }
15013
15014                    if let Err(error) =
15015                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
15016                    {
15017                        return Poll::Ready(Err(error));
15018                    }
15019                    match state.prepare_scalar_cancellation(
15020                        cursor,
15021                        CancellationCallKind::Signal,
15022                        &self.parallel_group_path,
15023                    ) {
15024                        Ok(true) => {
15025                            self.opened_wait = true;
15026                            self.matched_pending = true;
15027                            return Poll::Pending;
15028                        }
15029                        Ok(false) => {}
15030                        Err(error) => return Poll::Ready(Err(error)),
15031                    }
15032                    state.command_cursor += 1;
15033                    if let Some(value) = value {
15034                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15035                        return Poll::Ready(Ok(value));
15036                    }
15037                    if state
15038                        .resume_signal
15039                        .as_ref()
15040                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15041                    {
15042                        let signal = state
15043                            .resume_signal
15044                            .take()
15045                            .expect("matching resume signal is present");
15046                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15047                        return Poll::Ready(Ok(signal.arguments));
15048                    }
15049
15050                    state.matched_recorded_pending = true;
15051                    self.opened_wait = true;
15052                    self.matched_pending = true;
15053                    return Poll::Pending;
15054                }
15055                other => {
15056                    return Poll::Ready(Err(command_mismatch(
15057                        &other,
15058                        format!("signal wait:{}", self.signal_name),
15059                    )));
15060                }
15061            }
15062        }
15063
15064        match state.prepare_scalar_cancellation(
15065            cursor,
15066            CancellationCallKind::Signal,
15067            &self.parallel_group_path,
15068        ) {
15069            Ok(true) => {
15070                self.opened_wait = true;
15071                self.matched_pending = true;
15072                return Poll::Pending;
15073            }
15074            Ok(false) => {}
15075            Err(error) => return Poll::Ready(Err(error)),
15076        }
15077
15078        if state
15079            .resume_signal
15080            .as_ref()
15081            .is_some_and(|signal| signal.signal_name == self.signal_name)
15082        {
15083            let signal = state
15084                .resume_signal
15085                .take()
15086                .expect("matching resume signal is present");
15087            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15088            return Poll::Ready(Ok(signal.arguments));
15089        }
15090
15091        if !self.opened_wait {
15092            let mut command = serde_json::Map::from_iter([
15093                ("type".to_string(), json!("open_signal_wait")),
15094                ("signal_name".to_string(), json!(self.signal_name)),
15095            ]);
15096            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15097            ctx.apply_scope_membership(&mut command);
15098            state.commands.push(Value::Object(command));
15099            self.opened_wait = true;
15100        }
15101
15102        Poll::Pending
15103    }
15104}
15105
15106impl Future for SignalCall {
15107    type Output = Result<Vec<Value>>;
15108
15109    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15110        match self.poll_avro_value(cx) {
15111            Poll::Ready(Ok(values)) => Poll::Ready(
15112                values
15113                    .into_iter()
15114                    .map(AvroValue::into_json)
15115                    .collect::<Result<Vec<_>>>(),
15116            ),
15117            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15118            Poll::Pending => Poll::Pending,
15119        }
15120    }
15121}
15122
15123#[derive(Clone, Debug)]
15124pub struct ActivityContext {
15125    client: Client,
15126    pub task_id: String,
15127    pub activity_attempt_id: String,
15128    pub lease_owner: String,
15129    pub activity_type: String,
15130    pub attempt_number: u64,
15131    pub task_queue: String,
15132    pub worker_id: String,
15133    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15134    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15135    worker_session: Option<WorkerSession>,
15136}
15137
15138impl ActivityContext {
15139    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15140        if let Some(heartbeats) = &self.local_heartbeats {
15141            return heartbeats
15142                .lock()
15143                .map_err(|_| Error::WorkflowStatePoisoned)?
15144                .record(details);
15145        }
15146        if let Some(guard) = &self.claim_guard {
15147            return guard.heartbeat(self, details).await;
15148        }
15149        if let Some(session) = &self.worker_session {
15150            if !session.active() {
15151                return Err(Error::ActivityExecutionAbandoned(
15152                    "worker-session lease or TTL is no longer active".into(),
15153                ));
15154            }
15155            let result = self
15156                .client
15157                .heartbeat_activity_task_value(
15158                    &self.task_id,
15159                    &self.activity_attempt_id,
15160                    &self.lease_owner,
15161                    details,
15162                )
15163                .await;
15164            return worker_session::settle_activity_heartbeat(
15165                session,
15166                result,
15167                &self.task_id,
15168                &self.activity_attempt_id,
15169                &self.lease_owner,
15170            );
15171        }
15172        self.client
15173            .heartbeat_activity_task(
15174                &self.task_id,
15175                &self.activity_attempt_id,
15176                &self.lease_owner,
15177                details,
15178            )
15179            .await
15180    }
15181}
15182
15183fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15184    validate_payload_codec(codec)?;
15185    match value {
15186        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15187            value, codec,
15188        )?)),
15189        None => Ok(AvroValue::Array(Vec::new())),
15190    }
15191}
15192
15193fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15194    let Some(signal_name) = task
15195        .signal_name
15196        .as_deref()
15197        .filter(|value| !value.is_empty())
15198    else {
15199        return Ok(None);
15200    };
15201    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15202    let AvroValue::Array(arguments) = decoded else {
15203        unreachable!("normalize_avro_arguments always returns an array");
15204    };
15205
15206    Ok(Some(ResumeSignal {
15207        signal_name: signal_name.to_string(),
15208        arguments,
15209    }))
15210}
15211
15212fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15213    validate_payload_codec(&task.payload_codec)?;
15214    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15215    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15216    for event in &task.history_events {
15217        validate_history_event_payloads(event, &task.payload_codec)?;
15218    }
15219    Ok(())
15220}
15221
15222fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15223    validate_payload_codec(&task.payload_codec)?;
15224    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15225}
15226
15227fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15228    validate_payload_codec(&task.payload_codec)?;
15229    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15230    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15231    for event in &task.history_events {
15232        validate_history_event_payloads(event, &task.payload_codec)?;
15233    }
15234
15235    let Some(export) = task.history_export.as_ref() else {
15236        return Ok(());
15237    };
15238    let export_codec = match export.get("payloads") {
15239        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15240        None => None,
15241    }
15242    .unwrap_or(&task.payload_codec);
15243    validate_payload_codec(export_codec)?;
15244
15245    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15246        for event in events {
15247            let event_type = event
15248                .get("event_type")
15249                .or_else(|| event.get("type"))
15250                .and_then(Value::as_str)
15251                .unwrap_or_default();
15252            if let Some(payload) = event.get("payload") {
15253                validate_history_payloads(event_type, payload, export_codec)?;
15254            }
15255        }
15256    }
15257    for signal in export
15258        .get("signals")
15259        .and_then(Value::as_array)
15260        .into_iter()
15261        .flatten()
15262    {
15263        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15264        validate_payload_codec(codec)?;
15265        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15266    }
15267    for activity in export
15268        .get("activities")
15269        .and_then(Value::as_array)
15270        .into_iter()
15271        .flatten()
15272    {
15273        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15274        validate_payload_codec(codec)?;
15275        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15276        validate_optional_inbound_payload(activity.get("result"), codec)?;
15277    }
15278    Ok(())
15279}
15280
15281fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15282    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15283}
15284
15285fn validate_history_payloads(
15286    event_type: &str,
15287    payload: &Value,
15288    fallback_codec: &str,
15289) -> Result<()> {
15290    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15291    validate_payload_codec(codec)?;
15292    for field in history_payload_fields(event_type) {
15293        validate_optional_inbound_payload(payload.get(*field), codec)?;
15294    }
15295    Ok(())
15296}
15297
15298const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15299
15300fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15301    match event_type {
15302        "ActivityCompleted" => &["result"],
15303        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15304        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15305        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15306        "ChildRunCompleted" => &["result", "output"],
15307        "WorkflowCompleted" => &["output"],
15308        "ServiceCallStarted"
15309        | "ServiceCallCompleted"
15310        | "ServiceCallFailed"
15311        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15312        _ => &[],
15313    }
15314}
15315
15316fn signal_history_payload(payload: &Value) -> Option<&Value> {
15317    SIGNAL_HISTORY_PAYLOAD_FIELDS
15318        .iter()
15319        .find_map(|field| payload.get(*field))
15320}
15321
15322fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15323    match value.get(field) {
15324        None => Ok(None),
15325        Some(Value::String(codec)) => Ok(Some(codec)),
15326        Some(_) => Err(invalid_payload_envelope()),
15327    }
15328}
15329
15330fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15331    validate_payload_codec(codec)?;
15332    if let Some(value) = value.filter(|value| !value.is_null()) {
15333        decode_wire_avro_value(value, codec)?;
15334    }
15335    Ok(())
15336}
15337
15338fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15339    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15340        invalid_recorded_history(
15341            "parallel_group_metadata_invalid",
15342            sequence,
15343            "non-empty parallel_group_id",
15344            &payload.to_string(),
15345            "parallel-group history is missing its stable identity",
15346        )
15347    })?;
15348    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15349        invalid_recorded_history(
15350            "parallel_group_metadata_invalid",
15351            sequence,
15352            "activity, child, timer, signal, condition, or mixed group kind",
15353            &payload.to_string(),
15354            "parallel-group history is missing its group kind",
15355        )
15356    })?;
15357    if !matches!(
15358        kind.as_str(),
15359        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15360    ) {
15361        return Err(invalid_recorded_history(
15362            "parallel_group_metadata_invalid",
15363            sequence,
15364            "activity, child, timer, signal, condition, or mixed group kind",
15365            &kind,
15366            "parallel-group history contains an unsupported group kind",
15367        ));
15368    }
15369    let base_sequence = payload
15370        .get("parallel_group_base_sequence")
15371        .and_then(value_as_u64)
15372        .filter(|value| *value > 0)
15373        .ok_or_else(|| {
15374            invalid_recorded_history(
15375                "parallel_group_metadata_invalid",
15376                sequence,
15377                "positive parallel_group_base_sequence",
15378                &payload.to_string(),
15379                "parallel-group history contains an invalid base sequence",
15380            )
15381        })?;
15382    let size = payload
15383        .get("parallel_group_size")
15384        .and_then(value_as_u64)
15385        .and_then(|value| usize::try_from(value).ok())
15386        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15387        .ok_or_else(|| {
15388            invalid_recorded_history(
15389                "parallel_group_metadata_invalid",
15390                sequence,
15391                "bounded positive parallel_group_size",
15392                &payload.to_string(),
15393                "parallel-group history contains an invalid group size",
15394            )
15395        })?;
15396    let index = payload
15397        .get("parallel_group_index")
15398        .and_then(value_as_u64)
15399        .and_then(|value| usize::try_from(value).ok())
15400        .filter(|value| *value < size)
15401        .ok_or_else(|| {
15402            invalid_recorded_history(
15403                "parallel_group_metadata_invalid",
15404                sequence,
15405                "parallel_group_index within group bounds",
15406                &payload.to_string(),
15407                "parallel-group history contains an invalid member index",
15408            )
15409        })?;
15410    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15411        return Err(invalid_recorded_history(
15412            "parallel_group_metadata_invalid",
15413            sequence,
15414            "base sequence plus member index equals workflow sequence",
15415            &payload.to_string(),
15416            "parallel-group path does not preserve durable workflow position",
15417        ));
15418    }
15419    let mode = payload
15420        .get("parallel_group_mode")
15421        .and_then(Value::as_str)
15422        .unwrap_or("all");
15423    if !matches!(mode, "all" | "select") {
15424        return Err(invalid_recorded_history(
15425            "parallel_group_metadata_invalid",
15426            sequence,
15427            "parallel group mode all or select",
15428            mode,
15429            "parallel-group history contains an unsupported group mode",
15430        ));
15431    }
15432    let expected_id = if mode == "select" {
15433        format!("select-calls:{base_sequence}:{size}")
15434    } else {
15435        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15436    };
15437    if group_id != expected_id {
15438        return Err(invalid_recorded_history(
15439            "parallel_group_metadata_invalid",
15440            sequence,
15441            &expected_id,
15442            &group_id,
15443            "parallel-group history contains an incompatible stable group ID",
15444        ));
15445    }
15446    let selection_member_key = if mode == "select" {
15447        Some(selection_key_from_value(
15448            payload.get("selection_member_key"),
15449            sequence,
15450        )?)
15451    } else {
15452        None
15453    };
15454    let selection_member_index = if mode == "select" {
15455        Some(required_parallel_usize(
15456            payload,
15457            "selection_member_index",
15458            sequence,
15459        )?)
15460    } else {
15461        None
15462    };
15463    let selection_member_base_sequence = if mode == "select" {
15464        Some(
15465            payload
15466                .get("selection_member_base_sequence")
15467                .and_then(value_as_u64)
15468                .filter(|value| *value >= base_sequence)
15469                .ok_or_else(|| {
15470                    invalid_recorded_history(
15471                        "parallel_group_metadata_invalid",
15472                        sequence,
15473                        "selection member base within its group",
15474                        &payload.to_string(),
15475                        "selection history contains an invalid member base sequence",
15476                    )
15477                })?,
15478        )
15479    } else {
15480        None
15481    };
15482    let selection_member_size = if mode == "select" {
15483        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15484        if member_size == 0 {
15485            return Err(invalid_recorded_history(
15486                "parallel_group_metadata_invalid",
15487                sequence,
15488                "positive selection member size",
15489                &payload.to_string(),
15490                "selection history contains an invalid member size",
15491            ));
15492        }
15493        Some(member_size)
15494    } else {
15495        None
15496    };
15497    let selection_member_kind = if mode == "select" {
15498        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15499            invalid_recorded_history(
15500                "parallel_group_metadata_invalid",
15501                sequence,
15502                "selection member operation kind",
15503                &payload.to_string(),
15504                "selection history is missing its authored member kind",
15505            )
15506        })?;
15507        if !matches!(
15508            kind.as_str(),
15509            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15510        ) {
15511            return Err(invalid_recorded_history(
15512                "parallel_group_metadata_invalid",
15513                sequence,
15514                "activity, child, timer, signal, condition, or group selection member kind",
15515                &kind,
15516                "selection history contains an unsupported member kind",
15517            ));
15518        }
15519        Some(kind)
15520    } else {
15521        None
15522    };
15523    if let (Some(member_base), Some(member_size)) =
15524        (selection_member_base_sequence, selection_member_size)
15525    {
15526        let member_end = member_base
15527            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15528            .ok_or_else(|| {
15529                invalid_recorded_history(
15530                    "parallel_group_metadata_invalid",
15531                    sequence,
15532                    "bounded selection member range",
15533                    &payload.to_string(),
15534                    "selection member range overflowed",
15535                )
15536            })?;
15537        let group_end = base_sequence
15538            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15539            .unwrap_or(u64::MAX);
15540        if sequence < member_base || sequence >= member_end || member_end > group_end {
15541            return Err(invalid_recorded_history(
15542                "parallel_group_metadata_invalid",
15543                sequence,
15544                "workflow sequence within one bounded selection member",
15545                &payload.to_string(),
15546                "selection member range does not contain its durable leaf",
15547            ));
15548        }
15549    }
15550    Ok(ParallelGroupMetadata {
15551        parallel_group_id: group_id,
15552        parallel_group_kind: kind,
15553        parallel_group_base_sequence: base_sequence,
15554        parallel_group_size: size,
15555        parallel_group_index: index,
15556        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15557        selection_member_key,
15558        selection_member_index,
15559        selection_member_base_sequence,
15560        selection_member_size,
15561        selection_member_kind,
15562    })
15563}
15564
15565fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15566    payload
15567        .get(field)
15568        .and_then(value_as_u64)
15569        .and_then(|value| usize::try_from(value).ok())
15570        .ok_or_else(|| {
15571            invalid_recorded_history(
15572                "parallel_group_metadata_invalid",
15573                sequence,
15574                &format!("non-negative integer {field}"),
15575                &payload.to_string(),
15576                "selection history contains invalid member metadata",
15577            )
15578        })
15579}
15580
15581fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15582    match value {
15583        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15584        Some(value) => value_as_u64(value)
15585            .and_then(|value| usize::try_from(value).ok())
15586            .map(SelectionKey::Index)
15587            .ok_or_else(|| {
15588                invalid_recorded_history(
15589                    "selection_member_key_invalid",
15590                    sequence,
15591                    "non-empty string or non-negative integer member key",
15592                    &value.to_string(),
15593                    "selection history contains an invalid member key",
15594                )
15595            }),
15596        None => Err(invalid_recorded_history(
15597            "selection_member_key_missing",
15598            sequence,
15599            "selection_member_key",
15600            "<missing>",
15601            "selection history is missing its stable member key",
15602        )),
15603    }
15604}
15605
15606fn recorded_parallel_group_path(
15607    events: &[&HistoryEvent],
15608    sequence: u64,
15609) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15610    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15611    for event in events {
15612        let payload = &event.payload;
15613        let has_metadata = payload.get("parallel_group_path").is_some()
15614            || payload.get("parallel_group_id").is_some()
15615            || payload.get("parallel_group_kind").is_some()
15616            || payload.get("parallel_group_base_sequence").is_some()
15617            || payload.get("parallel_group_size").is_some()
15618            || payload.get("parallel_group_index").is_some()
15619            || payload.get("parallel_group_mode").is_some()
15620            || payload.get("selection_member_key").is_some();
15621        if !has_metadata {
15622            continue;
15623        }
15624
15625        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15626        let path = match payload.get("parallel_group_path") {
15627            None => vec![top_level.clone()],
15628            Some(Value::Array(entries)) if !entries.is_empty() => entries
15629                .iter()
15630                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15631                .collect::<Result<Vec<_>>>()?,
15632            Some(value) => {
15633                return Err(invalid_recorded_history(
15634                    "parallel_group_metadata_invalid",
15635                    sequence,
15636                    "non-empty parallel_group_path list",
15637                    &value.to_string(),
15638                    "parallel-group history contains an invalid group path",
15639                ));
15640            }
15641        };
15642        if path.last() != Some(&top_level) {
15643            return Err(invalid_recorded_history(
15644                "parallel_group_metadata_invalid",
15645                sequence,
15646                &serde_json::to_string(&path.last()).unwrap_or_default(),
15647                &serde_json::to_string(&top_level).unwrap_or_default(),
15648                "parallel-group top-level fields do not match the innermost path entry",
15649            ));
15650        }
15651        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15652            return Err(invalid_recorded_history(
15653                "parallel_group_history_conflict",
15654                sequence,
15655                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15656                &serde_json::to_string(&path).unwrap_or_default(),
15657                "parallel-group metadata changed between scheduling and resolution history",
15658            ));
15659        }
15660        recorded = Some(path);
15661    }
15662    Ok(recorded)
15663}
15664
15665fn recorded_commands(
15666    events: &[HistoryEvent],
15667    fallback_codec: &str,
15668    parent: WorkflowIdentity,
15669) -> Result<Vec<RecordedCommand>> {
15670    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15671    let mut last_new_sequence = None;
15672
15673    for event in events {
15674        let is_activity = matches!(
15675            event.event_type.as_str(),
15676            "ActivityScheduled"
15677                | "ActivityStarted"
15678                | "ActivityHeartbeatRecorded"
15679                | "ActivityRetryScheduled"
15680                | "ActivityCompleted"
15681                | "ActivityFailed"
15682                | "ActivityCancelled"
15683                | "ActivityTimedOut"
15684        );
15685        let is_workflow_timer = matches!(
15686            event.event_type.as_str(),
15687            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15688        ) && !is_internal_timer_event(event);
15689        let is_child_workflow = matches!(
15690            event.event_type.as_str(),
15691            "ChildWorkflowScheduled"
15692                | "ChildRunStarted"
15693                | "ChildRunCompleted"
15694                | "ChildRunFailed"
15695                | "ChildRunCancelled"
15696                | "ChildRunTerminated"
15697        );
15698        let is_signal_wait = is_recorded_signal_wait_event(event);
15699        let is_condition_wait = is_recorded_condition_wait_event(event);
15700        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15701        let is_side_effect = event.event_type == "SideEffectRecorded";
15702        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15703        let is_memo = event.event_type == "MemoUpserted";
15704        if !is_activity
15705            && !is_workflow_timer
15706            && !is_child_workflow
15707            && !is_signal_wait
15708            && !is_condition_wait
15709            && !is_search_attributes
15710            && !is_side_effect
15711            && !is_version_marker
15712            && !is_memo
15713        {
15714            continue;
15715        }
15716
15717        let sequence = durable_event_sequence(event).ok_or_else(|| {
15718            Error::NonDeterministicReplay(ReplayFailure::new(
15719                "durable_command_sequence_missing",
15720                None,
15721                Some("positive workflow sequence".to_string()),
15722                Some(event.event_type.clone()),
15723                "durable command history event has no workflow sequence",
15724            ))
15725        })?;
15726        if sequence == 0 {
15727            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15728                "durable_command_sequence_invalid",
15729                Some(sequence),
15730                Some("positive workflow sequence".to_string()),
15731                Some(sequence.to_string()),
15732                "durable command history uses an invalid workflow sequence",
15733            )));
15734        }
15735        if !events_by_sequence.contains_key(&sequence) {
15736            if let Some(previous) = last_new_sequence {
15737                if sequence < previous {
15738                    return Err(invalid_recorded_history(
15739                        "durable_command_sequence_mismatch",
15740                        sequence,
15741                        &format!("workflow sequence greater than {previous}"),
15742                        &sequence.to_string(),
15743                        "durable commands are not strictly ordered by their recorded workflow sequence",
15744                    ));
15745                }
15746            }
15747            last_new_sequence = Some(sequence);
15748        }
15749        events_by_sequence.entry(sequence).or_default().push(event);
15750    }
15751
15752    let commands: Vec<RecordedCommand> = events_by_sequence
15753        .into_iter()
15754        .map(|(sequence, sequence_events)| {
15755            let activity_events: Vec<_> = sequence_events
15756                .iter()
15757                .copied()
15758                .filter(|event| event.event_type.starts_with("Activity"))
15759                .collect();
15760            let timer_events: Vec<_> = sequence_events
15761                .iter()
15762                .copied()
15763                .filter(|event| event.event_type.starts_with("Timer"))
15764                .collect();
15765            let child_events: Vec<_> = sequence_events
15766                .iter()
15767                .copied()
15768                .filter(|event| {
15769                    event.event_type == "ChildWorkflowScheduled"
15770                        || event.event_type.starts_with("ChildRun")
15771                })
15772                .collect();
15773            let signal_wait_events: Vec<_> = sequence_events
15774                .iter()
15775                .copied()
15776                .filter(|event| is_recorded_signal_wait_event(event))
15777                .collect();
15778            let condition_wait_events: Vec<_> = sequence_events
15779                .iter()
15780                .copied()
15781                .filter(|event| is_recorded_condition_wait_event(event))
15782                .collect();
15783            let search_attribute_events: Vec<_> = sequence_events
15784                .iter()
15785                .copied()
15786                .filter(|event| event.event_type == "SearchAttributesUpserted")
15787                .collect();
15788            let side_effect_events: Vec<_> = sequence_events
15789                .iter()
15790                .copied()
15791                .filter(|event| event.event_type == "SideEffectRecorded")
15792                .collect();
15793            let version_marker_events: Vec<_> = sequence_events
15794                .iter()
15795                .copied()
15796                .filter(|event| event.event_type == "VersionMarkerRecorded")
15797                .collect();
15798            let memo_events: Vec<_> = sequence_events
15799                .iter()
15800                .copied()
15801                .filter(|event| event.event_type == "MemoUpserted")
15802                .collect();
15803
15804            let command_kind_count = usize::from(!activity_events.is_empty())
15805                + usize::from(!timer_events.is_empty())
15806                + usize::from(!child_events.is_empty())
15807                + usize::from(!signal_wait_events.is_empty())
15808                + usize::from(!condition_wait_events.is_empty())
15809                + usize::from(!search_attribute_events.is_empty())
15810                + usize::from(!side_effect_events.is_empty())
15811                + usize::from(!version_marker_events.is_empty())
15812                + usize::from(!memo_events.is_empty());
15813            if command_kind_count > 1 {
15814                let actual = [
15815                    (!activity_events.is_empty()).then_some("activity"),
15816                    (!timer_events.is_empty()).then_some("timer"),
15817                    (!child_events.is_empty()).then_some("child workflow"),
15818                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15819                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15820                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15821                    (!side_effect_events.is_empty()).then_some("side effect"),
15822                    (!version_marker_events.is_empty()).then_some("version marker"),
15823                    (!memo_events.is_empty()).then_some("memo upsert"),
15824                ]
15825                .into_iter()
15826                .flatten()
15827                .collect::<Vec<_>>()
15828                .join(" and ");
15829                return Err(invalid_recorded_history(
15830                    "durable_command_sequence_collision",
15831                    sequence,
15832                    "one durable command kind",
15833                    &actual,
15834                    "one workflow sequence records more than one durable command kind",
15835                ));
15836            }
15837
15838            if !activity_events.is_empty() {
15839                let parallel_group_path =
15840                    recorded_parallel_group_path(&activity_events, sequence)?;
15841                let scheduled_count = activity_events
15842                    .iter()
15843                    .filter(|event| event.event_type == "ActivityScheduled")
15844                    .count();
15845                if scheduled_count > 1 {
15846                    return Err(invalid_recorded_history(
15847                        "duplicate_activity_schedule",
15848                        sequence,
15849                        "at most one ActivityScheduled event",
15850                        "multiple ActivityScheduled events",
15851                        "activity history schedules more than one command at one workflow sequence",
15852                    ));
15853                }
15854                let activity_type = activity_events.iter().find_map(|event| {
15855                    event
15856                        .payload
15857                        .get("activity_type")
15858                        .or_else(|| event.payload.get("activity_name"))
15859                        .and_then(Value::as_str)
15860                        .map(str::to_string)
15861                });
15862                if activity_events.iter().filter_map(|event| {
15863                    event
15864                        .payload
15865                        .get("activity_type")
15866                        .or_else(|| event.payload.get("activity_name"))
15867                        .and_then(Value::as_str)
15868                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15869                    return Err(invalid_recorded_history(
15870                        "activity_identity_mismatch",
15871                        sequence,
15872                        activity_type.as_deref().unwrap_or("one activity identity"),
15873                        "conflicting activity identities",
15874                        "activity lifecycle events at one workflow sequence disagree on identity",
15875                    ));
15876                }
15877                let terminal: Vec<_> = activity_events
15878                    .iter()
15879                    .copied()
15880                    .filter(|event| {
15881                        matches!(
15882                            event.event_type.as_str(),
15883                            "ActivityCompleted"
15884                                | "ActivityFailed"
15885                                | "ActivityCancelled"
15886                                | "ActivityTimedOut"
15887                        )
15888                    })
15889                    .collect();
15890                let duplicate_delivery = terminal.first().is_some_and(|first| {
15891                    terminal.iter().all(|event| {
15892                        event.event_type == first.event_type && event.payload == first.payload
15893                    })
15894                });
15895                if terminal.len() > 1 && !duplicate_delivery {
15896                    return Err(invalid_recorded_history(
15897                        "duplicate_activity_terminal_event",
15898                        sequence,
15899                        "at most one terminal activity event",
15900                        "multiple terminal activity events",
15901                        "activity history settles one command more than once",
15902                    ));
15903                }
15904                let outcome = terminal
15905                    .first()
15906                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15907                    .transpose()?;
15908                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15909                let activity_snapshot = activity_events
15910                    .iter()
15911                    .find(|event| event.event_type == "ActivityScheduled")
15912                    .and_then(|event| event.payload.get("activity"))
15913                    .and_then(Value::as_object);
15914                let options = Some(match activity_snapshot {
15915                    Some(activity) => RecordedActivityOptions {
15916                        task_queue: recorded_optional_string(activity, "queue"),
15917                        execution_mode,
15918                        retry_policy: recorded_activity_retry_snapshot(
15919                            activity.get("retry_policy"),
15920                        ),
15921                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15922                    },
15923                    None => RecordedActivityOptions {
15924                        task_queue: RecordedSnapshotValue::Unknown,
15925                        execution_mode,
15926                        retry_policy: recorded_activity_retry_snapshot(None),
15927                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15928                    },
15929                });
15930                return Ok(RecordedCommand::Activity {
15931                    sequence,
15932                    activity_type,
15933                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15934                    options,
15935                    outcome,
15936                    parallel_group_path,
15937                });
15938            }
15939
15940            if !child_events.is_empty() {
15941                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15942                let scheduled: Vec<_> = child_events
15943                    .iter()
15944                    .copied()
15945                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15946                    .collect();
15947                if scheduled.len() != 1 {
15948                    return Err(invalid_recorded_history(
15949                        "child_workflow_schedule_missing_or_duplicate",
15950                        sequence,
15951                        "one ChildWorkflowScheduled event",
15952                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15953                        "child workflow replay requires exactly one recorded schedule event",
15954                    ));
15955                }
15956                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15957                let workflow_type = child_events.iter().find_map(|event| {
15958                    event
15959                        .payload
15960                        .get("child_workflow_type")
15961                        .or_else(|| event.payload.get("workflow_type"))
15962                        .and_then(Value::as_str)
15963                        .filter(|value| !value.is_empty())
15964                        .map(str::to_string)
15965                });
15966                if child_events
15967                    .iter()
15968                    .filter_map(|event| {
15969                        event
15970                            .payload
15971                            .get("child_workflow_type")
15972                            .or_else(|| event.payload.get("workflow_type"))
15973                            .and_then(Value::as_str)
15974                    })
15975                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15976                {
15977                    return Err(invalid_recorded_history(
15978                        "child_workflow_identity_mismatch",
15979                        sequence,
15980                        workflow_type
15981                            .as_deref()
15982                            .unwrap_or("one child workflow type"),
15983                        "conflicting child workflow types",
15984                        "child workflow lifecycle events at one sequence disagree on type",
15985                    ));
15986                }
15987                let mut outcomes = child_workflow_outcomes(
15988                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15989                    fallback_codec,
15990                    parent.clone(),
15991                )?;
15992                let terminal_events = child_events
15993                    .iter()
15994                    .copied()
15995                    .filter(|event| event.event_type.starts_with("ChildRun"))
15996                    .collect::<Vec<_>>();
15997                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
15998                    terminal_events.iter().all(|event| {
15999                        event.event_type == first.event_type && event.payload == first.payload
16000                    })
16001                });
16002                if outcomes.len() > 1 && !duplicate_delivery {
16003                    return Err(invalid_recorded_history(
16004                        "duplicate_child_workflow_terminal_event",
16005                        sequence,
16006                        "at most one terminal child event",
16007                        "multiple terminal child events",
16008                        "child workflow history settles one command more than once",
16009                    ));
16010                }
16011                return Ok(RecordedCommand::ChildWorkflow {
16012                    sequence,
16013                    workflow_type,
16014                    policies,
16015                    outcome: outcomes.pop(),
16016                    parallel_group_path,
16017                });
16018            }
16019
16020            if !signal_wait_events.is_empty() {
16021                let opened: Vec<_> = signal_wait_events
16022                    .iter()
16023                    .copied()
16024                    .filter(|event| event.event_type == "SignalWaitOpened")
16025                    .collect();
16026                if opened.len() != 1 {
16027                    return Err(invalid_recorded_history(
16028                        "signal_wait_open_missing_or_duplicate",
16029                        sequence,
16030                        "one SignalWaitOpened event",
16031                        &format!("{} SignalWaitOpened events", opened.len()),
16032                        "signal replay requires exactly one canonical wait-open event",
16033                    ));
16034                }
16035
16036                let applied: Vec<_> = signal_wait_events
16037                    .iter()
16038                    .copied()
16039                    .filter(|event| event.event_type == "SignalApplied")
16040                    .collect();
16041                if applied.len() > 1 {
16042                    return Err(invalid_recorded_history(
16043                        "duplicate_signal_wait_apply",
16044                        sequence,
16045                        "at most one SignalApplied event",
16046                        "multiple SignalApplied events",
16047                        "signal history applies one durable wait more than once",
16048                    ));
16049                }
16050
16051                let signal_names = signal_wait_events
16052                    .iter()
16053                    .map(|event| required_signal_wait_name(event, sequence))
16054                    .collect::<Result<Vec<_>>>()?;
16055                let signal_name = signal_names
16056                    .first()
16057                    .expect("signal wait events are not empty")
16058                    .clone();
16059                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16060                    return Err(invalid_recorded_history(
16061                        "signal_wait_identity_mismatch",
16062                        sequence,
16063                        &signal_name,
16064                        "conflicting signal names",
16065                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16066                    ));
16067                }
16068                let value = applied
16069                    .first()
16070                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16071                    .transpose()?;
16072                return Ok(RecordedCommand::SignalWait {
16073                    sequence,
16074                    signal_name,
16075                    value,
16076                    parallel_group_path: recorded_parallel_group_path(
16077                        &signal_wait_events,
16078                        sequence,
16079                    )?,
16080                });
16081            }
16082
16083            if !condition_wait_events.is_empty() {
16084                return recorded_condition_wait(
16085                    sequence,
16086                    &condition_wait_events,
16087                    events,
16088                );
16089            }
16090
16091            if !search_attribute_events.is_empty() {
16092                if search_attribute_events.len() != 1 {
16093                    return Err(invalid_recorded_history(
16094                        "duplicate_search_attribute_update",
16095                        sequence,
16096                        "one SearchAttributesUpserted event",
16097                        &format!(
16098                            "{} SearchAttributesUpserted events",
16099                            search_attribute_events.len()
16100                        ),
16101                        "search-attribute history records one workflow command more than once",
16102                    ));
16103                }
16104                let payload = &search_attribute_events[0].payload;
16105                let attributes = payload
16106                    .get("attributes")
16107                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16108                    .cloned()
16109                    .ok_or_else(|| {
16110                        invalid_recorded_history(
16111                            "search_attribute_update_missing",
16112                            sequence,
16113                            "non-empty attributes object",
16114                            "missing or invalid attributes",
16115                            "search-attribute history is missing its recorded mutation",
16116                        )
16117                    })?;
16118                let attribute_types =
16119                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16120                return Ok(RecordedCommand::SearchAttributes {
16121                    sequence,
16122                    attributes,
16123                    attribute_types,
16124                });
16125            }
16126
16127            if !side_effect_events.is_empty() {
16128                if side_effect_events.len() != 1 {
16129                    return Err(invalid_recorded_history(
16130                        "duplicate_side_effect_record",
16131                        sequence,
16132                        "one SideEffectRecorded event",
16133                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16134                        "side-effect history records one workflow command more than once",
16135                    ));
16136                }
16137                let event = side_effect_events[0];
16138                let result = event.payload.get("result").ok_or_else(|| {
16139                    invalid_recorded_history(
16140                        "side_effect_result_missing",
16141                        sequence,
16142                        "recorded result payload",
16143                        "missing result",
16144                        "side-effect history is missing its recorded value",
16145                    )
16146                })?;
16147                let has_published_envelope = result.as_str().is_some()
16148                    || result.as_object().is_some_and(|envelope| {
16149                        envelope.get("codec").and_then(Value::as_str).is_some()
16150                            && envelope.get("blob").and_then(Value::as_str).is_some()
16151                    });
16152                if !has_published_envelope {
16153                    return Err(invalid_recorded_history(
16154                        "side_effect_payload_malformed",
16155                        sequence,
16156                        "payload blob or {codec, blob} envelope",
16157                        &result.to_string(),
16158                        "side-effect history result does not use a published payload envelope",
16159                    ));
16160                }
16161                let codec = event
16162                    .payload
16163                    .get("payload_codec")
16164                    .and_then(Value::as_str)
16165                    .unwrap_or(fallback_codec);
16166                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16167                    if error.to_string().contains("unsupported_payload_codec") {
16168                        return error;
16169                    }
16170
16171                    invalid_recorded_history(
16172                        "side_effect_payload_incompatible",
16173                        sequence,
16174                        &format!("valid {codec} payload envelope"),
16175                        &error.to_string(),
16176                        "side-effect history payload cannot be decoded with its recorded codec",
16177                    )
16178                })?;
16179                return Ok(RecordedCommand::SideEffect { sequence, value });
16180            }
16181
16182            if !version_marker_events.is_empty() {
16183                if version_marker_events.len() != 1 {
16184                    return Err(invalid_recorded_history(
16185                        "duplicate_version_marker_record",
16186                        sequence,
16187                        "one VersionMarkerRecorded event",
16188                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16189                        "version-marker history records one workflow command more than once",
16190                    ));
16191                }
16192                let payload = &version_marker_events[0].payload;
16193                let change_id = payload
16194                    .get("change_id")
16195                    .and_then(Value::as_str)
16196                    .filter(|value| !value.is_empty())
16197                    .map(str::to_string)
16198                    .ok_or_else(|| {
16199                        invalid_recorded_history(
16200                            "version_marker_field_missing",
16201                            sequence,
16202                            "non-empty change_id",
16203                            "missing or invalid change_id",
16204                            "version-marker history is missing its stable change ID",
16205                        )
16206                    })?;
16207                let version = required_version_i32(payload, "version", sequence)?;
16208                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16209                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16210                if min_supported > max_supported || version < min_supported || version > max_supported {
16211                    return Err(invalid_recorded_history(
16212                        "version_marker_history_range_invalid",
16213                        sequence,
16214                        "min_supported <= version <= max_supported",
16215                        &format!("{min_supported} <= {version} <= {max_supported}"),
16216                        "recorded version marker contains an internally incompatible range",
16217                    ));
16218                }
16219                return Ok(RecordedCommand::VersionMarker {
16220                    sequence,
16221                    change_id,
16222                    version,
16223                });
16224            }
16225
16226            if !memo_events.is_empty() {
16227                if memo_events.len() != 1 {
16228                    return Err(invalid_recorded_history(
16229                        "duplicate_memo_upsert_record",
16230                        sequence,
16231                        "one MemoUpserted event",
16232                        &format!("{} MemoUpserted events", memo_events.len()),
16233                        "memo history records one workflow update more than once",
16234                    ));
16235                }
16236                let payload = &memo_events[0].payload;
16237                let entries = payload.get("entries").cloned().ok_or_else(|| {
16238                    invalid_recorded_history(
16239                        "memo_entries_missing",
16240                        sequence,
16241                        "memo entries object",
16242                        "missing entries",
16243                        "MemoUpserted history is missing replay identity entries",
16244                    )
16245                })?;
16246                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16247                    invalid_recorded_history(
16248                        "memo_entries_invalid",
16249                        sequence,
16250                        "valid canonical memo entries",
16251                        &error.to_string(),
16252                        "MemoUpserted history contains invalid replay identity entries",
16253                    )
16254                })?;
16255                let merged = payload.get("merged").cloned().ok_or_else(|| {
16256                    invalid_recorded_history(
16257                        "memo_merged_projection_missing",
16258                        sequence,
16259                        "merged memo projection",
16260                        "missing merged",
16261                        "MemoUpserted history is missing its merged projection",
16262                    )
16263                })?;
16264                decode_memo_history_map(&merged, false).map_err(|error| {
16265                    invalid_recorded_history(
16266                        "memo_merged_projection_invalid",
16267                        sequence,
16268                        "valid merged memo projection",
16269                        &error.to_string(),
16270                        "MemoUpserted history contains an invalid merged projection",
16271                    )
16272                })?;
16273
16274                return Ok(RecordedCommand::Memo { sequence, entries });
16275            }
16276            let scheduled: Vec<_> = timer_events
16277                .iter()
16278                .copied()
16279                .filter(|event| event.event_type == "TimerScheduled")
16280                .collect();
16281            let fired: Vec<_> = timer_events
16282                .iter()
16283                .copied()
16284                .filter(|event| event.event_type == "TimerFired")
16285                .collect();
16286            if scheduled.len() != 1 {
16287                return Err(invalid_recorded_history(
16288                    "timer_schedule_missing_or_duplicate",
16289                    sequence,
16290                    "one TimerScheduled event",
16291                    &format!("{} TimerScheduled events", scheduled.len()),
16292                    "timer replay requires exactly one recorded schedule event",
16293                ));
16294            }
16295            if fired.len() > 1 {
16296                return Err(invalid_recorded_history(
16297                    "duplicate_timer_fire",
16298                    sequence,
16299                    "at most one TimerFired event",
16300                    "multiple TimerFired events",
16301                    "timer history contains more than one fire event for a workflow sequence",
16302                ));
16303            }
16304
16305            let scheduled = scheduled[0];
16306            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16307            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16308            if let Some(fired) = fired.first() {
16309                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16310                if fired_timer_id != timer_id {
16311                    return Err(invalid_recorded_history(
16312                        "timer_identity_mismatch",
16313                        sequence,
16314                        &timer_id,
16315                        &fired_timer_id,
16316                        "TimerFired does not correspond to the recorded TimerScheduled event",
16317                    ));
16318                }
16319                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16320                if fired_delay != delay_seconds {
16321                    return Err(invalid_recorded_history(
16322                        "timer_history_delay_mismatch",
16323                        sequence,
16324                        &delay_seconds.to_string(),
16325                        &fired_delay.to_string(),
16326                        "TimerScheduled and TimerFired record different delays",
16327                    ));
16328                }
16329            }
16330
16331            Ok(RecordedCommand::Timer {
16332                sequence,
16333                delay_seconds,
16334                fired: !fired.is_empty(),
16335                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16336            })
16337        })
16338        .collect::<Result<_>>()?;
16339
16340    let mut marker_decisions = HashMap::new();
16341    for command in &commands {
16342        if let RecordedCommand::VersionMarker {
16343            sequence,
16344            change_id,
16345            version,
16346        } = command
16347        {
16348            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16349                if version != first_version {
16350                    return Err(invalid_recorded_history(
16351                        "version_marker_conflict",
16352                        *sequence,
16353                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16354                        &format!("version {version} at sequence {sequence}"),
16355                        "workflow history contains conflicting decisions for one stable change ID",
16356                    ));
16357                }
16358            } else {
16359                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16360            }
16361        }
16362    }
16363
16364    Ok(commands)
16365}
16366
16367fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16368    payload
16369        .get(field)
16370        .and_then(Value::as_i64)
16371        .and_then(|value| i32::try_from(value).ok())
16372        .ok_or_else(|| {
16373            invalid_recorded_history(
16374                "version_marker_field_missing",
16375                sequence,
16376                &format!("integer {field}"),
16377                "missing or out-of-range integer",
16378                "version-marker history is missing a required integer field",
16379            )
16380        })
16381}
16382
16383fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16384    event
16385        .payload
16386        .get("sequence")
16387        .or_else(|| event.payload.get("workflow_sequence"))
16388        .or_else(|| event.raw.get("sequence"))
16389        .or_else(|| event.raw.get("workflow_sequence"))
16390        .and_then(value_as_u64)
16391}
16392
16393fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16394    matches!(
16395        event
16396            .payload
16397            .get("timer_kind")
16398            .or_else(|| event.raw.get("timer_kind"))
16399            .and_then(Value::as_str),
16400        Some("condition_timeout" | "signal_timeout")
16401    )
16402}
16403
16404fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16405    matches!(
16406        event.event_type.as_str(),
16407        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16408    )
16409}
16410
16411fn recorded_condition_wait(
16412    sequence: u64,
16413    condition_events: &[&HistoryEvent],
16414    all_events: &[HistoryEvent],
16415) -> Result<RecordedCommand> {
16416    let opened = condition_events
16417        .iter()
16418        .copied()
16419        .filter(|event| event.event_type == "ConditionWaitOpened")
16420        .collect::<Vec<_>>();
16421    if opened.len() != 1 {
16422        return Err(invalid_recorded_history(
16423            "condition_wait_open_missing_or_duplicate",
16424            sequence,
16425            "one ConditionWaitOpened event",
16426            &format!("{} ConditionWaitOpened events", opened.len()),
16427            "condition replay requires exactly one canonical wait-open event",
16428        ));
16429    }
16430    let terminal = condition_events
16431        .iter()
16432        .copied()
16433        .filter(|event| {
16434            matches!(
16435                event.event_type.as_str(),
16436                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16437            )
16438        })
16439        .collect::<Vec<_>>();
16440    if terminal.len() > 1 {
16441        return Err(invalid_recorded_history(
16442            "duplicate_condition_wait_terminal_event",
16443            sequence,
16444            "at most one condition terminal event",
16445            "multiple condition terminal events",
16446            "condition history settles one durable wait more than once",
16447        ));
16448    }
16449
16450    let opened = opened[0];
16451    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16452    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16453    for event in condition_events
16454        .iter()
16455        .copied()
16456        .filter(|event| !std::ptr::eq(*event, opened))
16457    {
16458        let event_wait_id = required_condition_wait_id(event, sequence)?;
16459        if event_wait_id != condition_wait_id {
16460            return Err(invalid_recorded_history(
16461                "condition_wait_id_mismatch",
16462                sequence,
16463                &condition_wait_id,
16464                &event_wait_id,
16465                "condition lifecycle events at one sequence disagree on wait identity",
16466            ));
16467        }
16468        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16469        if event_occurrence_id != occurrence_id {
16470            return Err(invalid_recorded_history(
16471                "condition_wait_occurrence_history_mismatch",
16472                sequence,
16473                &occurrence_id,
16474                &event_occurrence_id,
16475                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16476            ));
16477        }
16478    }
16479
16480    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16481    let predicate_identity = opened
16482        .payload
16483        .get("condition_definition_fingerprint")
16484        .and_then(Value::as_str)
16485        .filter(|value| !value.is_empty())
16486        .map(str::to_string)
16487        .ok_or_else(|| {
16488            invalid_recorded_history(
16489                "condition_wait_predicate_fingerprint_missing",
16490                sequence,
16491                "non-empty condition_definition_fingerprint",
16492                &opened.event_type,
16493                "canonical condition history is missing its predicate identity",
16494            )
16495        })?;
16496    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16497    for event in condition_events
16498        .iter()
16499        .copied()
16500        .filter(|event| !std::ptr::eq(*event, opened))
16501    {
16502        for (field, opened_value) in [
16503            ("condition_key", condition_key.as_deref()),
16504            (
16505                "condition_definition_fingerprint",
16506                Some(predicate_identity.as_str()),
16507            ),
16508        ] {
16509            if let Some(value) = optional_non_empty_history_string(event, field) {
16510                if opened_value.is_some_and(|opened_value| opened_value != value) {
16511                    return Err(invalid_recorded_history(
16512                        "condition_wait_definition_history_mismatch",
16513                        sequence,
16514                        opened_value.unwrap_or_default(),
16515                        &value,
16516                        "condition lifecycle events disagree on the recorded definition",
16517                    ));
16518                }
16519            }
16520        }
16521        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16522            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16523                return Err(invalid_recorded_history(
16524                    "condition_wait_definition_history_mismatch",
16525                    sequence,
16526                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16527                    &format!("{event_timeout}s"),
16528                    "condition lifecycle events disagree on the recorded timeout",
16529                ));
16530            }
16531        }
16532    }
16533
16534    let timeout_timer_events = all_events
16535        .iter()
16536        .filter(|event| {
16537            matches!(
16538                event.event_type.as_str(),
16539                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16540            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16541                == Some("condition_timeout")
16542                && event
16543                    .payload
16544                    .get("condition_wait_id")
16545                    .and_then(Value::as_str)
16546                    == Some(condition_wait_id.as_str())
16547        })
16548        .collect::<Vec<_>>();
16549    let scheduled = timeout_timer_events
16550        .iter()
16551        .copied()
16552        .filter(|event| event.event_type == "TimerScheduled")
16553        .collect::<Vec<_>>();
16554    let fired = timeout_timer_events
16555        .iter()
16556        .copied()
16557        .filter(|event| event.event_type == "TimerFired")
16558        .collect::<Vec<_>>();
16559    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16560        return Err(invalid_recorded_history(
16561            "condition_wait_timeout_history_invalid",
16562            sequence,
16563            "one timeout schedule and at most one fire",
16564            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16565            "condition timeout history has a missing or duplicate lifecycle event",
16566        ));
16567    }
16568    if let Some(scheduled) = scheduled.first() {
16569        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16570        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16571        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16572            return Err(invalid_recorded_history(
16573                "condition_wait_timeout_delay_mismatch",
16574                sequence,
16575                &format!("{}s", timeout_seconds.unwrap_or_default()),
16576                &format!("{delay_seconds}s"),
16577                "condition timeout timer differs from the wait definition",
16578            ));
16579        }
16580        if let Some(fired) = fired.first() {
16581            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16582            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16583            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16584                return Err(invalid_recorded_history(
16585                    "condition_wait_timeout_identity_mismatch",
16586                    sequence,
16587                    &format!("{timer_id}:{delay_seconds}s"),
16588                    &format!("{fired_timer_id}:{fired_delay}s"),
16589                    "condition timeout fire does not match its durable schedule",
16590                ));
16591            }
16592        }
16593    }
16594
16595    let result = terminal.first().map(|event| {
16596        if event.event_type == "ConditionWaitTimedOut" {
16597            ConditionWaitResult::TimedOut
16598        } else {
16599            ConditionWaitResult::Satisfied
16600        }
16601    });
16602    let result = if !fired.is_empty() {
16603        if result == Some(ConditionWaitResult::Satisfied) {
16604            return Err(invalid_recorded_history(
16605                "condition_wait_terminal_conflict",
16606                sequence,
16607                "one satisfied or timed-out outcome",
16608                "satisfied event and fired timeout",
16609                "condition history records conflicting terminal outcomes",
16610            ));
16611        }
16612        Some(ConditionWaitResult::TimedOut)
16613    } else {
16614        result
16615    };
16616
16617    Ok(RecordedCommand::ConditionWait {
16618        sequence,
16619        occurrence_id,
16620        condition_key,
16621        predicate_identity,
16622        timeout_seconds,
16623        result,
16624        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16625    })
16626}
16627
16628fn recorded_condition_group_path(
16629    condition_events: &[&HistoryEvent],
16630    all_events: &[HistoryEvent],
16631    sequence: u64,
16632) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16633    let opened = condition_events
16634        .iter()
16635        .copied()
16636        .find(|event| event.event_type == "ConditionWaitOpened")
16637        .expect("canonical condition opener is validated first");
16638    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16639    let previous_events = all_events
16640        .iter()
16641        .take_while(|event| !std::ptr::eq(*event, opened))
16642        .collect::<Vec<_>>();
16643    let originals = previous_events
16644        .iter()
16645        .copied()
16646        .filter(|event| event.event_type == "ConditionWaitOpened")
16647        .filter(|event| {
16648            event
16649                .payload
16650                .get("condition_wait_occurrence_id")
16651                .and_then(Value::as_str)
16652                == Some(occurrence.as_str())
16653        })
16654        .collect::<Vec<_>>();
16655    let Some(original) = originals.first().copied() else {
16656        return recorded_parallel_group_path(condition_events, sequence);
16657    };
16658    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16659    if authored_sequence == sequence {
16660        return recorded_parallel_group_path(condition_events, sequence);
16661    }
16662    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16663    if original_path.is_none() {
16664        return recorded_parallel_group_path(condition_events, sequence);
16665    }
16666    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16667    let identity_matches = [
16668        "condition_key",
16669        "condition_definition_fingerprint",
16670        "timeout_seconds",
16671    ]
16672    .iter()
16673    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16674    let previous = originals
16675        .iter()
16676        .copied()
16677        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16678        .max_by_key(|event| durable_event_sequence(event));
16679    let previously_satisfied = previous.is_some_and(|previous| {
16680        previous_events.iter().any(|event| {
16681            event.event_type == "ConditionWaitSatisfied"
16682                && event.payload.get("condition_wait_id")
16683                    == previous.payload.get("condition_wait_id")
16684                && event.payload.get("condition_wait_occurrence_id")
16685                    == previous.payload.get("condition_wait_occurrence_id")
16686                && durable_event_sequence(event) == durable_event_sequence(previous)
16687        })
16688    });
16689    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16690        return Err(invalid_recorded_history(
16691            "condition_wait_group_reopen_mismatch",
16692            sequence,
16693            "same authored condition and group path after a satisfied physical wait",
16694            &opened.payload.to_string(),
16695            "grouped condition reopen has no matching recorded predecessor",
16696        ));
16697    }
16698    Ok(reopened_path)
16699}
16700
16701fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16702    event
16703        .payload
16704        .get("condition_wait_occurrence_id")
16705        .and_then(Value::as_str)
16706        .filter(|value| !value.is_empty())
16707        .map(str::to_string)
16708        .ok_or_else(|| {
16709            invalid_recorded_history(
16710                "condition_wait_occurrence_id_missing",
16711                sequence,
16712                "non-empty condition_wait_occurrence_id",
16713                &event.event_type,
16714                "condition history is missing authored occurrence identity",
16715            )
16716        })
16717}
16718
16719fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16720    event
16721        .payload
16722        .get("condition_wait_id")
16723        .and_then(Value::as_str)
16724        .filter(|value| !value.is_empty())
16725        .map(str::to_string)
16726        .ok_or_else(|| {
16727            invalid_recorded_history(
16728                "condition_wait_id_missing",
16729                sequence,
16730                "non-empty condition_wait_id",
16731                &event.event_type,
16732                "canonical condition history is missing its durable wait identity",
16733            )
16734        })
16735}
16736
16737fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16738    event
16739        .payload
16740        .get(field)
16741        .and_then(Value::as_str)
16742        .filter(|value| !value.is_empty())
16743        .map(str::to_string)
16744}
16745
16746fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16747    match event.payload.get(field) {
16748        None | Some(Value::Null) => Ok(None),
16749        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16750            invalid_recorded_history(
16751                "condition_wait_definition_invalid",
16752                sequence,
16753                &format!("non-negative integer {field}"),
16754                &value.to_string(),
16755                "condition history contains an invalid numeric definition field",
16756            )
16757        }),
16758    }
16759}
16760
16761fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16762    event
16763        .payload
16764        .get("signal_name")
16765        .or_else(|| event.raw.get("signal_name"))
16766        .and_then(Value::as_str)
16767        .filter(|value| !value.is_empty())
16768        .map(str::to_string)
16769        .ok_or_else(|| {
16770            invalid_recorded_history(
16771                "signal_wait_name_missing",
16772                sequence,
16773                "non-empty signal_name",
16774                &event.event_type,
16775                "canonical signal-wait history is missing its signal identity",
16776            )
16777        })
16778}
16779
16780fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16781    // Applying a buffered control-plane signal has no authored call sequence.
16782    // Its outer sequence orders history events and must not become a wait.
16783    if event.event_type == "SignalApplied"
16784        && event
16785            .payload
16786            .get("signal_wait_id")
16787            .and_then(Value::as_str)
16788            .is_some_and(|id| id.starts_with("signal-command:"))
16789        && event.payload.get("sequence").is_none()
16790        && event.payload.get("workflow_sequence").is_none()
16791    {
16792        return false;
16793    }
16794    matches!(
16795        event.event_type.as_str(),
16796        "SignalWaitOpened" | "SignalApplied"
16797    )
16798}
16799
16800fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16801    event
16802        .payload
16803        .get(field)
16804        .and_then(Value::as_str)
16805        .filter(|value| !value.is_empty())
16806        .map(str::to_string)
16807        .ok_or_else(|| {
16808            invalid_recorded_history(
16809                "timer_history_field_missing",
16810                sequence,
16811                field,
16812                &event.event_type,
16813                "timer history is missing a required identity field",
16814            )
16815        })
16816}
16817
16818fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16819    event
16820        .payload
16821        .get(field)
16822        .and_then(value_as_u64)
16823        .ok_or_else(|| {
16824            invalid_recorded_history(
16825                "timer_history_field_missing",
16826                sequence,
16827                field,
16828                &event.event_type,
16829                "timer history is missing a required numeric field",
16830            )
16831        })
16832}
16833
16834fn recorded_search_attribute_types(
16835    payload: &Value,
16836    attributes: &Value,
16837    sequence: u64,
16838) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16839    let Some(raw_types) = payload.get("attribute_types") else {
16840        // This is the explicit compatibility rule for histories recorded
16841        // before typed identity was persisted. Values still constrain replay;
16842        // the unknown type snapshot does not assert a typed match.
16843        return Ok(RecordedSnapshotValue::Unknown);
16844    };
16845    let Some(raw_types) = raw_types.as_object() else {
16846        return Err(invalid_recorded_history(
16847            "search_attribute_types_malformed",
16848            sequence,
16849            "canonical attribute type map",
16850            &raw_types.to_string(),
16851            "search-attribute history contains malformed type identity",
16852        ));
16853    };
16854    let attribute_keys = attributes
16855        .as_object()
16856        .expect("recorded search attributes were validated as an object");
16857    let mut types = BTreeMap::new();
16858    for (key, value) in raw_types {
16859        let Some(attribute_type) = value.as_str() else {
16860            return Err(invalid_recorded_history(
16861                "search_attribute_types_malformed",
16862                sequence,
16863                "canonical string type name",
16864                &value.to_string(),
16865                "search-attribute history contains a non-string type identity",
16866            ));
16867        };
16868        if !attribute_keys.contains_key(key)
16869            || !matches!(
16870                attribute_type,
16871                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16872            )
16873        {
16874            return Err(invalid_recorded_history(
16875                "search_attribute_types_malformed",
16876                sequence,
16877                "canonical types for keys present in attributes",
16878                &format!("{key}:{attribute_type}"),
16879                "search-attribute history contains unsupported or orphaned type identity",
16880            ));
16881        }
16882        types.insert(key.clone(), attribute_type.to_string());
16883    }
16884    Ok(RecordedSnapshotValue::Known(types))
16885}
16886
16887fn invalid_recorded_history(
16888    reason: &str,
16889    sequence: u64,
16890    expected: &str,
16891    actual: &str,
16892    message: &str,
16893) -> Error {
16894    Error::NonDeterministicReplay(ReplayFailure::new(
16895        reason,
16896        Some(sequence),
16897        Some(expected.to_string()),
16898        Some(actual.to_string()),
16899        message,
16900    ))
16901}
16902
16903type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16904
16905fn activity_outcome(
16906    event: &HistoryEvent,
16907    fallback_codec: &str,
16908    recorded_activity_type: Option<String>,
16909) -> Result<ActivityOutcome> {
16910    if event.event_type == "ActivityCompleted" {
16911        let codec = event
16912            .payload
16913            .get("payload_codec")
16914            .and_then(Value::as_str)
16915            .unwrap_or(fallback_codec);
16916        return Ok(Ok(decode_wire_avro_value(
16917            event.payload.get("result").unwrap_or(&Value::Null),
16918            codec,
16919        )?));
16920    }
16921
16922    let payload = &event.payload;
16923    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16924        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16925        "ActivityCancelled" => (
16926            ActivityFailureKind::Cancelled,
16927            "cancelled",
16928            "activity was cancelled",
16929        ),
16930        "ActivityTimedOut" => (
16931            ActivityFailureKind::TimedOut,
16932            "timeout",
16933            "activity timed out",
16934        ),
16935        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16936    };
16937    let exception = payload
16938        .get("exception")
16939        .filter(|value| !value.is_null())
16940        .cloned();
16941    let failure_category = payload_string(payload, "failure_category");
16942    let timeout_kind = payload_string(payload, "timeout_kind");
16943    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16944        ActivityFailureKind::Failed => failure_category
16945            .clone()
16946            .unwrap_or_else(|| fallback_reason.to_string()),
16947        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16948        ActivityFailureKind::TimedOut => timeout_kind
16949            .clone()
16950            .unwrap_or_else(|| fallback_reason.to_string()),
16951    });
16952    let message = payload_string(payload, "message")
16953        .or_else(|| {
16954            exception
16955                .as_ref()
16956                .and_then(|value| payload_string(value, "message"))
16957        })
16958        .unwrap_or_else(|| fallback_message.to_string());
16959
16960    Ok(Err(ActivityFailure {
16961        kind,
16962        reason,
16963        message,
16964        activity_execution_id: payload_string(payload, "activity_execution_id"),
16965        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16966        activity_type: payload_string(payload, "activity_type")
16967            .or_else(|| payload_string(payload, "activity_name"))
16968            .or(recorded_activity_type),
16969        activity_class: payload_string(payload, "activity_class"),
16970        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16971        failure_id: payload_string(payload, "failure_id"),
16972        failure_category,
16973        timeout_kind,
16974        non_retryable: payload
16975            .get("non_retryable")
16976            .and_then(Value::as_bool)
16977            .unwrap_or(false),
16978        exception_type: payload_string(payload, "exception_type").or_else(|| {
16979            exception
16980                .as_ref()
16981                .and_then(|value| payload_string(value, "type"))
16982        }),
16983        exception_class: payload_string(payload, "exception_class").or_else(|| {
16984            exception
16985                .as_ref()
16986                .and_then(|value| payload_string(value, "class"))
16987        }),
16988        code: payload
16989            .get("code")
16990            .filter(|value| !value.is_null())
16991            .cloned(),
16992        exception,
16993    }))
16994}
16995
16996type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
16997
16998fn child_workflow_outcomes(
16999    events: &[HistoryEvent],
17000    fallback_codec: &str,
17001    parent: WorkflowIdentity,
17002) -> Result<Vec<ChildWorkflowOutcome>> {
17003    let mut outcomes = Vec::new();
17004
17005    for event in events {
17006        let kind = match event.event_type.as_str() {
17007            "ChildRunCompleted" => None,
17008            "ChildRunFailed" => Some((
17009                ChildWorkflowFailureKind::Failed,
17010                "child_workflow",
17011                "child workflow failed",
17012            )),
17013            "ChildRunCancelled" => Some((
17014                ChildWorkflowFailureKind::Cancelled,
17015                "cancelled",
17016                "child workflow was cancelled",
17017            )),
17018            "ChildRunTerminated" => Some((
17019                ChildWorkflowFailureKind::Terminated,
17020                "terminated",
17021                "child workflow was terminated",
17022            )),
17023            _ => continue,
17024        };
17025        let payload = &event.payload;
17026        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17027        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17028        let child_workflow_type = payload_string(payload, "child_workflow_type");
17029
17030        if let Some((kind, reason, fallback_message)) = kind {
17031            let exception = payload
17032                .get("exception")
17033                .filter(|value| !value.is_null())
17034                .cloned();
17035            let message = payload_string(payload, "message")
17036                .or_else(|| {
17037                    exception
17038                        .as_ref()
17039                        .and_then(|value| payload_string(value, "message"))
17040                })
17041                .unwrap_or_else(|| fallback_message.to_string());
17042            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17043                exception
17044                    .as_ref()
17045                    .and_then(|value| payload_string(value, "type"))
17046            });
17047            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17048                exception
17049                    .as_ref()
17050                    .and_then(|value| payload_string(value, "class"))
17051            });
17052            outcomes.push(Err(ChildWorkflowFailure {
17053                kind,
17054                reason: reason.to_string(),
17055                message,
17056                parent_workflow_id: parent.workflow_id.clone(),
17057                parent_workflow_run_id: parent.run_id.clone(),
17058                child_workflow_id,
17059                child_workflow_run_id,
17060                child_workflow_type,
17061                failure_id: payload_string(payload, "failure_id"),
17062                failure_category: payload_string(payload, "failure_category"),
17063                exception_type,
17064                exception_class,
17065                non_retryable: payload
17066                    .get("non_retryable")
17067                    .and_then(Value::as_bool)
17068                    .unwrap_or(false),
17069                code: payload
17070                    .get("code")
17071                    .filter(|value| !value.is_null())
17072                    .cloned(),
17073                exception,
17074            }));
17075            continue;
17076        }
17077
17078        let codec = payload
17079            .get("payload_codec")
17080            .and_then(Value::as_str)
17081            .unwrap_or(fallback_codec);
17082        let result = payload
17083            .get("result")
17084            .or_else(|| payload.get("output"))
17085            .unwrap_or(&Value::Null);
17086        outcomes.push(Ok(ChildWorkflowAvroResult {
17087            parent: parent.clone(),
17088            child: WorkflowIdentity {
17089                workflow_id: child_workflow_id,
17090                run_id: child_workflow_run_id,
17091            },
17092            child_workflow_type,
17093            result: decode_wire_avro_value(result, codec)?,
17094        }));
17095    }
17096
17097    Ok(outcomes)
17098}
17099
17100fn payload_string(payload: &Value, key: &str) -> Option<String> {
17101    payload
17102        .get(key)
17103        .and_then(Value::as_str)
17104        .filter(|value| !value.is_empty())
17105        .map(str::to_string)
17106}
17107
17108fn recorded_activity_failure_boundary(
17109    ctx: &WorkflowContext,
17110    error: &Error,
17111) -> Option<(u64, String)> {
17112    let Error::ActivityFailed(failure) = error else {
17113        return None;
17114    };
17115    if failure.kind != ActivityFailureKind::Failed {
17116        return None;
17117    }
17118    let activity_execution_id = failure
17119        .activity_execution_id
17120        .as_deref()
17121        .filter(|value| !value.is_empty())?;
17122    let state = ctx.state.lock().ok()?;
17123    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17124        let RecordedCommand::Activity {
17125            sequence,
17126            outcome: Some(Err(recorded_failure)),
17127            ..
17128        } = command
17129        else {
17130            return None;
17131        };
17132        (*sequence > 0 && recorded_failure == failure)
17133            .then_some((*sequence, activity_execution_id.to_string()))
17134    });
17135    let boundary = matches.next()?;
17136    matches.next().is_none().then_some(boundary)
17137}
17138
17139fn workflow_failure_command(
17140    error: &Error,
17141    failed_activity_boundary: Option<(u64, String)>,
17142) -> Value {
17143    let (exception_type, exception_class, properties) = match error {
17144        Error::ActivityFailed(failure) => (
17145            match failure.kind {
17146                ActivityFailureKind::Failed => "ActivityFailed",
17147                ActivityFailureKind::Cancelled => "ActivityCancelled",
17148                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17149            },
17150            "durable_workflow::ActivityFailure",
17151            json!({
17152                "reason": failure.reason,
17153                "activity_execution_id": failure.activity_execution_id,
17154                "activity_attempt_id": failure.activity_attempt_id,
17155                "activity_type": failure.activity_type,
17156                "activity_class": failure.activity_class,
17157                "attempt_number": failure.attempt_number,
17158                "failure_id": failure.failure_id,
17159                "failure_category": failure.failure_category,
17160                "timeout_kind": failure.timeout_kind,
17161                "activity_non_retryable": failure.non_retryable,
17162                "activity_exception_type": failure.exception_type,
17163                "activity_exception_class": failure.exception_class,
17164                "activity_code": failure.code,
17165                "activity_exception": failure.exception,
17166            }),
17167        ),
17168        Error::ChildWorkflowFailed(failure) => (
17169            match failure.kind {
17170                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17171                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17172                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17173            },
17174            "durable_workflow::ChildWorkflowFailure",
17175            json!({
17176                "reason": failure.reason,
17177                "parent_workflow_id": failure.parent_workflow_id,
17178                "parent_workflow_run_id": failure.parent_workflow_run_id,
17179                "child_workflow_id": failure.child_workflow_id,
17180                "child_workflow_run_id": failure.child_workflow_run_id,
17181                "child_workflow_type": failure.child_workflow_type,
17182                "failure_id": failure.failure_id,
17183                "failure_category": failure.failure_category,
17184                "child_exception_type": failure.exception_type,
17185                "child_exception_class": failure.exception_class,
17186                "child_non_retryable": failure.non_retryable,
17187                "child_code": failure.code,
17188                "child_exception": failure.exception,
17189            }),
17190        ),
17191        Error::ParallelFailed(failure) => (
17192            "ParallelFailed",
17193            "durable_workflow::ParallelFailure",
17194            json!({
17195                "parallel_group_id": failure.group_id,
17196                "parallel_member_path": failure.member_path,
17197                "parallel_group_path": failure.group_path,
17198                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17199                "cause_type": workflow_error_type(&failure.cause),
17200                "cause_message": failure.cause.to_string(),
17201            }),
17202        ),
17203        Error::SagaCompensationFailed(failure) => (
17204            "SagaCompensationFailed",
17205            "durable_workflow::SagaCompensationFailure",
17206            json!({
17207                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17208                "initiating_failure_message": failure.initiating_failure.to_string(),
17209                "compensation_activity_type": failure.compensation_activity_type,
17210                "compensation_registration_order": failure.compensation_registration_order,
17211                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17212                "compensation_failure_message": failure.compensation_failure.to_string(),
17213            }),
17214        ),
17215        Error::WorkflowCancellationRequested(_) => (
17216            "WorkflowCancellationRequested",
17217            "durable_workflow::WorkflowCancellationRequested",
17218            json!({"reason": "cancelled"}),
17219        ),
17220        Error::CooperativeCancellationRequested(cancellation) => (
17221            "WorkflowCancellationRequested",
17222            "durable_workflow::CooperativeCancellationRequested",
17223            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17224                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17225        ),
17226        Error::CancellationScopeRequested(cancellation) => (
17227            "WorkflowCancellationRequested",
17228            "durable_workflow::CancellationScopeRequested",
17229            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17230                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17231                "cancellation":cancellation.context.to_value()}),
17232        ),
17233        Error::NonDeterministicReplay(_) => (
17234            "NonDeterministicReplay",
17235            "durable_workflow::Error",
17236            Value::Null,
17237        ),
17238        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17239    };
17240    let non_retryable = match error {
17241        Error::ActivityFailed(failure) => failure.non_retryable,
17242        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17243        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17244        Error::SagaCompensationFailed(failure) => {
17245            workflow_error_non_retryable(&failure.compensation_failure)
17246        }
17247        Error::WorkflowCancellationRequested(_)
17248        | Error::CooperativeCancellationRequested(_)
17249        | Error::CancellationScopeRequested(_) => true,
17250        Error::NonDeterministicReplay(_) => true,
17251        _ => false,
17252    };
17253
17254    let mut command = json!({
17255        "type": "fail_workflow",
17256        "message": error.to_string(),
17257        "exception_type": exception_type,
17258        "exception_class": exception_class,
17259        "non_retryable": non_retryable,
17260        "exception": {
17261            "type": exception_type,
17262            "class": exception_class,
17263            "message": error.to_string(),
17264            "properties": properties,
17265        }
17266    });
17267
17268    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17269        command["failed_step_sequence"] = json!(sequence);
17270        command["failed_activity_execution_id"] = json!(activity_execution_id);
17271    }
17272
17273    command
17274}
17275
17276fn workflow_error_type(error: &Error) -> &'static str {
17277    match error {
17278        Error::ActivityFailed(failure) => match failure.kind {
17279            ActivityFailureKind::Failed => "ActivityFailed",
17280            ActivityFailureKind::Cancelled => "ActivityCancelled",
17281            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17282        },
17283        Error::ChildWorkflowFailed(failure) => match failure.kind {
17284            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17285            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17286            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17287        },
17288        Error::ParallelFailed(_) => "ParallelFailed",
17289        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17290        Error::WorkflowCancellationRequested(_)
17291        | Error::CooperativeCancellationRequested(_)
17292        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17293        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17294        _ => "RustWorkflowError",
17295    }
17296}
17297
17298fn workflow_error_non_retryable(error: &Error) -> bool {
17299    match error {
17300        Error::ActivityFailed(failure) => failure.non_retryable,
17301        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17302        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17303        Error::SagaCompensationFailed(failure) => {
17304            workflow_error_non_retryable(&failure.compensation_failure)
17305        }
17306        Error::WorkflowCancellationRequested(_)
17307        | Error::CooperativeCancellationRequested(_)
17308        | Error::CancellationScopeRequested(_)
17309        | Error::NonDeterministicReplay(_) => true,
17310        _ => false,
17311    }
17312}
17313
17314fn workflow_task_integrity_error(error: &Error) -> bool {
17315    matches!(
17316        error,
17317        Error::NonDeterministicReplay(_)
17318            | Error::Protocol(_)
17319            | Error::CancellationScopeExecutionUnavailable
17320            | Error::MissingWorkflowCommandIdentity
17321            | Error::WorkflowStatePoisoned
17322    )
17323}
17324
17325fn decode_signal_event_arguments(
17326    event: &HistoryEvent,
17327    fallback_codec: &str,
17328) -> Result<Vec<AvroValue>> {
17329    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17330    validate_payload_codec(codec)?;
17331    let raw = signal_history_payload(&event.payload);
17332    let decoded = match raw.filter(|value| !value.is_null()) {
17333        Some(value) => decode_wire_avro_value(value, codec)?,
17334        None => AvroValue::Array(Vec::new()),
17335    };
17336    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17337        unreachable!("normalize_avro_arguments always returns an array");
17338    };
17339    Ok(arguments)
17340}
17341
17342fn decode_update_event_arguments(
17343    event: &HistoryEvent,
17344    fallback_codec: &str,
17345) -> Result<Vec<AvroValue>> {
17346    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17347    validate_payload_codec(codec)?;
17348    let decoded = match event
17349        .payload
17350        .get("arguments")
17351        .filter(|value| !value.is_null())
17352    {
17353        Some(value) => decode_wire_avro_value(value, codec)?,
17354        None => AvroValue::Array(Vec::new()),
17355    };
17356    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17357        unreachable!("normalize_avro_arguments always returns an array");
17358    };
17359    Ok(arguments)
17360}
17361
17362fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17363    let Some(export_events) = task
17364        .history_export
17365        .as_ref()
17366        .and_then(|export| export.get("history_events"))
17367        .and_then(Value::as_array)
17368    else {
17369        return Ok(());
17370    };
17371
17372    if export_events.len() > task.history_events.len() {
17373        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17374    }
17375
17376    Ok(())
17377}
17378
17379fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17380    let Some(export) = task.history_export.as_ref() else {
17381        return Ok(());
17382    };
17383    let signals = export
17384        .get("signals")
17385        .and_then(Value::as_array)
17386        .cloned()
17387        .unwrap_or_default();
17388    let activities = export
17389        .get("activities")
17390        .and_then(Value::as_array)
17391        .cloned()
17392        .unwrap_or_default();
17393    let export_codec = export
17394        .get("payloads")
17395        .and_then(|payloads| payloads.get("codec"))
17396        .and_then(Value::as_str)
17397        .unwrap_or(&task.payload_codec)
17398        .to_string();
17399    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17400
17401    for event in &mut task.history_events {
17402        if event.event_type == "ActivityCompleted" {
17403            let sequence = event
17404                .payload
17405                .get("sequence")
17406                .or_else(|| event.payload.get("workflow_sequence"))
17407                .and_then(value_as_u64);
17408            let Some(activity) = sequence.and_then(|sequence| {
17409                activities.iter().find(|activity| {
17410                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17411                })
17412            }) else {
17413                continue;
17414            };
17415            let Some(payload) = event.payload.as_object_mut() else {
17416                continue;
17417            };
17418            if missing_payload(payload.get("result")) {
17419                if let Some(result) = activity
17420                    .get("result")
17421                    .filter(|value| !missing_payload(Some(value)))
17422                {
17423                    payload.insert("result".to_string(), result.clone());
17424                }
17425            }
17426            for field in ["payload_codec", "activity_type"] {
17427                if payload
17428                    .get(field)
17429                    .and_then(Value::as_str)
17430                    .unwrap_or_default()
17431                    .is_empty()
17432                {
17433                    if let Some(value) = activity.get(field) {
17434                        payload.insert(field.to_string(), value.clone());
17435                    }
17436                }
17437            }
17438            continue;
17439        }
17440
17441        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17442            continue;
17443        }
17444        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17445        let command_id = event
17446            .payload
17447            .get("workflow_command_id")
17448            .or_else(|| event.raw.get("workflow_command_id"))
17449            .and_then(Value::as_str);
17450        let signal_name = event
17451            .payload
17452            .get("signal_name")
17453            .and_then(Value::as_str)
17454            .unwrap_or_default()
17455            .to_string();
17456        let matched = signals
17457            .iter()
17458            .find(|signal| {
17459                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17460            })
17461            .or_else(|| {
17462                signals.iter().find(|signal| {
17463                    command_id.is_some()
17464                        && signal.get("command_id").and_then(Value::as_str) == command_id
17465                })
17466            })
17467            .or_else(|| {
17468                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17469                let signal = signals
17470                    .iter()
17471                    .filter(|signal| {
17472                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17473                    })
17474                    .nth(*offset);
17475                if signal.is_some() {
17476                    *offset += 1;
17477                }
17478                signal
17479            });
17480        let Some(signal) = matched else {
17481            continue;
17482        };
17483        let signal_codec = signal
17484            .get("payload_codec")
17485            .and_then(Value::as_str)
17486            .unwrap_or(&export_codec);
17487        let Some(payload) = event.payload.as_object_mut() else {
17488            continue;
17489        };
17490        if missing_payload(payload.get("arguments")) {
17491            if let Some(arguments) = signal
17492                .get("arguments")
17493                .filter(|value| !missing_payload(Some(value)))
17494            {
17495                let envelope = match arguments {
17496                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17497                    other => other.clone(),
17498                };
17499                payload.insert("arguments".to_string(), envelope);
17500            }
17501        }
17502        if payload
17503            .get("payload_codec")
17504            .and_then(Value::as_str)
17505            .unwrap_or_default()
17506            .is_empty()
17507        {
17508            payload.insert("payload_codec".to_string(), json!(signal_codec));
17509        }
17510    }
17511
17512    Ok(())
17513}
17514
17515fn missing_payload(value: Option<&Value>) -> bool {
17516    match value {
17517        None | Some(Value::Null) => true,
17518        Some(Value::String(value)) => value.is_empty(),
17519        Some(_) => false,
17520    }
17521}
17522
17523fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17524    history_signal_events(
17525        &task.history_events,
17526        task.history_export.as_ref(),
17527        &task.payload_codec,
17528    )
17529}
17530
17531fn history_signal_events(
17532    history_events: &[HistoryEvent],
17533    history_export: Option<&Value>,
17534    payload_codec: &str,
17535) -> Result<Vec<QuerySignal>> {
17536    let export_signals = history_export
17537        .and_then(|export| export.get("signals"))
17538        .and_then(Value::as_array)
17539        .cloned()
17540        .unwrap_or_default();
17541    let export_codec = history_export
17542        .and_then(|export| export.get("payloads"))
17543        .and_then(|payloads| payloads.get("codec"))
17544        .and_then(Value::as_str)
17545        .unwrap_or(payload_codec);
17546    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17547    let mut signals: Vec<QuerySignal> = Vec::new();
17548    let mut signal_indices = HashMap::new();
17549    let mut command_indices = HashMap::new();
17550
17551    for event in history_events {
17552        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17553            continue;
17554        }
17555
17556        let name = event
17557            .payload
17558            .get("signal_name")
17559            .and_then(Value::as_str)
17560            .unwrap_or_default();
17561        if name.is_empty() {
17562            continue;
17563        }
17564        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17565        let command_id = event
17566            .payload
17567            .get("workflow_command_id")
17568            .or_else(|| event.raw.get("workflow_command_id"))
17569            .and_then(Value::as_str);
17570        let matched_export = export_signals
17571            .iter()
17572            .find(|candidate| {
17573                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17574            })
17575            .or_else(|| {
17576                export_signals.iter().find(|candidate| {
17577                    command_id.is_some()
17578                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17579                })
17580            })
17581            .or_else(|| {
17582                let offset = name_offsets.entry(name.to_string()).or_default();
17583                let candidate = export_signals
17584                    .iter()
17585                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17586                    .nth(*offset);
17587                if candidate.is_some() {
17588                    *offset += 1;
17589                }
17590                candidate
17591            });
17592        let codec = event
17593            .payload
17594            .get("payload_codec")
17595            .and_then(Value::as_str)
17596            .or_else(|| {
17597                matched_export
17598                    .and_then(|signal| signal.get("payload_codec"))
17599                    .and_then(Value::as_str)
17600            })
17601            .unwrap_or(export_codec);
17602        let raw_arguments = signal_history_payload(&event.payload)
17603            .filter(|value| !value.is_null())
17604            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17605        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17606        let workflow_sequence = event
17607            .payload
17608            .get("workflow_sequence")
17609            .and_then(value_as_u64)
17610            .or_else(|| {
17611                matched_export
17612                    .and_then(|signal| signal.get("workflow_sequence"))
17613                    .and_then(value_as_u64)
17614            });
17615
17616        let id = signal_id.or_else(|| {
17617            matched_export
17618                .and_then(|signal| signal.get("id"))
17619                .and_then(Value::as_str)
17620        });
17621        let command_id = command_id.or_else(|| {
17622            matched_export
17623                .and_then(|signal| signal.get("command_id"))
17624                .and_then(Value::as_str)
17625        });
17626        let duplicate = id
17627            .and_then(|id| signal_indices.get(id))
17628            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17629            .copied();
17630        let index = duplicate.unwrap_or(signals.len());
17631        if let Some(index) = duplicate {
17632            let original = &mut signals[index];
17633            let same_arguments = if event.event_type == "SignalApplied" {
17634                if let Some(value) = event.payload.get("value") {
17635                    let expected = match original.avro_arguments.as_slice() {
17636                        [] => AvroValue::Boolean(true),
17637                        [value] => value.clone(),
17638                        values => AvroValue::Array(values.to_vec()),
17639                    };
17640                    let applied = decode_wire_avro_value(value, codec)?;
17641                    applied == expected
17642                        || applied == AvroValue::Array(original.avro_arguments.clone())
17643                } else {
17644                    original.avro_arguments == avro_arguments
17645                }
17646            } else {
17647                original.avro_arguments == avro_arguments
17648            };
17649            if original.name != name
17650                || !same_arguments
17651                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17652            {
17653                return Err(Error::Codec("conflicting committed signal identity".into()));
17654            }
17655            if original.id.is_none() {
17656                original.id = id.map(str::to_string);
17657            }
17658            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17659        } else {
17660            signals.push(QuerySignal {
17661                id: id.map(str::to_string),
17662                name: name.to_string(),
17663                arguments,
17664                avro_arguments,
17665                workflow_sequence,
17666            });
17667        }
17668        if let Some(id) = id {
17669            signal_indices.insert(id.to_string(), index);
17670        }
17671        if let Some(id) = command_id {
17672            command_indices.insert(id.to_string(), index);
17673        }
17674    }
17675
17676    if signals.is_empty() {
17677        for signal in export_signals {
17678            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17679                continue;
17680            }
17681            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17682                continue;
17683            };
17684            let codec = signal
17685                .get("payload_codec")
17686                .and_then(Value::as_str)
17687                .unwrap_or(export_codec);
17688            let (arguments, avro_arguments) =
17689                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17690            signals.push(QuerySignal {
17691                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17692                name: name.to_string(),
17693                arguments,
17694                avro_arguments,
17695                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17696            });
17697        }
17698        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17699    }
17700
17701    Ok(signals)
17702}
17703
17704fn decode_query_signal_arguments(
17705    raw: Option<&Value>,
17706    codec: &str,
17707) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17708    validate_payload_codec(codec)?;
17709    let decoded = match raw.filter(|value| !value.is_null()) {
17710        Some(value) => decode_wire_avro_value(value, codec)?,
17711        None => AvroValue::Array(Vec::new()),
17712    };
17713    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17714        unreachable!("normalize_avro_arguments always returns an array");
17715    };
17716    let arguments = avro_arguments
17717        .iter()
17718        .cloned()
17719        .map(AvroValue::into_json)
17720        .collect::<Result<Vec<_>>>()?;
17721    Ok((arguments, avro_arguments))
17722}
17723
17724fn value_as_u64(value: &Value) -> Option<u64> {
17725    value
17726        .as_u64()
17727        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17728}
17729
17730#[cfg(test)]
17731mod tests {
17732    use super::*;
17733    mod activity_cancellation_policies;
17734    mod cancellation_scope_admission;
17735    mod cancellation_scope_authoring;
17736    mod cancellation_scope_history;
17737    mod cancellation_scope_opening;
17738    mod cancellation_scope_replay;
17739    mod child_workflow_policies;
17740    mod cooperative_cancellation;
17741    mod local_activity;
17742    mod runtime_payloads;
17743    mod runtime_uploads;
17744    mod version_marker_contract;
17745    mod worker_session;
17746    use std::{
17747        fs,
17748        io::{Read, Write},
17749        net::{SocketAddr, TcpListener, TcpStream},
17750        process::Command as ProcessCommand,
17751        sync::atomic::AtomicUsize,
17752        thread,
17753    };
17754
17755    #[derive(Clone, Copy, Debug)]
17756    enum InvalidTaskPayloadCodec {
17757        Missing,
17758        Null,
17759        NonString,
17760    }
17761
17762    impl InvalidTaskPayloadCodec {
17763        fn label(self) -> &'static str {
17764            match self {
17765                Self::Missing => "missing",
17766                Self::Null => "null",
17767                Self::NonString => "non-string",
17768            }
17769        }
17770
17771        fn apply(self, task: &mut Value) {
17772            let task = task.as_object_mut().expect("task fixture object");
17773            match self {
17774                Self::Missing => {
17775                    task.remove("payload_codec");
17776                }
17777                Self::Null => {
17778                    task.insert("payload_codec".to_string(), Value::Null);
17779                }
17780                Self::NonString => {
17781                    task.insert("payload_codec".to_string(), json!(42));
17782                }
17783            }
17784        }
17785    }
17786
17787    fn fixture_envelope(value: Value) -> Value {
17788        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17789    }
17790
17791    fn fixture_blob(value: Value) -> String {
17792        encode_payload(&value, DEFAULT_CODEC)
17793            .expect("encode Avro test fixture")
17794            .blob
17795    }
17796
17797    #[test]
17798    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17799        for base_url in [
17800            "http://127.0.0.1:8080/api",
17801            "http://localhost:8080/api/",
17802            "https://runtime.example.test/namespaces/orders/api",
17803        ] {
17804            let error = Client::builder(base_url)
17805                .build()
17806                .expect_err("SDK-owned /api suffix must be rejected during build");
17807
17808            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17809            assert!(
17810                error.to_string().contains("SDK appends /api automatically"),
17811                "the validation error must explain how to fix the endpoint"
17812            );
17813        }
17814    }
17815
17816    #[test]
17817    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17818        for (base_url, expected) in [
17819            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17820            (
17821                "http://localhost:8080/durable-workflow/",
17822                "http://localhost:8080/durable-workflow",
17823            ),
17824            (
17825                "https://runtime.example.test/namespaces/orders",
17826                "https://runtime.example.test/namespaces/orders",
17827            ),
17828            (
17829                "https://runtime.example.test/gateway/api/namespaces/orders",
17830                "https://runtime.example.test/gateway/api/namespaces/orders",
17831            ),
17832            (
17833                "https://api.example.test/runtime/orders/",
17834                "https://api.example.test/runtime/orders",
17835            ),
17836        ] {
17837            let client = Client::builder(base_url)
17838                .build()
17839                .expect("Server and Cloud runtime base URL must remain valid");
17840
17841            assert_eq!(client.base_url, expected);
17842        }
17843    }
17844
17845    #[test]
17846    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17847        assert_eq!(
17848            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17849            MINIMUM_WORKER_PROTOCOL_VERSION
17850        );
17851        assert_eq!(
17852            workflow_completion_protocol_version(&[json!({
17853                "type": "upsert_search_attributes",
17854                "attributes": {"OrderStatus": "waiting"},
17855            })]),
17856            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17857        );
17858        assert_eq!(
17859            workflow_completion_protocol_version(&[json!({
17860                "type": "upsert_search_attributes",
17861                "attributes": {"OrderStatus": "waiting"},
17862                "attribute_types": {"OrderStatus": "keyword"},
17863            })]),
17864            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17865        );
17866        assert_eq!(
17867            workflow_completion_protocol_version(&[
17868                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17869                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17870            ]),
17871            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17872        );
17873        assert_eq!(
17874            workflow_completion_protocol_version(&[
17875                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17876                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17877            ]),
17878            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17879        );
17880        assert_eq!(
17881            workflow_completion_protocol_version(&[json!({
17882                "type": "open_condition_wait",
17883                "condition_wait_occurrence_id": "rust:condition-wait:0",
17884                "condition_key": "ready",
17885            })]),
17886            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17887        );
17888        assert_eq!(
17889            workflow_completion_protocol_version_with_message_streams(
17890                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17891                true,
17892            ),
17893            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17894        );
17895        assert_eq!(
17896            workflow_completion_protocol_version_with_message_streams(
17897                &[json!({
17898                    "type": "open_condition_wait",
17899                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17900                    "condition_key": "ready",
17901                })],
17902                true,
17903            ),
17904            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17905        );
17906    }
17907
17908    #[test]
17909    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17910        let manifest = portable_worker_affinity_capability_manifest();
17911
17912        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17913            assert_eq!(manifest[capability]["supported"], json!(false));
17914            assert_eq!(
17915                manifest[capability]["minimum_protocol_version"],
17916                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17917            );
17918            assert!(manifest[capability]["reason"]
17919                .as_str()
17920                .is_some_and(|reason| !reason.is_empty()));
17921        }
17922    }
17923
17924    fn typed_fidelity_probe() -> AvroValue {
17925        AvroValue::Map(BTreeMap::from([
17926            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17927            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17928            (
17929                "numeric".to_string(),
17930                AvroValue::Map(BTreeMap::from([
17931                    ("0".to_string(), AvroValue::String("zero".to_string())),
17932                    ("1".to_string(), AvroValue::String("one".to_string())),
17933                ])),
17934            ),
17935            (
17936                "nested".to_string(),
17937                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17938                    "enabled".to_string(),
17939                    AvroValue::Boolean(true),
17940                )]))]),
17941            ),
17942            (
17943                "projection_collisions".to_string(),
17944                AvroValue::Array(projection_collision_probe()),
17945            ),
17946        ]))
17947    }
17948
17949    fn projection_collision_probe() -> Vec<AvroValue> {
17950        vec![
17951            AvroValue::Map(BTreeMap::from([
17952                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17953                (
17954                    "base64".to_string(),
17955                    AvroValue::String("ordinary user text".to_string()),
17956                ),
17957            ])),
17958            AvroValue::Map(BTreeMap::from([
17959                ("$type".to_string(), AvroValue::String("map".to_string())),
17960                (
17961                    "entries".to_string(),
17962                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17963                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17964                        (
17965                            "value".to_string(),
17966                            AvroValue::String("user map".to_string()),
17967                        ),
17968                    ]))]),
17969                ),
17970            ])),
17971        ]
17972    }
17973
17974    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17975    struct TypedContract {
17976        nested: TypedNested,
17977        mode: TypedMode,
17978        optional: Option<String>,
17979        absent: Option<String>,
17980        items: Vec<i64>,
17981        labels: BTreeMap<String, String>,
17982        bytes: serde_bytes::ByteBuf,
17983        signed: i64,
17984        finite: f64,
17985    }
17986
17987    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17988    struct TypedNested {
17989        enabled: bool,
17990    }
17991
17992    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17993    enum TypedMode {
17994        Detailed { label: String },
17995    }
17996
17997    fn typed_contract() -> TypedContract {
17998        TypedContract {
17999            nested: TypedNested { enabled: true },
18000            mode: TypedMode::Detailed {
18001                label: "compiler-checked".to_string(),
18002            },
18003            optional: Some("present".to_string()),
18004            absent: None,
18005            items: vec![i64::MIN, 0, i64::MAX],
18006            labels: BTreeMap::from([
18007                ("language".to_string(), "rust".to_string()),
18008                ("wire".to_string(), "avro".to_string()),
18009            ]),
18010            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
18011            signed: -9_223_372_036_854_775_000,
18012            finite: 12.5,
18013        }
18014    }
18015
18016    #[derive(Clone, Debug, Default, PartialEq)]
18017    struct ReplayCounterState {
18018        loaded: Option<String>,
18019        count: i64,
18020        finished: bool,
18021    }
18022
18023    fn replay_counter_worker() -> Worker {
18024        let client = Client::new("http://127.0.0.1:8080").expect("client");
18025        let mut worker = Worker::new(client, "rust-workers");
18026        worker.register_replayed_workflow(
18027            "replay-counter",
18028            ReplayCounterState::default,
18029            |ctx, _input, state| async move {
18030                let loaded = ctx.activity("load-counter", json!([])).await?;
18031                state.update(|current| {
18032                    current.loaded = loaded.as_str().map(str::to_string);
18033                })?;
18034                for _ in 0..2 {
18035                    let signal = ctx.wait_signal("increment").await?;
18036                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18037                    state.update(|current| current.count += amount)?;
18038                }
18039                state.update(|current| current.finished = true)?;
18040                state.read(|current| Ok(json!(current.count)))?
18041            },
18042        );
18043        worker.register_replayed_query::<ReplayCounterState, _, _>(
18044            "replay-counter",
18045            "current",
18046            |_ctx, state, _args| async move {
18047                Ok(json!({
18048                    "loaded": state.loaded,
18049                    "count": state.count,
18050                    "finished": state.finished,
18051                }))
18052            },
18053        );
18054        worker.register_replayed_query::<ReplayCounterState, _, _>(
18055            "replay-counter",
18056            "detached-mutation",
18057            |_ctx, state, _args| async move {
18058                let mut detached = (*state).clone();
18059                detached.count = 999;
18060                Ok(json!(detached.count))
18061            },
18062        );
18063        worker.register_replayed_query::<ReplayCounterState, _, _>(
18064            "replay-counter",
18065            "failed-mutation",
18066            |_ctx, state, _args| async move {
18067                let mut detached = (*state).clone();
18068                detached.count = 999;
18069                Err(Error::WorkerLoop("query refused".to_string()))
18070            },
18071        );
18072        worker
18073    }
18074
18075    fn replay_counter_query(
18076        query_name: &str,
18077        history_events: Value,
18078        run_status: &str,
18079    ) -> QueryTask {
18080        let arguments = fixture_envelope(json!([]));
18081        serde_json::from_value(json!({
18082            "query_task_id": format!("query-{query_name}"),
18083            "workflow_type": "replay-counter",
18084            "query_name": query_name,
18085            "payload_codec": DEFAULT_CODEC,
18086            "workflow_arguments": arguments.clone(),
18087            "query_arguments": arguments,
18088            "history_events": history_events,
18089            "run_status": run_status,
18090        }))
18091        .expect("query task")
18092    }
18093
18094    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18095        workflow_context_with_codec(history, DEFAULT_CODEC)
18096    }
18097
18098    fn workflow_context_with_codec(
18099        history: Vec<HistoryEvent>,
18100        payload_codec: &str,
18101    ) -> WorkflowContext {
18102        WorkflowContext {
18103            cancellation_scope_id: "root".into(),
18104            state: Arc::new(Mutex::new(
18105                WorkflowState::new_with_identity(
18106                    history,
18107                    None,
18108                    None,
18109                    "rust-workers".to_string(),
18110                    payload_codec.to_string(),
18111                    None,
18112                )
18113                .expect("valid workflow history"),
18114            )),
18115        }
18116    }
18117
18118    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18119        HistoryEvent {
18120            event_type: event_type.to_string(),
18121            payload,
18122            raw: HashMap::new(),
18123        }
18124    }
18125
18126    fn parallel_path_entry(
18127        kind: &str,
18128        base: u64,
18129        size: usize,
18130        index: usize,
18131    ) -> ParallelGroupMetadata {
18132        parallel_group_entry(base, size, index, kind)
18133    }
18134
18135    fn parallel_history_event(
18136        event_type: &str,
18137        sequence: u64,
18138        identity_field: &str,
18139        identity: &str,
18140        path: Vec<ParallelGroupMetadata>,
18141        result: Option<Value>,
18142    ) -> HistoryEvent {
18143        let mut payload = serde_json::Map::from_iter([
18144            ("sequence".to_string(), json!(sequence)),
18145            (identity_field.to_string(), json!(identity)),
18146        ]);
18147        let inner = path.last().expect("parallel history path");
18148        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18149        payload.insert("parallel_group_path".to_string(), json!(path));
18150        if let Some(result) = result {
18151            let field = if event_type == "ChildRunCompleted" {
18152                "result"
18153            } else {
18154                "result"
18155            };
18156            payload.insert(field.to_string(), fixture_envelope(result));
18157            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18158        }
18159        history_event(event_type, Value::Object(payload))
18160    }
18161
18162    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18163        vec![
18164            ParallelOperation::activity("first", json!([])),
18165            ParallelOperation::group(vec![
18166                ParallelOperation::child_workflow(
18167                    "second",
18168                    ChildWorkflowOptions::new("child-workers"),
18169                    json!([]),
18170                ),
18171                ParallelOperation::activity("third", json!([])),
18172            ]),
18173        ]
18174    }
18175
18176    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18177        let outer = [
18178            parallel_path_entry("mixed", 1, 3, 0),
18179            parallel_path_entry("mixed", 1, 3, 1),
18180            parallel_path_entry("mixed", 1, 3, 2),
18181        ];
18182        [
18183            vec![outer[0].clone()],
18184            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18185            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18186        ]
18187    }
18188
18189    #[test]
18190    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18191        let ctx = workflow_context(Vec::new());
18192        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18193        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18194
18195        assert!(matches!(
18196            call.as_mut().poll(&mut task_context),
18197            Poll::Pending
18198        ));
18199        let commands = ctx.take_commands().expect("parallel commands");
18200        assert_eq!(
18201            commands
18202                .iter()
18203                .map(|command| command["type"].as_str().unwrap_or_default())
18204                .collect::<Vec<_>>(),
18205            [
18206                "schedule_activity",
18207                "start_child_workflow",
18208                "schedule_activity"
18209            ]
18210        );
18211        let paths = nested_parallel_paths();
18212        for (command, path) in commands.iter().zip(paths) {
18213            assert_eq!(command["parallel_group_path"], json!(path));
18214            assert_eq!(
18215                command["parallel_group_id"],
18216                json!(path.last().expect("inner group").parallel_group_id)
18217            );
18218        }
18219    }
18220
18221    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18222        let paths = nested_parallel_paths();
18223        let third = parallel_history_event(
18224            "ActivityCompleted",
18225            3,
18226            "activity_type",
18227            "third",
18228            paths[2].clone(),
18229            Some(json!("three")),
18230        );
18231        vec![
18232            parallel_history_event(
18233                "ActivityCompleted",
18234                1,
18235                "activity_type",
18236                "first",
18237                paths[0].clone(),
18238                Some(json!("one")),
18239            ),
18240            parallel_history_event(
18241                "ChildWorkflowScheduled",
18242                2,
18243                "child_workflow_type",
18244                "second",
18245                paths[1].clone(),
18246                None,
18247            ),
18248            parallel_history_event(
18249                "ChildRunCompleted",
18250                2,
18251                "child_workflow_type",
18252                "second",
18253                paths[1].clone(),
18254                Some(json!("two")),
18255            ),
18256            third.clone(),
18257            third,
18258        ]
18259    }
18260
18261    #[test]
18262    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18263        for _restart_or_completed_replay in 0..2 {
18264            let ctx = workflow_context(completed_nested_parallel_history());
18265            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18266            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18267            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18268                panic!("completed nested parallel history must replay");
18269            };
18270            assert_eq!(
18271                results,
18272                vec![
18273                    ParallelResult::Activity(json!("one")),
18274                    ParallelResult::Group(vec![
18275                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18276                            parent: WorkflowIdentity {
18277                                workflow_id: None,
18278                                run_id: None,
18279                            },
18280                            child: WorkflowIdentity {
18281                                workflow_id: None,
18282                                run_id: None,
18283                            },
18284                            child_workflow_type: Some("second".to_string()),
18285                            result: json!("two"),
18286                        }),
18287                        ParallelResult::Activity(json!("three")),
18288                    ]),
18289                ]
18290            );
18291            assert!(ctx.take_commands().expect("commands").is_empty());
18292            ctx.ensure_history_consumed().expect("history consumed");
18293        }
18294    }
18295
18296    #[test]
18297    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18298        let paths = nested_parallel_paths();
18299        let history = vec![
18300            parallel_history_event(
18301                "ActivityCompleted",
18302                1,
18303                "activity_type",
18304                "first",
18305                paths[0].clone(),
18306                Some(json!("one")),
18307            ),
18308            parallel_history_event(
18309                "ChildWorkflowScheduled",
18310                2,
18311                "child_workflow_type",
18312                "second",
18313                paths[1].clone(),
18314                None,
18315            ),
18316            parallel_history_event(
18317                "ChildRunFailed",
18318                2,
18319                "child_workflow_type",
18320                "second",
18321                paths[1].clone(),
18322                None,
18323            ),
18324            parallel_history_event(
18325                "ActivityCompleted",
18326                3,
18327                "activity_type",
18328                "third",
18329                paths[2].clone(),
18330                Some(json!("late")),
18331            ),
18332        ];
18333        let ctx = workflow_context(history);
18334        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18335        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18336        let outcome = call.as_mut().poll(&mut task_context);
18337        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18338            panic!("one failed child must return a typed partial failure: {outcome:?}");
18339        };
18340        assert_eq!(failure.member_path, [1, 0]);
18341        assert_eq!(failure.group_id, "parallel-calls:1:3");
18342        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18343        assert_eq!(
18344            failure
18345                .completed
18346                .iter()
18347                .map(|completion| completion.member_path.clone())
18348                .collect::<Vec<_>>(),
18349            [vec![0], vec![1, 1]]
18350        );
18351    }
18352
18353    #[test]
18354    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18355        let paths = nested_parallel_paths();
18356        let history = vec![
18357            parallel_history_event(
18358                "ActivityScheduled",
18359                1,
18360                "activity_type",
18361                "first",
18362                paths[0].clone(),
18363                None,
18364            ),
18365            parallel_history_event(
18366                "ChildWorkflowScheduled",
18367                2,
18368                "child_workflow_type",
18369                "second",
18370                paths[1].clone(),
18371                None,
18372            ),
18373            parallel_history_event(
18374                "ActivityScheduled",
18375                3,
18376                "activity_type",
18377                "third",
18378                paths[2].clone(),
18379                None,
18380            ),
18381        ];
18382        for _restart in 0..2 {
18383            let ctx = workflow_context(history.clone());
18384            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18385            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18386            let outcome = call.as_mut().poll(&mut task_context);
18387            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18388            assert!(ctx.take_commands().expect("commands").is_empty());
18389        }
18390    }
18391
18392    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18393        vec![selection_group_entry(
18394            1,
18395            2,
18396            index,
18397            "activity",
18398            &SelectionMemberMetadata {
18399                key: SelectionKey::Name(key.to_string()),
18400                index,
18401                base_sequence: index as u64 + 1,
18402                size: 1,
18403                kind: "activity".to_string(),
18404            },
18405        )]
18406    }
18407
18408    fn selection_activity_event(
18409        event_type: &str,
18410        index: usize,
18411        key: &str,
18412        result: Option<Value>,
18413    ) -> HistoryEvent {
18414        let sequence = index as u64 + 1;
18415        let mut event = parallel_history_event(
18416            event_type,
18417            sequence,
18418            "activity_type",
18419            &format!("{key}-activity"),
18420            selection_path(index, key),
18421            result,
18422        );
18423        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18424        event.raw.insert(
18425            "id".to_string(),
18426            json!(if event_type == "ActivityCompleted" {
18427                format!("event-{key}")
18428            } else {
18429                format!("{event_type}-{key}")
18430            }),
18431        );
18432        event
18433    }
18434
18435    fn selection_winner_marker() -> HistoryEvent {
18436        history_event(
18437            "SelectionResolved",
18438            json!({
18439                "selection_group_id": "select-calls:1:2",
18440                "selection_group_base_sequence": 1,
18441                "selection_group_size": 2,
18442                "member_key": "fast",
18443                "member_index": 1,
18444                "member_base_sequence": 2,
18445                "member_size": 1,
18446                "operation_kind": "activity",
18447                "operation_identity": "activity-fast",
18448                "outcome": "completed",
18449                "resolution_event_id": "event-fast",
18450                "resolution_event_type": "ActivityCompleted",
18451            }),
18452        )
18453    }
18454
18455    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18456        ctx.select_keyed(vec![
18457            (
18458                "slow",
18459                ParallelOperation::activity_with_options(
18460                    "slow-activity",
18461                    ActivityOptions::new().task_queue("default"),
18462                    json!([]),
18463                ),
18464            ),
18465            (
18466                "fast",
18467                ParallelOperation::activity_with_options(
18468                    "fast-activity",
18469                    ActivityOptions::new().task_queue("default"),
18470                    json!([]),
18471                ),
18472            ),
18473        ])
18474    }
18475
18476    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18477        let ctx = workflow_context(history);
18478        let mut call = Box::pin(keyed_activity_selection(&ctx));
18479        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18480        let selected = match call.as_mut().poll(&mut task_context) {
18481            Poll::Ready(Ok(selected)) => selected,
18482            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18483            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18484        };
18485        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18486        assert_eq!(
18487            selected.value,
18488            Some(ParallelResult::Activity(json!("winner-value")))
18489        );
18490        let slow = selected
18491            .handle(&SelectionKey::Name("slow".to_string()))
18492            .expect("slow handle")
18493            .clone();
18494        let mut await_slow = Box::pin(slow.await_result());
18495        assert!(matches!(
18496            await_slow.as_mut().poll(&mut task_context),
18497            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18498        ));
18499        assert!(ctx.take_commands().expect("commands").is_empty());
18500    }
18501
18502    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18503
18504    fn canonical_selection_history() -> Vec<HistoryEvent> {
18505        const FIXTURE: &[u8] =
18506            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18507        assert_eq!(
18508            format!("{:x}", Sha256::digest(FIXTURE)),
18509            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18510        );
18511        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18512
18513        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18514    }
18515
18516    #[test]
18517    fn selection_fresh_process_entrypoint() {
18518        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18519            return;
18520        };
18521        let persisted = fs::read(path).expect("persisted selection history");
18522        assert_eq!(
18523            format!("{:x}", Sha256::digest(&persisted)),
18524            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18525        );
18526        let fixture: Value =
18527            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18528        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18529            .expect("valid persisted selection history");
18530
18531        assert_persisted_selection_replay(history);
18532    }
18533
18534    #[test]
18535    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18536        let ctx = workflow_context(Vec::new());
18537        let mut call = Box::pin(keyed_activity_selection(&ctx));
18538        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18539
18540        assert!(matches!(
18541            call.as_mut().poll(&mut task_context),
18542            Poll::Pending
18543        ));
18544        let commands = ctx.take_commands().expect("selection commands");
18545        assert_eq!(commands.len(), 2);
18546        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18547        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18548        assert!(commands.iter().all(|command| {
18549            command["parallel_group_id"] == json!("select-calls:1:2")
18550                && command["parallel_group_mode"] == json!("select")
18551        }));
18552    }
18553
18554    #[test]
18555    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18556        let ctx = workflow_context(Vec::new());
18557        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18558            "",
18559            ParallelOperation::activity("invalid", json!([])),
18560        )]));
18561        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18562        assert!(matches!(
18563            invalid.as_mut().poll(&mut task_context),
18564            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18565                reason: "selection_key_invalid",
18566                ..
18567            })))
18568        ));
18569
18570        for invalid_key in [json!(""), json!(-1)] {
18571            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18572            event.payload["selection_member_key"] = invalid_key.clone();
18573            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18574            assert!(matches!(
18575                WorkflowState::new_with_identity(
18576                    vec![event],
18577                    None,
18578                    None,
18579                    "rust-workers".to_string(),
18580                    DEFAULT_CODEC.to_string(),
18581                    None,
18582                ),
18583                Err(Error::NonDeterministicReplay(_))
18584            ));
18585        }
18586    }
18587
18588    #[test]
18589    fn selection_preserves_valid_named_and_numeric_keys() {
18590        let ctx = workflow_context(Vec::new());
18591        let mut selection = Box::pin(ctx.select_keyed(vec![
18592            (
18593                SelectionKey::Index(0),
18594                ParallelOperation::activity("numeric", json!([])),
18595            ),
18596            (
18597                SelectionKey::Name("named".to_string()),
18598                ParallelOperation::timer(Duration::from_secs(1)),
18599            ),
18600        ]));
18601        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18602
18603        assert!(matches!(
18604            selection.as_mut().poll(&mut task_context),
18605            Poll::Pending
18606        ));
18607        let commands = ctx.take_commands().expect("selection commands");
18608        assert_eq!(commands[0]["selection_member_key"], json!(0));
18609        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18610    }
18611
18612    #[test]
18613    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18614        let history = canonical_selection_history();
18615        assert_persisted_selection_replay(history.clone());
18616
18617        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18618            .join("tests/fixtures/durable_selection_runtime_history.json");
18619        let output =
18620            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18621                .args([
18622                    "--exact",
18623                    "tests::selection_fresh_process_entrypoint",
18624                    "--nocapture",
18625                ])
18626                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18627                .output()
18628                .expect("run fresh selection replay process");
18629
18630        assert!(
18631            output.status.success(),
18632            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18633            String::from_utf8_lossy(&output.stdout),
18634            String::from_utf8_lossy(&output.stderr),
18635        );
18636    }
18637
18638    #[test]
18639    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18640        let mut history = canonical_selection_history();
18641        history.retain(|event| event.event_type != "SelectionResolved");
18642        let ctx = workflow_context(history);
18643        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18644        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18645
18646        assert!(matches!(
18647            selection.as_mut().poll(&mut task_context),
18648            Poll::Pending
18649        ));
18650        assert!(ctx.take_commands().expect("commands").is_empty());
18651        assert!(
18652            ctx.matched_recorded_pending()
18653                .expect("selection pending state"),
18654            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18655        );
18656    }
18657
18658    #[test]
18659    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18660        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18661            ("ConditionWaitSatisfied", true, None),
18662            ("ConditionWaitTimedOut", false, Some(0)),
18663        ] {
18664            let member = SelectionMemberMetadata {
18665                key: SelectionKey::Name("condition".to_string()),
18666                index: 0,
18667                base_sequence: 1,
18668                size: 1,
18669                kind: "condition".to_string(),
18670            };
18671            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18672            let mut payload = json!({
18673                "sequence": 1,
18674                "condition_wait_id": "condition-1",
18675                "condition_wait_occurrence_id": "rust:condition-wait:0",
18676                "condition_key": "ready",
18677                "condition_definition_fingerprint": "sha256:ready-v1",
18678                "parallel_group_path": path,
18679            });
18680            payload
18681                .as_object_mut()
18682                .expect("condition history payload")
18683                .extend(
18684                    serde_json::to_value(&path[0])
18685                        .expect("condition selection metadata")
18686                        .as_object()
18687                        .expect("condition selection metadata object")
18688                        .clone(),
18689                );
18690            if let Some(timeout_seconds) = timeout_seconds {
18691                payload["timeout_seconds"] = json!(timeout_seconds);
18692            }
18693            let history = vec![
18694                history_event("ConditionWaitOpened", payload.clone()),
18695                history_event(terminal_event, payload),
18696            ];
18697            let ctx = workflow_context(history);
18698            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18699            if timeout_seconds.is_some() {
18700                options = options.timeout(Duration::ZERO);
18701            }
18702            let mut selection = Box::pin(ctx.select_keyed(vec![(
18703                "condition",
18704                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18705            )]));
18706            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18707
18708            assert!(matches!(
18709                selection.as_mut().poll(&mut task_context),
18710                Poll::Pending
18711            ));
18712            assert!(ctx.take_commands().expect("commands").is_empty());
18713            assert!(
18714                ctx.matched_recorded_pending()
18715                    .expect("condition selection pending state"),
18716                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18717            );
18718        }
18719    }
18720
18721    #[test]
18722    fn selection_immediate_condition_members_open_a_durable_wait() {
18723        for predicate_satisfied in [true, false] {
18724            let ctx = workflow_context(Vec::new());
18725            let mut selection = Box::pin(ctx.select_keyed(vec![(
18726                "condition",
18727                ParallelOperation::condition(
18728                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18729                    move || Ok(predicate_satisfied),
18730                ),
18731            )]));
18732            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18733
18734            assert!(matches!(
18735                selection.as_mut().poll(&mut task_context),
18736                Poll::Pending
18737            ));
18738            let commands = ctx.take_commands().expect("condition selection command");
18739            assert_eq!(commands.len(), 1);
18740            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18741            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18742            assert_eq!(
18743                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18744                json!("select")
18745            );
18746        }
18747    }
18748
18749    #[test]
18750    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18751        let history = vec![
18752            selection_activity_event("ActivityScheduled", 0, "slow", None),
18753            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18754            selection_winner_marker(),
18755        ];
18756        let ctx = workflow_context(history.clone());
18757        let mut call = Box::pin(keyed_activity_selection(&ctx));
18758        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18759        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18760            panic!("winner must replay");
18761        };
18762        let slow = selected
18763            .handle(&SelectionKey::Name("slow".to_string()))
18764            .expect("slow handle")
18765            .clone();
18766        let mut cancel = Box::pin(slow.cancel());
18767        assert!(matches!(
18768            cancel.as_mut().poll(&mut task_context),
18769            Poll::Pending
18770        ));
18771        assert!(matches!(
18772            cancel.as_mut().poll(&mut task_context),
18773            Poll::Pending
18774        ));
18775        let commands = ctx.take_commands().expect("cancel command");
18776        assert_eq!(commands.len(), 1);
18777        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18778        assert_eq!(commands[0]["member_key"], json!("slow"));
18779
18780        let mut cancelled_history = history;
18781        cancelled_history.push(history_event(
18782            "SelectionOperationCancelled",
18783            json!({
18784                "selection_group_id": "select-calls:1:2",
18785                "member_key": "slow",
18786                "member_index": 0,
18787                "member_base_sequence": 1,
18788                "member_size": 1,
18789                "operation_kind": "activity",
18790                "operation_identity": "activity-slow",
18791                "cancelled_at": "2026-08-27T00:00:00Z",
18792            }),
18793        ));
18794        let replayed = workflow_context(cancelled_history);
18795        let mut call = Box::pin(keyed_activity_selection(&replayed));
18796        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18797            panic!("winner must replay after cancellation");
18798        };
18799        let slow = selected
18800            .handle(&SelectionKey::Name("slow".to_string()))
18801            .expect("slow handle")
18802            .clone();
18803        let mut cancel = Box::pin(slow.cancel());
18804        assert!(matches!(
18805            cancel.as_mut().poll(&mut task_context),
18806            Poll::Ready(Ok(()))
18807        ));
18808        assert!(replayed.take_commands().expect("commands").is_empty());
18809    }
18810
18811    #[test]
18812    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18813        let base_history = vec![
18814            selection_activity_event("ActivityScheduled", 0, "slow", None),
18815            selection_activity_event("ActivityScheduled", 1, "fast", None),
18816            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18817            selection_winner_marker(),
18818        ];
18819        for (field, corrupt) in [
18820            ("member_key", json!("fast")),
18821            ("member_index", json!(1)),
18822            ("member_base_sequence", json!(3)),
18823            ("member_size", json!(2)),
18824            ("operation_kind", json!("timer")),
18825            ("operation_identity", json!("forged")),
18826        ] {
18827            let mut cancellation = json!({
18828                "selection_group_id": "select-calls:1:2",
18829                "member_key": "slow",
18830                "member_index": 0,
18831                "member_base_sequence": 1,
18832                "member_size": 1,
18833                "operation_kind": "activity",
18834                "operation_identity": "activity-slow",
18835            });
18836            cancellation[field] = corrupt;
18837            let mut history = base_history.clone();
18838            history.push(history_event("SelectionOperationCancelled", cancellation));
18839            let ctx = workflow_context(history);
18840            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18841            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18842
18843            assert!(matches!(
18844                selection.as_mut().poll(&mut task_context),
18845                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18846            ));
18847        }
18848    }
18849
18850    #[test]
18851    fn selection_child_identity_prefers_the_durable_run_id() {
18852        let ctx = workflow_context(vec![history_event(
18853            "ChildWorkflowScheduled",
18854            json!({
18855                "sequence": 1,
18856                "child_workflow_type": "child",
18857                "child_workflow_instance_id": "child-instance",
18858                "child_workflow_run_id": "child-run",
18859            }),
18860        )]);
18861        let state = ctx.state.lock().expect("workflow state");
18862
18863        assert_eq!(
18864            selection_operation_identity(&state, "child", 1, 1),
18865            "child-run"
18866        );
18867    }
18868
18869    #[test]
18870    fn selection_activity_identity_requires_canonical_execution_id() {
18871        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18872        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18873        let mut fast_completed =
18874            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18875        for event in [&mut fast_open, &mut fast_completed] {
18876            event
18877                .payload
18878                .as_object_mut()
18879                .expect("activity payload")
18880                .remove("activity_execution_id");
18881            event.payload["activity_id"] = json!("forged-activity-id");
18882        }
18883        let mut marker = selection_winner_marker();
18884        marker.payload["operation_identity"] = json!("forged-activity-id");
18885        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18886        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18887        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18888
18889        assert!(matches!(
18890            selection.as_mut().poll(&mut task_context),
18891            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18892        ));
18893    }
18894
18895    #[test]
18896    fn selection_completion_before_cancellation_remains_awaitable() {
18897        let history = vec![
18898            selection_activity_event("ActivityScheduled", 0, "slow", None),
18899            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18900            selection_winner_marker(),
18901            selection_activity_event(
18902                "ActivityCompleted",
18903                0,
18904                "slow",
18905                Some(json!("completed-first")),
18906            ),
18907        ];
18908        let ctx = workflow_context(history);
18909        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18910        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18911        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18912            panic!("winner must replay");
18913        };
18914        let slow = selected
18915            .handle(&SelectionKey::Name("slow".to_string()))
18916            .expect("slow handle")
18917            .clone();
18918        let mut cancel = Box::pin(slow.cancel());
18919        assert!(matches!(
18920            cancel.as_mut().poll(&mut task_context),
18921            Poll::Ready(Ok(()))
18922        ));
18923        let mut await_slow = Box::pin(slow.await_result());
18924        assert!(matches!(
18925            await_slow.as_mut().poll(&mut task_context),
18926            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18927        ));
18928        let commands = ctx.take_commands().expect("commands");
18929        assert!(commands.is_empty());
18930    }
18931
18932    #[test]
18933    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18934        let nested_member = SelectionMemberMetadata {
18935            key: SelectionKey::Name("nested".to_string()),
18936            index: 0,
18937            base_sequence: 1,
18938            size: 2,
18939            kind: "group".to_string(),
18940        };
18941        let deadline_member = SelectionMemberMetadata {
18942            key: SelectionKey::Name("deadline".to_string()),
18943            index: 1,
18944            base_sequence: 3,
18945            size: 1,
18946            kind: "timer".to_string(),
18947        };
18948        let nested_paths = [
18949            vec![
18950                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18951                parallel_group_entry(1, 2, 0, "activity"),
18952            ],
18953            vec![
18954                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18955                parallel_group_entry(1, 2, 1, "activity"),
18956            ],
18957        ];
18958        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18959        let mut timer_fired = parallel_history_event(
18960            "TimerFired",
18961            3,
18962            "timer_id",
18963            "timer-3",
18964            deadline_path.clone(),
18965            None,
18966        );
18967        timer_fired.payload["delay_seconds"] = json!(0);
18968        timer_fired
18969            .raw
18970            .insert("id".to_string(), json!("timer-fired"));
18971        let mut timer_scheduled = parallel_history_event(
18972            "TimerScheduled",
18973            3,
18974            "timer_id",
18975            "timer-3",
18976            deadline_path,
18977            None,
18978        );
18979        timer_scheduled.payload["delay_seconds"] = json!(0);
18980        let history = vec![
18981            parallel_history_event(
18982                "ActivityScheduled",
18983                1,
18984                "activity_type",
18985                "nested-first",
18986                nested_paths[0].clone(),
18987                None,
18988            ),
18989            parallel_history_event(
18990                "ActivityScheduled",
18991                2,
18992                "activity_type",
18993                "nested-second",
18994                nested_paths[1].clone(),
18995                None,
18996            ),
18997            timer_scheduled,
18998            timer_fired,
18999            history_event(
19000                "SelectionResolved",
19001                json!({
19002                    "selection_group_id": "select-calls:1:3",
19003                    "selection_group_base_sequence": 1,
19004                    "selection_group_size": 3,
19005                    "member_key": "deadline",
19006                    "member_index": 1,
19007                    "member_base_sequence": 3,
19008                    "member_size": 1,
19009                    "operation_kind": "timer",
19010                    "operation_identity": "timer-3",
19011                    "outcome": "completed",
19012                    "resolution_event_id": "timer-fired",
19013                    "resolution_event_type": "TimerFired",
19014                }),
19015            ),
19016            parallel_history_event(
19017                "ActivityFailed",
19018                2,
19019                "activity_type",
19020                "nested-second",
19021                nested_paths[1].clone(),
19022                None,
19023            ),
19024        ];
19025        let ctx = workflow_context(history);
19026        let mut selection = Box::pin(ctx.select_keyed(vec![
19027            (
19028                "nested",
19029                ParallelOperation::group(vec![
19030                    ParallelOperation::activity("nested-first", json!([])),
19031                    ParallelOperation::activity("nested-second", json!([])),
19032                ]),
19033            ),
19034            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19035        ]));
19036        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19037        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19038            panic!("deadline winner must replay");
19039        };
19040        let nested = selected
19041            .handle(&SelectionKey::Name("nested".to_string()))
19042            .expect("nested handle")
19043            .clone();
19044        let mut cancel = Box::pin(nested.cancel());
19045        assert!(matches!(
19046            cancel.as_mut().poll(&mut task_context),
19047            Poll::Ready(Ok(()))
19048        ));
19049        let mut await_nested = Box::pin(nested.await_result());
19050
19051        assert!(matches!(
19052            await_nested.as_mut().poll(&mut task_context),
19053            Poll::Ready(Err(Error::ActivityFailed(_)))
19054        ));
19055        assert!(ctx.take_commands().expect("commands").is_empty());
19056    }
19057
19058    #[test]
19059    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19060        let ctx = workflow_context(Vec::new());
19061        let mut call = Box::pin(ctx.select(vec![
19062            ParallelOperation::child_workflow(
19063                "child",
19064                ChildWorkflowOptions::new("children"),
19065                json!([]),
19066            ),
19067            ParallelOperation::timer(Duration::from_secs(30)),
19068            ParallelOperation::signal("approval"),
19069            ParallelOperation::condition(
19070                ConditionWaitOptions::new("ready", "sha256:ready"),
19071                || Ok(false),
19072            ),
19073            ParallelOperation::group(vec![
19074                ParallelOperation::activity("nested-one", json!([])),
19075                ParallelOperation::activity("nested-two", json!([])),
19076            ]),
19077        ]));
19078        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19079        assert!(matches!(
19080            call.as_mut().poll(&mut task_context),
19081            Poll::Pending
19082        ));
19083        let commands = ctx.take_commands().expect("selection commands");
19084        assert_eq!(
19085            commands
19086                .iter()
19087                .map(|command| command["type"].as_str().unwrap_or_default())
19088                .collect::<Vec<_>>(),
19089            [
19090                "start_child_workflow",
19091                "start_timer",
19092                "open_signal_wait",
19093                "open_condition_wait",
19094                "schedule_activity",
19095                "schedule_activity",
19096            ]
19097        );
19098        assert!(commands.iter().all(|command| {
19099            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19100        }));
19101        assert_eq!(
19102            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19103            Some(2)
19104        );
19105        assert_eq!(
19106            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19107            json!("group")
19108        );
19109        assert_eq!(
19110            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19111            json!("group")
19112        );
19113
19114        let one_leaf_ctx = workflow_context(Vec::new());
19115        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19116            ParallelOperation::activity("nested-only", json!([])),
19117        ])]));
19118        assert!(matches!(
19119            one_leaf.as_mut().poll(&mut task_context),
19120            Poll::Pending
19121        ));
19122        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19123        assert_eq!(one_leaf_commands.len(), 1);
19124        assert_eq!(
19125            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19126            json!("group")
19127        );
19128        assert_eq!(
19129            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19130            json!(1)
19131        );
19132    }
19133
19134    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19135        let mut saga = ctx.saga();
19136        let outcome = async {
19137            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19138            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19139            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19140            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19141            ctx.activity("trip.charge", json!([])).await?;
19142            Ok(json!({"status": "booked"}))
19143        }
19144        .await;
19145        saga.finish(outcome).await
19146    }
19147
19148    fn saga_activity(
19149        event_type: &str,
19150        sequence: u64,
19151        activity_type: &str,
19152        result: Option<Value>,
19153    ) -> HistoryEvent {
19154        let mut payload = json!({
19155            "sequence": sequence,
19156            "activity_type": activity_type,
19157            "message": format!("{activity_type} failed"),
19158            "exception_type": "PlannedFailure",
19159            "non_retryable": true,
19160        });
19161        if let Some(result) = result {
19162            payload["result"] = fixture_envelope(result);
19163        }
19164        history_event(event_type, payload)
19165    }
19166
19167    #[test]
19168    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19169        let completed_hotel_compensation = saga_activity(
19170            "ActivityCompleted",
19171            4,
19172            "trip.cancel-hotel",
19173            Some(Value::Null),
19174        );
19175        let history = vec![
19176            saga_activity(
19177                "ActivityCompleted",
19178                1,
19179                "trip.reserve-flight",
19180                Some(json!("flight-1")),
19181            ),
19182            saga_activity(
19183                "ActivityCompleted",
19184                2,
19185                "trip.reserve-hotel",
19186                Some(json!("hotel-1")),
19187            ),
19188            saga_activity("ActivityFailed", 3, "trip.charge", None),
19189            completed_hotel_compensation.clone(),
19190            completed_hotel_compensation,
19191        ];
19192
19193        for _restart in 0..2 {
19194            let ctx = workflow_context(history.clone());
19195            let mut future = Box::pin(trip_saga(ctx.clone()));
19196            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19197            assert!(matches!(
19198                future.as_mut().poll(&mut task_context),
19199                Poll::Pending
19200            ));
19201            let commands = ctx.take_commands().expect("compensation command");
19202            assert_eq!(commands.len(), 1);
19203            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19204        }
19205    }
19206
19207    #[test]
19208    fn saga_compensation_failure_preserves_both_typed_failures() {
19209        let history = vec![
19210            saga_activity(
19211                "ActivityCompleted",
19212                1,
19213                "trip.reserve-flight",
19214                Some(json!("flight-1")),
19215            ),
19216            saga_activity(
19217                "ActivityCompleted",
19218                2,
19219                "trip.reserve-hotel",
19220                Some(json!("hotel-1")),
19221            ),
19222            saga_activity("ActivityFailed", 3, "trip.charge", None),
19223            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19224        ];
19225        let ctx = workflow_context(history);
19226        let mut future = Box::pin(trip_saga(ctx));
19227        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19228        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19229            future.as_mut().poll(&mut task_context)
19230        else {
19231            panic!("compensation failure must remain structured");
19232        };
19233        assert!(matches!(
19234            *failure.initiating_failure,
19235            Error::ActivityFailed(_)
19236        ));
19237        assert!(matches!(
19238            *failure.compensation_failure,
19239            Error::ActivityFailed(_)
19240        ));
19241        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19242        assert_eq!(failure.compensation_registration_order, 2);
19243    }
19244
19245    #[test]
19246    fn saga_compensates_cooperative_cancellation() {
19247        let ctx = workflow_context(vec![saga_activity(
19248            "ActivityCompleted",
19249            1,
19250            "trip.reserve-flight",
19251            Some(json!("flight-1")),
19252        )]);
19253        ctx.state.lock().expect("state").cancel_requested = true;
19254        let run = {
19255            let ctx = ctx.clone();
19256            async move {
19257                let mut saga = ctx.saga();
19258                let outcome = async {
19259                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19260                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19261                    ctx.throw_if_cancellation_requested()?;
19262                    Ok(json!("unexpected"))
19263                }
19264                .await;
19265                saga.finish(outcome).await
19266            }
19267        };
19268        let mut future = Box::pin(run);
19269        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19270        assert!(matches!(
19271            future.as_mut().poll(&mut task_context),
19272            Poll::Pending
19273        ));
19274        let commands = ctx.take_commands().expect("cancellation compensation");
19275        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19276    }
19277
19278    fn workflow_task(
19279        workflow_type: &str,
19280        history_events: Vec<HistoryEvent>,
19281        payload_codec: &str,
19282    ) -> WorkflowTask {
19283        WorkflowTask {
19284            task_id: format!("wft-{workflow_type}"),
19285            workflow_command_id: None,
19286            workflow_id: Some(format!("wf-{workflow_type}")),
19287            run_id: Some(format!("run-{workflow_type}")),
19288            workflow_type: workflow_type.to_string(),
19289            cancel_requested: false,
19290            payload_codec: payload_codec.to_string(),
19291            arguments: Some(
19292                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19293            ),
19294            total_history_events: Some(history_events.len() as u64),
19295            history_size_bytes: None,
19296            continue_as_new_recommended: None,
19297            history_budget_pressure: None,
19298            history_events,
19299            next_history_page_token: None,
19300            workflow_task_attempt: 1,
19301            workflow_signal_id: None,
19302            signal_name: None,
19303            signal_arguments: None,
19304            workflow_update_id: None,
19305            update_name: None,
19306            lease_owner: Some("rust-worker".to_string()),
19307        }
19308    }
19309
19310    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19311    struct SideEffectProbe {
19312        request_id: String,
19313        attempt: u32,
19314    }
19315
19316    #[test]
19317    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19318        let calls = AtomicUsize::new(0);
19319        let ctx = workflow_context(Vec::new());
19320        let value = ctx
19321            .side_effect(|| {
19322                calls.fetch_add(1, Ordering::SeqCst);
19323                SideEffectProbe {
19324                    request_id: "request-42".to_string(),
19325                    attempt: 3,
19326                }
19327            })
19328            .expect("first side effect");
19329        assert_eq!(value.attempt, 3);
19330        assert_eq!(calls.load(Ordering::SeqCst), 1);
19331        let commands = ctx.take_commands().expect("commands");
19332        assert_eq!(commands.len(), 1);
19333        assert_eq!(commands[0]["type"], "record_side_effect");
19334        assert_eq!(
19335            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19336            serde_json::to_value(&value).expect("value")
19337        );
19338
19339        let replay = workflow_context(vec![history_event(
19340            "SideEffectRecorded",
19341            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19342        )]);
19343        let replayed: SideEffectProbe = replay
19344            .side_effect(|| {
19345                calls.fetch_add(1, Ordering::SeqCst);
19346                panic!("committed side-effect callbacks must not run during replay")
19347            })
19348            .expect("replayed side effect");
19349        assert_eq!(replayed, value);
19350        assert_eq!(calls.load(Ordering::SeqCst), 1);
19351        assert!(replay.take_commands().expect("commands").is_empty());
19352        replay.ensure_history_consumed().expect("history consumed");
19353    }
19354
19355    #[test]
19356    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19357        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19358        let value = ctx
19359            .side_effect(|| SideEffectProbe {
19360                request_id: "avro-request".to_string(),
19361                attempt: 1,
19362            })
19363            .expect("Avro side effect");
19364        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19365        let commands = ctx.take_commands().expect("commands");
19366        assert_eq!(commands.len(), 2);
19367        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19368        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19369        assert_eq!(
19370            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19371            serde_json::to_value(&value).expect("value")
19372        );
19373
19374        let replay = workflow_context_with_codec(
19375            vec![
19376                history_event(
19377                    "SideEffectRecorded",
19378                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19379                ),
19380                history_event(
19381                    "SideEffectRecorded",
19382                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19383                ),
19384            ],
19385            DEFAULT_CODEC,
19386        );
19387        let replayed: SideEffectProbe = replay
19388            .side_effect(|| panic!("Avro callback must not run"))
19389            .expect("replayed Avro value");
19390        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19391        assert_eq!(replayed, value);
19392        assert_eq!(replayed_uuid, uuid);
19393        assert!(replay.take_commands().expect("commands").is_empty());
19394    }
19395
19396    #[test]
19397    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19398        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19399        let value = ctx
19400            .side_effect_avro_value(typed_fidelity_probe)
19401            .expect("typed side effect");
19402        let commands = ctx.take_commands().expect("side-effect command");
19403        assert_eq!(
19404            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19405                .expect("recorded side effect"),
19406            value
19407        );
19408
19409        let replay = workflow_context_with_codec(
19410            vec![history_event(
19411                "SideEffectRecorded",
19412                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19413            )],
19414            DEFAULT_CODEC,
19415        );
19416        assert_eq!(
19417            replay
19418                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19419                .expect("replayed typed side effect"),
19420            value
19421        );
19422    }
19423
19424    #[test]
19425    fn ordered_side_effects_share_the_durable_command_stream() {
19426        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19427        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19428        let ctx = workflow_context(vec![
19429            history_event(
19430                "SideEffectRecorded",
19431                json!({"sequence": 1, "result": first}),
19432            ),
19433            history_event(
19434                "SideEffectRecorded",
19435                json!({"sequence": 2, "result": second}),
19436            ),
19437        ]);
19438        let first: String = ctx
19439            .side_effect(|| panic!("first callback must not run"))
19440            .expect("first replay");
19441        let second: i32 = ctx
19442            .side_effect(|| panic!("second callback must not run"))
19443            .expect("second replay");
19444        assert_eq!(first, "first");
19445        assert_eq!(second, 29);
19446        ctx.ensure_history_consumed().expect("ordered history");
19447
19448        let reordered = workflow_context(vec![history_event(
19449            "VersionMarkerRecorded",
19450            json!({
19451                "sequence": 1,
19452                "change_id": "before-side-effect",
19453                "version": 1,
19454                "min_supported": 1,
19455                "max_supported": 1,
19456            }),
19457        )]);
19458        let error = reordered
19459            .side_effect(|| "new".to_string())
19460            .expect_err("command reordering must fail");
19461        assert!(matches!(
19462            error,
19463            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19464                if reason == "recorded_command_mismatch"
19465        ));
19466    }
19467
19468    #[test]
19469    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19470        for completed in [false, true] {
19471            let mut history = vec![history_event(
19472                "ActivityScheduled",
19473                json!({"sequence": 1, "activity_type": "old"}),
19474            )];
19475            if completed {
19476                history.push(history_event(
19477                    "ActivityCompleted",
19478                    json!({
19479                        "sequence": 1,
19480                        "activity_type": "old",
19481                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19482                    }),
19483                ));
19484            }
19485            for _cold_replay in 0..2 {
19486                let ctx = workflow_context(history.clone());
19487                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19488                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19489                ctx.deprecate_patch("added-step")
19490                    .expect("retained boundary");
19491                let mut activity = Box::pin(ctx.activity("old", json!([])));
19492                let mut context = TaskContext::from_waker(noop_waker_ref());
19493                match activity.as_mut().poll(&mut context) {
19494                    Poll::Ready(result) => {
19495                        assert!(completed);
19496                        assert_eq!(result.expect("recorded result"), json!(41));
19497                        ctx.ensure_history_consumed().expect("old command retained");
19498                    }
19499                    Poll::Pending => assert!(!completed),
19500                }
19501                assert!(ctx.take_commands().expect("commands").is_empty());
19502            }
19503        }
19504    }
19505
19506    #[test]
19507    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19508        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19509        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19510        ctx.deprecate_patch("added-step")
19511            .expect("same legacy decision");
19512        assert!(ctx.take_commands().expect("commands").is_empty());
19513        ctx.ensure_history_consumed().expect("completed history");
19514    }
19515
19516    #[test]
19517    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19518        let ctx = workflow_context(vec![history_event(
19519            "ActivityScheduled",
19520            json!({"sequence": 1, "activity_type": "old"}),
19521        )]);
19522        let error = ctx
19523            .get_version("added-step", 0, 1)
19524            .expect_err("legacy is unsupported");
19525        assert!(matches!(
19526            error,
19527            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19528                if reason == "version_marker_incompatible_range"
19529        ));
19530        assert!(!ctx
19531            .patched("supported-step")
19532            .expect("failed check did not consume history"));
19533        assert!(ctx.take_commands().expect("commands").is_empty());
19534    }
19535
19536    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19537        let mut event = history_event(
19538            "VersionMarkerRecorded",
19539            json!({
19540                "sequence": sequence,
19541                "change_id": "retained-patch",
19542                "version": version,
19543                "min_supported": -1,
19544                "max_supported": 1,
19545            }),
19546        );
19547        event.raw.insert("timestamp".into(), json!(time));
19548        event
19549    }
19550
19551    #[test]
19552    fn retained_patch_markers_preserve_each_original_boundary() {
19553        for completed in [false, true] {
19554            let mut history = vec![
19555                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19556                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19557                history_event(
19558                    "ActivityScheduled",
19559                    json!({"sequence": 3, "activity_type": "old"}),
19560                ),
19561            ];
19562            if completed {
19563                history.push(history_event(
19564                    "ActivityCompleted",
19565                    json!({
19566                        "sequence": 3,
19567                        "activity_type": "old",
19568                        "result": fixture_envelope(json!(41)),
19569                    }),
19570                ));
19571            }
19572            for _cold_replay in 0..2 {
19573                let ctx = workflow_context(history.clone());
19574                assert!(ctx.patched("retained-patch").unwrap());
19575                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19576                assert!(ctx.patched("retained-patch").unwrap());
19577                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19578                ctx.deprecate_patch("retained-patch").unwrap();
19579                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19580                let mut activity = Box::pin(ctx.activity("old", json!([])));
19581                let mut context = TaskContext::from_waker(noop_waker_ref());
19582                match activity.as_mut().poll(&mut context) {
19583                    Poll::Ready(result) => {
19584                        assert!(completed);
19585                        assert_eq!(result.unwrap(), json!(41));
19586                        ctx.ensure_history_consumed().unwrap();
19587                    }
19588                    Poll::Pending => assert!(!completed),
19589                }
19590                assert!(ctx.take_commands().unwrap().is_empty());
19591                let state = ctx.state.lock().unwrap();
19592                for (actual, original) in state.history_events.iter().zip(&history) {
19593                    assert_eq!(actual.payload, original.payload);
19594                    assert_eq!(actual.raw, original.raw);
19595                }
19596            }
19597        }
19598    }
19599
19600    #[test]
19601    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19602        let ctx = workflow_context(vec![
19603            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19604            history_event(
19605                "SideEffectRecorded",
19606                json!({
19607                    "sequence": 2, "result": fixture_envelope(json!("between")),
19608                }),
19609            ),
19610            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19611            history_event(
19612                "VersionMarkerRecorded",
19613                json!({
19614                    "sequence": 4, "change_id": "other-patch", "version": 1,
19615                    "min_supported": -1, "max_supported": 1,
19616                }),
19617            ),
19618        ]);
19619        assert!(ctx.patched("retained-patch").unwrap());
19620        assert!(ctx.patched("retained-patch").unwrap());
19621        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19622        assert_eq!(
19623            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19624            "between"
19625        );
19626        ctx.deprecate_patch("retained-patch").unwrap();
19627        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19628        ctx.deprecate_patch("retained-patch").unwrap();
19629        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19630        assert!(ctx.patched("other-patch").unwrap());
19631        ctx.ensure_history_consumed().unwrap();
19632        assert!(ctx.take_commands().unwrap().is_empty());
19633    }
19634
19635    #[test]
19636    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19637        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19638        alias.payload["max_supported"] = json!(3);
19639        let ctx = workflow_context(vec![
19640            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19641            alias,
19642        ]);
19643        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19644        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19645        assert!(matches!(error,
19646            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19647                if reason == "version_marker_incompatible_range"));
19648        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19649        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19650        ctx.ensure_history_consumed().unwrap();
19651        assert!(ctx.take_commands().unwrap().is_empty());
19652    }
19653
19654    #[test]
19655    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19656        let ctx = workflow_context(Vec::new());
19657        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19658        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19659        assert!(ctx.patched("new-search").expect("patch"));
19660        ctx.deprecate_patch("new-search").expect("deprecate patch");
19661        let commands = ctx.take_commands().expect("commands");
19662        assert_eq!(commands.len(), 2);
19663        assert_eq!(commands[0]["type"], "record_version_marker");
19664        assert_eq!(commands[0]["version"], 2);
19665        assert_eq!(commands[1]["change_id"], "new-search");
19666
19667        let replay = workflow_context(vec![history_event(
19668            "VersionMarkerRecorded",
19669            json!({
19670                "sequence": 1,
19671                "change_id": "checkout-v2",
19672                "version": 2,
19673                "min_supported": 1,
19674                "max_supported": 2,
19675            }),
19676        )]);
19677        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19678        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19679        assert!(replay.take_commands().expect("commands").is_empty());
19680        replay.ensure_history_consumed().expect("history consumed");
19681    }
19682
19683    #[test]
19684    fn version_markers_reject_incompatible_or_malformed_history() {
19685        let incompatible = workflow_context(vec![history_event(
19686            "VersionMarkerRecorded",
19687            json!({
19688                "sequence": 1,
19689                "change_id": "checkout-v2",
19690                "version": 1,
19691                "min_supported": 1,
19692                "max_supported": 2,
19693            }),
19694        )]);
19695        let error = incompatible
19696            .get_version("checkout-v2", 2, 3)
19697            .expect_err("old version is unsupported");
19698        assert!(matches!(
19699            error,
19700            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19701                if reason == "version_marker_incompatible_range"
19702        ));
19703
19704        for (history, reason) in [
19705            (
19706                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19707                "side_effect_result_missing",
19708            ),
19709            (
19710                vec![history_event(
19711                    "SideEffectRecorded",
19712                    json!({
19713                        "sequence": 1,
19714                        "result": {"codec": "avro", "blob": "not-base64"},
19715                    }),
19716                )],
19717                "side_effect_payload_incompatible",
19718            ),
19719            (
19720                vec![history_event(
19721                    "SideEffectRecorded",
19722                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19723                )],
19724                "side_effect_payload_malformed",
19725            ),
19726            (
19727                vec![history_event(
19728                    "VersionMarkerRecorded",
19729                    json!({
19730                        "sequence": 1,
19731                        "change_id": "change",
19732                        "version": 1,
19733                        "min_supported": 2,
19734                        "max_supported": 1,
19735                    }),
19736                )],
19737                "version_marker_history_range_invalid",
19738            ),
19739        ] {
19740            let error = WorkflowState::new(
19741                history,
19742                "rust-workers".to_string(),
19743                DEFAULT_CODEC.to_string(),
19744                None,
19745            )
19746            .expect_err("malformed history must fail");
19747            assert!(matches!(
19748                error,
19749                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
19750                    if actual == reason
19751            ));
19752        }
19753    }
19754
19755    #[test]
19756    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
19757        let history = vec![history_event(
19758            "SearchAttributesUpserted",
19759            json!({
19760                "sequence": 1,
19761                "attributes": {"customer_tier": "gold"},
19762                "attribute_types": {"customer_tier": "keyword"},
19763                "merged": {"customer_tier": "gold"}
19764            }),
19765        )];
19766
19767        let matching = workflow_context(history.clone());
19768        matching
19769            .upsert_search_attributes(
19770                SearchAttributeUpdate::new()
19771                    .keyword("customer_tier", "gold")
19772                    .expect("keyword update"),
19773            )
19774            .expect("matching typed update must replay");
19775        matching
19776            .ensure_history_consumed()
19777            .expect("history consumed");
19778
19779        let changed_type = workflow_context(history.clone());
19780        let error = changed_type
19781            .upsert_search_attributes(
19782                SearchAttributeUpdate::new()
19783                    .string("customer_tier", "gold")
19784                    .expect("string update"),
19785            )
19786            .expect_err("same JSON value with a different declaration must be nondeterministic");
19787        let Error::NonDeterministicReplay(failure) = error else {
19788            panic!("typed identity drift must be a replay failure");
19789        };
19790        assert_eq!(failure.reason, "search_attribute_type_mismatch");
19791        assert_eq!(failure.sequence, Some(1));
19792
19793        let changed_value = workflow_context(history);
19794        let error = changed_value
19795            .upsert_search_attributes(
19796                SearchAttributeUpdate::new()
19797                    .keyword("customer_tier", "platinum")
19798                    .expect("keyword update"),
19799            )
19800            .expect_err("changed values must be nondeterministic");
19801        let Error::NonDeterministicReplay(failure) = error else {
19802            panic!("value drift must be a replay failure");
19803        };
19804        assert_eq!(failure.reason, "search_attribute_value_mismatch");
19805    }
19806
19807    #[test]
19808    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
19809        let history = vec![history_event(
19810            "SearchAttributesUpserted",
19811            json!({
19812                "sequence": 1,
19813                "attributes": {"customer_tier": "gold"},
19814                "merged": {"customer_tier": "gold"}
19815            }),
19816        )];
19817
19818        for update in [
19819            SearchAttributeUpdate::new()
19820                .keyword("customer_tier", "gold")
19821                .expect("keyword update"),
19822            SearchAttributeUpdate::new()
19823                .string("customer_tier", "gold")
19824                .expect("string update"),
19825        ] {
19826            let restarted = workflow_context(history.clone());
19827            restarted
19828                .upsert_search_attributes(update)
19829                .expect("legacy history constrains values but has unknown type identity");
19830            restarted
19831                .ensure_history_consumed()
19832                .expect("history consumed");
19833        }
19834    }
19835
19836    #[test]
19837    fn search_attribute_command_emits_canonical_types() {
19838        let ctx = workflow_context(Vec::new());
19839        ctx.upsert_search_attributes(
19840            SearchAttributeUpdate::new()
19841                .keyword("customer_tier", "gold")
19842                .expect("keyword update")
19843                .int("attempts", 3)
19844                .expect("int update")
19845                .delete("obsolete")
19846                .expect("delete update"),
19847        )
19848        .expect("valid search attributes");
19849
19850        assert_eq!(
19851            ctx.take_commands().expect("commands"),
19852            vec![json!({
19853                "type": "upsert_search_attributes",
19854                "attributes": {
19855                    "attempts": 3,
19856                    "customer_tier": "gold",
19857                    "obsolete": null
19858                },
19859                "attribute_types": {
19860                    "attempts": "int",
19861                    "customer_tier": "keyword"
19862                }
19863            })]
19864        );
19865    }
19866
19867    #[test]
19868    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
19869        let duplicate_side_effect = WorkflowState::new(
19870            vec![
19871                history_event(
19872                    "SideEffectRecorded",
19873                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19874                ),
19875                history_event(
19876                    "SideEffectRecorded",
19877                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19878                ),
19879            ],
19880            "rust-workers".to_string(),
19881            DEFAULT_CODEC.to_string(),
19882            None,
19883        )
19884        .expect_err("duplicate side effect");
19885        assert!(matches!(
19886            duplicate_side_effect,
19887            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19888                if reason == "duplicate_side_effect_record"
19889        ));
19890
19891        let marker = |sequence, version| {
19892            history_event(
19893                "VersionMarkerRecorded",
19894                json!({
19895                    "sequence": sequence,
19896                    "change_id": "same-change",
19897                    "version": version,
19898                    "min_supported": -1,
19899                    "max_supported": 1,
19900                }),
19901            )
19902        };
19903        let duplicate_marker = WorkflowState::new(
19904            vec![marker(1, 1), marker(3, -1)],
19905            "rust-workers".to_string(),
19906            DEFAULT_CODEC.to_string(),
19907            None,
19908        )
19909        .expect_err("conflicting marker");
19910        assert!(matches!(
19911            duplicate_marker,
19912            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19913                if reason == "version_marker_conflict"
19914        ));
19915    }
19916
19917    #[test]
19918    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
19919        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
19920        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19921        invalid_alias.payload["max_supported"] = json!(0);
19922        for (history, expected_reason) in [
19923            (
19924                vec![marker.clone(), marker.clone()],
19925                "duplicate_version_marker_record",
19926            ),
19927            (
19928                vec![marker, invalid_alias],
19929                "version_marker_history_range_invalid",
19930            ),
19931        ] {
19932            let error =
19933                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
19934                    .expect_err("invalid historical alias");
19935            assert!(matches!(error,
19936                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
19937                    if reason == expected_reason));
19938        }
19939    }
19940
19941    #[test]
19942    fn retained_patch_aliases_require_the_original_call_boundary() {
19943        let ctx = workflow_context(vec![
19944            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19945            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19946        ]);
19947        assert!(ctx.patched("retained-patch").unwrap());
19948        assert!(ctx.ensure_history_consumed().is_err());
19949        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19950        ctx.deprecate_patch("retained-patch").unwrap();
19951        ctx.ensure_history_consumed().unwrap();
19952        assert!(ctx.take_commands().unwrap().is_empty());
19953    }
19954
19955    #[test]
19956    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
19957        let ctx = workflow_context(vec![
19958            history_event(
19959                "SideEffectRecorded",
19960                json!({
19961                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
19962                }),
19963            ),
19964            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19965        ]);
19966        assert!(!ctx.patched("retained-patch").unwrap());
19967        assert_eq!(
19968            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19969            "old-operation"
19970        );
19971        let error = ctx.patched("retained-patch").unwrap_err();
19972        assert!(matches!(error,
19973            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19974                if reason == "version_marker_conflict"));
19975        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19976        assert!(ctx.take_commands().unwrap().is_empty());
19977    }
19978
19979    #[test]
19980    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19981        let mut state = WorkflowState::new(
19982            Vec::new(),
19983            "rust-workers".to_string(),
19984            DEFAULT_CODEC.to_string(),
19985            None,
19986        )
19987        .expect("workflow state");
19988        state.workflow_command_identity = "command-7".to_string();
19989        let context = WorkflowContext {
19990            state: Arc::new(Mutex::new(state)),
19991            cancellation_scope_id: "root".into(),
19992        };
19993        let item =
19994            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
19995
19996        context
19997            .append_workflow_stream("output", &[item], Some(10))
19998            .expect("append command");
19999        context
20000            .error_workflow_stream("output", "producer failed", None)
20001            .expect("error command");
20002        let commands = context.take_commands().expect("commands");
20003
20004        assert_eq!(commands[0]["type"], "record_side_effect");
20005        assert_eq!(
20006            commands[0]["workflow_stream"]["command_identity"],
20007            "command-7"
20008        );
20009        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
20010        assert_eq!(
20011            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20012            "dw-stream:command-7:0:0"
20013        );
20014        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
20015
20016        let recorded = history_event(
20017            "SideEffectRecorded",
20018            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
20019        );
20020        let mut replay_state = WorkflowState::new(
20021            vec![recorded],
20022            "rust-workers".to_string(),
20023            DEFAULT_CODEC.to_string(),
20024            None,
20025        )
20026        .expect("replay state");
20027        replay_state.workflow_command_identity = "command-7".to_string();
20028        let replay_context = WorkflowContext {
20029            state: Arc::new(Mutex::new(replay_state)),
20030            cancellation_scope_id: "root".into(),
20031        };
20032        replay_context
20033            .append_workflow_stream(
20034                "output",
20035                &[WorkflowStreamAppendItem::from_reference(
20036                    "s3://bucket/item.avro",
20037                )],
20038                Some(10),
20039            )
20040            .expect("replayed append");
20041        assert!(replay_context
20042            .take_commands()
20043            .expect("replayed commands")
20044            .is_empty());
20045    }
20046
20047    #[test]
20048    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20049        let context = workflow_context(Vec::new());
20050        let error = context
20051            .append_workflow_stream(
20052                "output",
20053                &[WorkflowStreamAppendItem::from_reference(
20054                    "s3://bucket/item.avro",
20055                )],
20056                None,
20057            )
20058            .expect_err("stream append without durable command identity must fail closed");
20059
20060        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20061        assert!(context.take_commands().expect("commands").is_empty());
20062    }
20063
20064    #[test]
20065    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20066        let client = Client::builder("http://localhost:8080").build().unwrap();
20067        let mut worker = Worker::new(client, "rust-workers");
20068        worker.register_workflow("streams.worker", |ctx, _| async move {
20069            ctx.append_workflow_stream(
20070                "output",
20071                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20072                None,
20073            )?;
20074            ctx.close_workflow_stream("output", None)?;
20075            Ok(json!("done"))
20076        });
20077        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20078            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20079            task.workflow_command_id = command_id.clone();
20080            let expected_identity = command_id
20081                .as_deref()
20082                .filter(|id| !id.is_empty())
20083                .unwrap_or(&task.task_id)
20084                .to_string();
20085            let commands = worker
20086                .execute_workflow_task(task)
20087                .expect("ordinary worker stream output");
20088            assert_eq!(commands.len(), 3);
20089            assert_eq!(
20090                commands[0]["workflow_stream"]["command_identity"],
20091                expected_identity
20092            );
20093            assert_eq!(
20094                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20095                format!("dw-stream:{expected_identity}:0:0")
20096            );
20097            assert_eq!(
20098                commands[1]["workflow_stream"]["command_identity"],
20099                expected_identity
20100            );
20101            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20102            let history = commands[..2]
20103                .iter()
20104                .enumerate()
20105                .map(|(index, command)| {
20106                    history_event(
20107                        "SideEffectRecorded",
20108                        json!({"sequence":index + 1,"result":command["result"]}),
20109                    )
20110                })
20111                .collect();
20112            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20113            replay.task_id = "replacement-task".to_string();
20114            let replayed = worker
20115                .execute_workflow_task(replay)
20116                .expect("replacement worker consumes recorded stream effects");
20117            assert_eq!(replayed.len(), 1);
20118            assert_eq!(replayed[0]["type"], "complete_workflow");
20119        }
20120        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20121        missing.task_id.clear();
20122        assert!(matches!(
20123            worker.execute_workflow_task(missing),
20124            Err(Error::MissingWorkflowCommandIdentity)
20125        ));
20126    }
20127
20128    #[test]
20129    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20130        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20131            let client = Client::new("http://127.0.0.1:8080").expect("client");
20132            let mut worker = Worker::new(client, "rust-workers");
20133            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20134                let calls = Arc::clone(&calls);
20135                async move {
20136                    let captured = ctx.side_effect(|| {
20137                        calls.fetch_add(1, Ordering::SeqCst);
20138                        "captured-once".to_string()
20139                    })?;
20140                    let version = ctx.get_version("cold-restart", 1, 2)?;
20141                    Ok(json!({"captured": captured, "version": version}))
20142                }
20143            });
20144            worker
20145        }
20146
20147        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20148            WorkflowTask {
20149                task_id: "wft-side-effect-version".to_string(),
20150                workflow_command_id: None,
20151                workflow_id: Some("wf-side-effect-version".to_string()),
20152                run_id: Some("run-side-effect-version".to_string()),
20153                workflow_type: "rust.side-effect-version".to_string(),
20154                cancel_requested: false,
20155                payload_codec: DEFAULT_CODEC.to_string(),
20156                arguments: Some(
20157                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20158                ),
20159                history_events,
20160                total_history_events: None,
20161                history_size_bytes: None,
20162                continue_as_new_recommended: None,
20163                history_budget_pressure: None,
20164                next_history_page_token: None,
20165                workflow_task_attempt: 1,
20166                workflow_signal_id: None,
20167                signal_name: None,
20168                signal_arguments: None,
20169                workflow_update_id: None,
20170                update_name: None,
20171                lease_owner: Some("rust-worker".to_string()),
20172            }
20173        }
20174
20175        let calls = Arc::new(AtomicUsize::new(0));
20176        let initial = worker(Arc::clone(&calls))
20177            .execute_workflow_task(task(Vec::new()))
20178            .expect("initial execution");
20179        assert_eq!(
20180            initial
20181                .iter()
20182                .map(|command| &command["type"])
20183                .collect::<Vec<_>>(),
20184            vec![
20185                "record_side_effect",
20186                "record_version_marker",
20187                "complete_workflow"
20188            ]
20189        );
20190        assert_eq!(calls.load(Ordering::SeqCst), 1);
20191
20192        let restarted = worker(Arc::clone(&calls));
20193        let replayed = restarted
20194            .execute_workflow_task(task(vec![
20195                history_event(
20196                    "SideEffectRecorded",
20197                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20198                ),
20199                history_event(
20200                    "VersionMarkerRecorded",
20201                    json!({
20202                        "sequence": 2,
20203                        "change_id": "cold-restart",
20204                        "version": 2,
20205                        "min_supported": 1,
20206                        "max_supported": 2,
20207                    }),
20208                ),
20209            ]))
20210            .expect("cold replay");
20211        assert_eq!(replayed.len(), 1);
20212        assert_eq!(replayed[0]["type"], "complete_workflow");
20213        assert_eq!(calls.load(Ordering::SeqCst), 1);
20214    }
20215
20216    #[test]
20217    fn side_effect_replay_rejects_changed_rust_value_type() {
20218        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20219        let ctx = workflow_context(vec![history_event(
20220            "SideEffectRecorded",
20221            json!({"sequence": 1, "result": result}),
20222        )]);
20223        let error = ctx
20224            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20225            .expect_err("changed type must fail replay");
20226        assert!(matches!(
20227            error,
20228            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20229                if reason == "side_effect_type_mismatch"
20230        ));
20231    }
20232
20233    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20234        vec![
20235            history_event(
20236                "ActivityScheduled",
20237                json!({
20238                    "sequence": 1,
20239                    "activity_type": "flaky",
20240                    "activity_execution_id": "act-1",
20241                    "activity": {
20242                        "id": "act-1",
20243                        "sequence": 1,
20244                        "type": "flaky",
20245                        "queue": "critical-activities",
20246                        "execution_mode": null,
20247                        "retry_policy": {
20248                            "snapshot_version": 1,
20249                            "max_attempts": 3,
20250                            "backoff_seconds": [2, 4],
20251                            "start_to_close_timeout": 30,
20252                            "schedule_to_start_timeout": 5,
20253                            "schedule_to_close_timeout": 90,
20254                            "heartbeat_timeout": 10,
20255                            "non_retryable_error_types": ["PermanentError"]
20256                        }
20257                    }
20258                }),
20259            ),
20260            history_event(
20261                "ActivityStarted",
20262                json!({
20263                    "sequence": 1,
20264                    "activity_type": "flaky",
20265                    "activity_execution_id": "act-1",
20266                    "activity_attempt_id": "attempt-1",
20267                    "attempt_number": 1
20268                }),
20269            ),
20270            history_event(
20271                "ActivityRetryScheduled",
20272                json!({
20273                    "sequence": 1,
20274                    "activity_type": "flaky",
20275                    "activity_execution_id": "act-1",
20276                    "activity_attempt_id": "attempt-1",
20277                    "attempt_number": 1,
20278                    "retry_after_attempt": 1,
20279                    "retry_backoff_seconds": 2,
20280                    "failure_category": "activity",
20281                    "exception_type": "TransientError"
20282                }),
20283            ),
20284            history_event(
20285                "ActivityStarted",
20286                json!({
20287                    "sequence": 1,
20288                    "activity_type": "flaky",
20289                    "activity_execution_id": "act-1",
20290                    "activity_attempt_id": "attempt-2",
20291                    "attempt_number": 2
20292                }),
20293            ),
20294            history_event(
20295                "ActivityCompleted",
20296                json!({
20297                    "sequence": 1,
20298                    "activity_type": "flaky",
20299                    "activity_execution_id": "act-1",
20300                    "activity_attempt_id": "attempt-2",
20301                    "attempt_number": 2,
20302                    "payload_codec": DEFAULT_CODEC,
20303                    "result": fixture_envelope(json!({"status":"recovered"}))
20304                }),
20305            ),
20306        ]
20307    }
20308
20309    fn retry_activity_options() -> ActivityOptions {
20310        ActivityOptions::new()
20311            .task_queue("critical-activities")
20312            .retry_policy(
20313                ActivityRetryPolicy::new(3)
20314                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20315                    .non_retryable_error_type("PermanentError"),
20316            )
20317            .start_to_close_timeout(Duration::from_secs(30))
20318            .schedule_to_start_timeout(Duration::from_secs(5))
20319            .schedule_to_close_timeout(Duration::from_secs(90))
20320            .heartbeat_timeout(Duration::from_secs(10))
20321    }
20322
20323    #[test]
20324    fn fixed_avro_value_round_trips_json_values() {
20325        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20326        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20327        assert_eq!(envelope.codec, DEFAULT_CODEC);
20328        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20329    }
20330
20331    #[tokio::test]
20332    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20333        let client = Client::new("http://127.0.0.1:8080").expect("client");
20334        let mut worker = Worker::new(client, "rust-workers");
20335        worker.register_typed_workflow(
20336            "typed.contract.workflow",
20337            |_ctx, input: TypedContract| async move { Ok(input) },
20338        );
20339        worker.register_typed_activity(
20340            "typed.contract.activity",
20341            |_ctx, input: TypedContract| async move { Ok(input) },
20342        );
20343
20344        let expected = typed_contract();
20345        let arguments = AvroValue::Array(vec![
20346            AvroValue::from_serialize(&expected).expect("typed request")
20347        ]);
20348        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20349        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20350        workflow.arguments = Some(envelope.clone());
20351        let commands = worker
20352            .execute_workflow_task(workflow)
20353            .expect("typed workflow task");
20354        let workflow_result: TypedContract =
20355            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20356                .expect("workflow result envelope")
20357                .deserialize()
20358                .expect("workflow result type");
20359        assert_eq!(workflow_result, expected);
20360
20361        let activity = ActivityTask {
20362            task_id: "typed-contract-activity".to_string(),
20363            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20364            attempt_id: None,
20365            activity_type: "typed.contract.activity".to_string(),
20366            payload_codec: DEFAULT_CODEC.to_string(),
20367            arguments: Some(envelope),
20368            attempt_number: 1,
20369            lease_owner: Some("rust-worker".to_string()),
20370        };
20371        let activity_result: TypedContract = worker
20372            .execute_activity_task(activity)
20373            .await
20374            .expect("typed activity task")
20375            .deserialize()
20376            .expect("activity result type");
20377        assert_eq!(activity_result, expected);
20378    }
20379
20380    #[tokio::test]
20381    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
20382        let client = Client::new("http://127.0.0.1:8080").expect("client");
20383        let mut worker = Worker::new(client, "rust-workers");
20384        worker.register_typed_workflow(
20385            "typed.shape.workflow",
20386            |_ctx, input: TypedContract| async move { Ok(input) },
20387        );
20388        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
20389            Ok(f64::NAN)
20390        });
20391
20392        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
20393        workflow.arguments = Some(
20394            encode_typed_envelope(
20395                &AvroValue::Array(vec![
20396                    AvroValue::String("first".to_string()),
20397                    AvroValue::String("second".to_string()),
20398                ]),
20399                DEFAULT_CODEC,
20400            )
20401            .expect("malformed typed arguments"),
20402        );
20403        let commands = worker
20404            .execute_workflow_task(workflow)
20405            .expect("shape mismatch becomes a workflow failure");
20406        let message = commands[0]["message"].as_str().expect("failure message");
20407        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
20408        assert!(message.contains(type_name::<TypedContract>()));
20409        assert!(message.contains("task carried 2 arguments"));
20410
20411        let activity = ActivityTask {
20412            task_id: "typed-unsupported-activity".to_string(),
20413            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
20414            attempt_id: None,
20415            activity_type: "typed.unsupported.activity".to_string(),
20416            payload_codec: DEFAULT_CODEC.to_string(),
20417            arguments: Some(
20418                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20419                    .expect("unit arguments"),
20420            ),
20421            attempt_number: 1,
20422            lease_owner: Some("rust-worker".to_string()),
20423        };
20424        let Error::HandlerType {
20425            handler_kind,
20426            handler_name,
20427            value_kind,
20428            rust_type,
20429            message,
20430        } = worker
20431            .execute_activity_task(activity)
20432            .await
20433            .expect_err("non-finite handler output must fail")
20434        else {
20435            panic!("expected contextual handler type failure");
20436        };
20437        assert_eq!(handler_kind, HandlerKind::Activity);
20438        assert_eq!(handler_name, "typed.unsupported.activity");
20439        assert_eq!(value_kind, HandlerValueKind::Result);
20440        assert_eq!(rust_type, type_name::<f64>());
20441        assert!(message.contains("non_finite_float"));
20442    }
20443
20444    #[tokio::test]
20445    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20446        #[derive(Clone, Default)]
20447        struct State {
20448            observed: Option<TypedContract>,
20449        }
20450
20451        let client = Client::new("http://127.0.0.1:8080").expect("client");
20452        let mut worker = Worker::new(client, "rust-workers");
20453        worker.register_typed_replayed_workflow(
20454            "typed.contract.replayed",
20455            State::default,
20456            |ctx, input: TypedContract, state| async move {
20457                let result: TypedContract =
20458                    ctx.activity_typed("typed.contract.activity", input).await?;
20459                state.update(|current| current.observed = Some(result.clone()))?;
20460                Ok(result)
20461            },
20462        );
20463        worker.register_replayed_query::<State, _, _>(
20464            "typed.contract.replayed",
20465            "observed",
20466            |_ctx, state, _args| async move {
20467                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20468            },
20469        );
20470
20471        let expected = typed_contract();
20472        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20473        let workflow_arguments =
20474            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20475                .expect("workflow arguments");
20476        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20477        let task = QueryTask {
20478            query_task_id: "typed-replay-query".to_string(),
20479            query_task_attempt: 1,
20480            lease_owner: Some("rust-worker".to_string()),
20481            workflow_id: Some("typed-replay".to_string()),
20482            run_id: Some("typed-replay-run".to_string()),
20483            workflow_type: "typed.contract.replayed".to_string(),
20484            query_name: "observed".to_string(),
20485            payload_codec: DEFAULT_CODEC.to_string(),
20486            workflow_arguments: Some(workflow_arguments),
20487            query_arguments: Some(
20488                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20489                    .expect("query arguments"),
20490            ),
20491            history_events: vec![
20492                history_event(
20493                    "ActivityScheduled",
20494                    json!({
20495                        "sequence": 1,
20496                        "activity_type": "typed.contract.activity"
20497                    }),
20498                ),
20499                history_event(
20500                    "ActivityCompleted",
20501                    json!({
20502                        "sequence": 1,
20503                        "activity_type": "typed.contract.activity",
20504                        "payload_codec": DEFAULT_CODEC,
20505                        "result": result
20506                    }),
20507                ),
20508            ],
20509            history_export: None,
20510            run_status: Some("completed".to_string()),
20511        };
20512
20513        assert_eq!(
20514            worker
20515                .execute_query_task(task)
20516                .await
20517                .expect("typed replay query")
20518                .deserialize::<i64>()
20519                .expect("query result"),
20520            expected.signed
20521        );
20522    }
20523
20524    #[tokio::test]
20525    async fn update_context_preserves_workflow_input_and_committed_signals() {
20526        let client = Client::new("http://127.0.0.1:8080").expect("client");
20527        let mut worker = Worker::new(client, "rust-workers");
20528        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20529        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20530        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20531        let expected_input = workflow_input.clone();
20532        let expected_signals = signal_arguments.clone();
20533        let handler = move |context: QueryContext, arguments: AvroValue| {
20534            let expected_input = expected_input.clone();
20535            let expected_signals = expected_signals.clone();
20536            async move {
20537                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20538                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20539                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20540                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20541                assert_eq!(
20542                    context.signals_avro_value("changed"),
20543                    vec![expected_signals.clone()]
20544                );
20545                assert_eq!(
20546                    context.signals("changed"),
20547                    vec![expected_signals
20548                        .into_iter()
20549                        .map(AvroValue::into_json)
20550                        .collect::<Result<Vec<_>>>()?]
20551                );
20552                assert_eq!(
20553                    context.signal_events()[0].id.as_deref(),
20554                    Some("signal-original")
20555                );
20556                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20557                Ok(arguments)
20558            }
20559        };
20560        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20561        worker.register_update_avro_value("snapshot", "inspect", handler);
20562        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20563        let update_envelope =
20564            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20565        let mut task = workflow_task(
20566            "snapshot",
20567            vec![
20568                history_event(
20569                    "SignalReceived",
20570                    json!({
20571                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20572                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20573                    }),
20574                ),
20575                history_event(
20576                    "UpdateAccepted",
20577                    json!({
20578                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20579                    }),
20580                ),
20581            ],
20582            DEFAULT_CODEC,
20583        );
20584        task.arguments =
20585            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
20586        task.workflow_update_id = Some("update-original".into());
20587        task.update_name = Some("inspect".into());
20588        let query = QueryTask {
20589            query_task_id: "query-snapshot".into(),
20590            query_task_attempt: 1,
20591            lease_owner: None,
20592            workflow_id: task.workflow_id.clone(),
20593            run_id: task.run_id.clone(),
20594            workflow_type: task.workflow_type.clone(),
20595            query_name: "inspect".into(),
20596            payload_codec: DEFAULT_CODEC.into(),
20597            workflow_arguments: task.arguments.clone(),
20598            query_arguments: Some(update_envelope),
20599            history_events: task.history_events.clone(),
20600            history_export: None,
20601            run_status: Some("running".into()),
20602        };
20603        assert_eq!(
20604            worker
20605                .execute_query_task(query)
20606                .await
20607                .expect("query snapshot"),
20608            update_arguments
20609        );
20610        for _ in 0..2 {
20611            let commands = worker
20612                .execute_workflow_task(task.clone())
20613                .expect("cold update snapshot");
20614            assert_eq!(commands[0]["type"], "complete_update");
20615            assert_eq!(commands[0]["update_id"], "update-original");
20616            assert_eq!(
20617                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20618                    .expect("update result"),
20619                update_arguments
20620            );
20621        }
20622    }
20623
20624    #[test]
20625    fn committed_signal_snapshot_counts_identities_once() {
20626        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
20627        let received = history_event(
20628            "SignalReceived",
20629            json!({
20630                "signal_id": "signal-first", "workflow_command_id": "command-first",
20631                "signal_name": "changed", "arguments": arguments.clone(),
20632            }),
20633        );
20634        let applied = history_event(
20635            "SignalApplied",
20636            json!({
20637                "signal_id": "signal-first", "workflow_command_id": "command-first",
20638                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
20639            }),
20640        );
20641        let distinct = history_event(
20642            "SignalReceived",
20643            json!({
20644                "signal_id": "signal-second", "workflow_command_id": "command-second",
20645                "signal_name": "changed", "arguments": arguments,
20646            }),
20647        );
20648        let history = vec![received.clone(), applied.clone(), distinct];
20649        let signals =
20650            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
20651        assert_eq!(signals.len(), 2);
20652        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20653        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
20654        assert_eq!(signals[0].workflow_sequence, Some(1));
20655        assert_eq!(signals[0].arguments, signals[1].arguments);
20656        let mut command_only = received.clone();
20657        command_only
20658            .payload
20659            .as_object_mut()
20660            .expect("payload")
20661            .remove("signal_id");
20662        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
20663            .expect("command identity");
20664        assert_eq!(signals.len(), 1);
20665        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20666        let mut conflicting = applied;
20667        conflicting.payload["value"] =
20668            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
20669        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
20670    }
20671
20672    #[test]
20673    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
20674        for arguments in [
20675            vec![],
20676            vec![AvroValue::Array(vec![
20677                AvroValue::Long(1),
20678                AvroValue::Long(2),
20679            ])],
20680            vec![AvroValue::Bytes(vec![0, 255])],
20681            vec![AvroValue::Null],
20682            vec![AvroValue::Boolean(false)],
20683            vec![
20684                AvroValue::Long(1),
20685                AvroValue::Array(vec![AvroValue::Long(2)]),
20686            ],
20687        ] {
20688            let applied = match arguments.as_slice() {
20689                [] => AvroValue::Boolean(true),
20690                [value] => value.clone(),
20691                values => AvroValue::Array(values.to_vec()),
20692            };
20693            for applied in [applied, AvroValue::Array(arguments.clone())] {
20694                let events = vec![
20695                    history_event(
20696                        "SignalReceived",
20697                        json!({
20698                            "signal_id": "original", "signal_name": "changed",
20699                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
20700                        }),
20701                    ),
20702                    history_event(
20703                        "SignalApplied",
20704                        json!({
20705                            "signal_id": "original", "signal_name": "changed",
20706                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
20707                        }),
20708                    ),
20709                ];
20710                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
20711                    .expect("canonical signal snapshot");
20712                assert_eq!(signals.len(), 1);
20713                assert_eq!(signals[0].avro_arguments, arguments);
20714            }
20715        }
20716    }
20717
20718    #[tokio::test]
20719    async fn update_context_rejects_malformed_snapshot_before_handler() {
20720        let client = Client::new("http://127.0.0.1:8080").expect("client");
20721        let mut worker = Worker::new(client, "rust-workers");
20722        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20723        let calls = Arc::new(AtomicUsize::new(0));
20724        let observed = Arc::clone(&calls);
20725        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
20726            observed.fetch_add(1, Ordering::SeqCst);
20727            async { Ok(Value::Null) }
20728        });
20729        let mut task = workflow_task(
20730            "snapshot",
20731            vec![history_event(
20732                "UpdateAccepted",
20733                json!({
20734                    "update_id": "update-original", "update_name": "inspect",
20735                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
20736                }),
20737            )],
20738            DEFAULT_CODEC,
20739        );
20740        task.workflow_update_id = Some("update-original".into());
20741        task.update_name = Some("inspect".into());
20742        let mut bad_input = task.clone();
20743        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
20744        assert!(worker.execute_workflow_task(bad_input).is_err());
20745        task.history_events.insert(0, history_event("SignalReceived", json!({
20746            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
20747        })));
20748        assert!(worker.execute_workflow_task(task).is_err());
20749        assert_eq!(calls.load(Ordering::SeqCst), 0);
20750    }
20751
20752    #[tokio::test]
20753    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
20754        let client = Client::new("http://127.0.0.1:8080").expect("client");
20755        let mut worker = Worker::new(client, "rust-workers");
20756        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
20757        worker
20758            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
20759        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
20760            Ok(input)
20761        });
20762        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
20763            Ok(input)
20764        });
20765        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
20766            Ok(AvroValue::Array(
20767                ctx.wait_signal_avro_value("changed").await?,
20768            ))
20769        });
20770
20771        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
20772        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
20773
20774        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
20775        workflow.arguments = Some(envelope.clone());
20776        let commands = worker
20777            .execute_workflow_task(workflow)
20778            .expect("typed workflow task");
20779        assert_eq!(commands[0]["type"], "complete_workflow");
20780        assert_eq!(
20781            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20782                .expect("typed workflow result"),
20783            arguments
20784        );
20785
20786        let activity = ActivityTask {
20787            task_id: "activity-typed".to_string(),
20788            activity_attempt_id: Some("attempt-typed".to_string()),
20789            attempt_id: None,
20790            activity_type: "typed.activity".to_string(),
20791            payload_codec: DEFAULT_CODEC.to_string(),
20792            arguments: Some(envelope.clone()),
20793            attempt_number: 1,
20794            lease_owner: Some("rust-worker".to_string()),
20795        };
20796        assert_eq!(
20797            worker
20798                .execute_activity_task(activity)
20799                .await
20800                .expect("typed activity result"),
20801            arguments
20802        );
20803
20804        let query = QueryTask {
20805            query_task_id: "query-typed".to_string(),
20806            query_task_attempt: 1,
20807            lease_owner: Some("rust-worker".to_string()),
20808            workflow_id: Some("typed-1".to_string()),
20809            run_id: Some("run-typed".to_string()),
20810            workflow_type: "typed.echo".to_string(),
20811            query_name: "inspect".to_string(),
20812            payload_codec: DEFAULT_CODEC.to_string(),
20813            workflow_arguments: Some(
20814                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20815                    .expect("workflow input"),
20816            ),
20817            query_arguments: Some(envelope.clone()),
20818            history_events: Vec::new(),
20819            history_export: None,
20820            run_status: Some("running".to_string()),
20821        };
20822        assert_eq!(
20823            worker
20824                .execute_query_task(query)
20825                .await
20826                .expect("typed query result"),
20827            arguments
20828        );
20829
20830        let mut update = workflow_task(
20831            "typed.echo",
20832            vec![history_event(
20833                "UpdateAccepted",
20834                json!({
20835                    "update_id": "update-typed",
20836                    "update_name": "replace",
20837                    "arguments": envelope.clone(),
20838                }),
20839            )],
20840            DEFAULT_CODEC,
20841        );
20842        update.workflow_update_id = Some("update-typed".to_string());
20843        update.update_name = Some("replace".to_string());
20844        let commands = worker
20845            .execute_workflow_task(update)
20846            .expect("typed update task");
20847        assert_eq!(commands[0]["type"], "complete_update");
20848        assert_eq!(
20849            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20850                .expect("typed update result"),
20851            arguments
20852        );
20853
20854        let mut signal = workflow_task(
20855            "typed.signal",
20856            vec![history_event(
20857                "SignalReceived",
20858                json!({
20859                    "signal_id": "signal-typed",
20860                    "signal_name": "changed",
20861                    "arguments": envelope.clone(),
20862                }),
20863            )],
20864            DEFAULT_CODEC,
20865        );
20866        signal.workflow_signal_id = Some("signal-typed".to_string());
20867        signal.signal_name = Some("changed".to_string());
20868        signal.signal_arguments = Some(envelope);
20869        let commands = worker
20870            .execute_workflow_task(signal)
20871            .expect("typed signal resume");
20872        assert_eq!(
20873            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20874                .expect("typed signal result"),
20875            arguments
20876        );
20877    }
20878
20879    #[tokio::test]
20880    async fn typed_helpers_never_parse_json_inspection_projection() {
20881        let collision_values = projection_collision_probe();
20882        let expected = AvroValue::Array(collision_values.clone());
20883        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
20884
20885        let activity_context = workflow_context_with_codec(
20886            vec![history_event(
20887                "ActivityCompleted",
20888                json!({
20889                    "sequence": 1,
20890                    "activity_type": "collision.activity",
20891                    "payload_codec": DEFAULT_CODEC,
20892                    "result": envelope.clone(),
20893                }),
20894            )],
20895            DEFAULT_CODEC,
20896        );
20897        assert_eq!(
20898            activity_context
20899                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
20900                .await
20901                .expect("typed activity collision result"),
20902            expected
20903        );
20904
20905        let signal_context = workflow_context_with_codec(
20906            vec![
20907                history_event(
20908                    "SignalWaitOpened",
20909                    json!({"sequence": 1, "signal_name": "collision"}),
20910                ),
20911                history_event(
20912                    "SignalApplied",
20913                    json!({
20914                        "sequence": 1,
20915                        "signal_name": "collision",
20916                        "payload_codec": DEFAULT_CODEC,
20917                        "value": envelope.clone(),
20918                    }),
20919                ),
20920            ],
20921            DEFAULT_CODEC,
20922        );
20923        assert_eq!(
20924            signal_context
20925                .wait_signal_avro_value("collision")
20926                .await
20927                .expect("typed signal collision arguments"),
20928            collision_values
20929        );
20930
20931        let child_context = workflow_context_with_codec(
20932            vec![
20933                history_event(
20934                    "ChildWorkflowScheduled",
20935                    json!({
20936                        "sequence": 1,
20937                        "child_workflow_instance_id": "collision-child",
20938                        "child_workflow_run_id": "collision-run",
20939                        "child_workflow_type": "collision.child",
20940                    }),
20941                ),
20942                history_event(
20943                    "ChildRunCompleted",
20944                    json!({
20945                        "sequence": 1,
20946                        "child_workflow_instance_id": "collision-child",
20947                        "child_workflow_run_id": "collision-run",
20948                        "child_workflow_type": "collision.child",
20949                        "payload_codec": DEFAULT_CODEC,
20950                        "result": envelope,
20951                    }),
20952                ),
20953            ],
20954            DEFAULT_CODEC,
20955        );
20956        let child = child_context
20957            .start_child_workflow_avro_value(
20958                "collision.child",
20959                ChildWorkflowOptions::new("collision-workers"),
20960                AvroValue::Array(Vec::new()),
20961            )
20962            .await
20963            .expect("typed child collision result");
20964        assert_eq!(child.result, expected);
20965    }
20966
20967    #[tokio::test]
20968    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
20969        let client = Client::new("http://127.0.0.1:8080").expect("client");
20970        let mut worker = Worker::new(client, "rust-workers");
20971        worker.register_replayed_workflow_avro_value(
20972            "typed.replayed",
20973            || (),
20974            |_ctx, input, _state| async move { Ok(input) },
20975        );
20976        worker.register_replayed_query_avro_value::<(), _, _>(
20977            "typed.replayed",
20978            "inspect",
20979            |ctx, _state, args| async move {
20980                let mut signals = ctx.signals_avro_value("collision");
20981                let signal = signals
20982                    .pop()
20983                    .map(AvroValue::Array)
20984                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
20985                Ok(AvroValue::Array(vec![
20986                    ctx.workflow_input_avro_value().clone(),
20987                    signal,
20988                    args,
20989                ]))
20990            },
20991        );
20992        let arguments = AvroValue::Array(projection_collision_probe());
20993        let signal_arguments =
20994            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
20995        let task = QueryTask {
20996            query_task_id: "query-typed-replay".to_string(),
20997            query_task_attempt: 1,
20998            lease_owner: Some("rust-worker".to_string()),
20999            workflow_id: Some("typed-replay".to_string()),
21000            run_id: Some("run-typed-replay".to_string()),
21001            workflow_type: "typed.replayed".to_string(),
21002            query_name: "inspect".to_string(),
21003            payload_codec: DEFAULT_CODEC.to_string(),
21004            workflow_arguments: Some(
21005                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
21006            ),
21007            query_arguments: Some(
21008                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
21009            ),
21010            history_events: vec![history_event(
21011                "SignalReceived",
21012                json!({
21013                    "signal_id": "collision-signal",
21014                    "signal_name": "collision",
21015                    "workflow_sequence": 1,
21016                    "payload_codec": DEFAULT_CODEC,
21017                    "arguments": signal_arguments,
21018                }),
21019            )],
21020            history_export: None,
21021            run_status: Some("completed".to_string()),
21022        };
21023
21024        assert_eq!(
21025            worker
21026                .execute_query_task(task)
21027                .await
21028                .expect("typed replay query"),
21029            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21030        );
21031    }
21032
21033    #[test]
21034    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21035        let value = BTreeMap::from([(1_i32, "integer key")]);
21036        let error = PayloadEnvelope::avro(&value)
21037            .expect_err("integer map keys must fail")
21038            .to_string();
21039
21040        assert!(error.contains("invalid_map_key"));
21041    }
21042
21043    #[test]
21044    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21045        let envelope = PayloadEnvelope {
21046            codec: "json".to_string(),
21047            blob: r#"{"greeting":"hello"}"#.to_string(),
21048        };
21049
21050        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21051        let diagnostic = error.to_string();
21052        assert!(diagnostic.contains("unsupported_payload_codec"));
21053        assert!(diagnostic.contains("codec=\"avro\""));
21054        assert!(diagnostic.contains("HTTP document transport"));
21055    }
21056
21057    #[test]
21058    fn untagged_json_payload_value_fails_closed() {
21059        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21060            .expect_err("untagged JSON payload values must fail");
21061        let diagnostic = error.to_string();
21062        assert!(diagnostic.contains("unsupported_payload_codec"));
21063        assert!(diagnostic.contains("untagged durable payload"));
21064        assert!(diagnostic.contains("HTTP document transport"));
21065    }
21066
21067    #[test]
21068    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21069        let envelope = PayloadEnvelope {
21070            codec: DEFAULT_CODEC.to_string(),
21071            blob: BASE64.encode([0x01]),
21072        };
21073
21074        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21075        assert!(error.to_string().contains("invalid_payload_framing"));
21076    }
21077
21078    #[tokio::test]
21079    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21080        let server = MockWorkerServer::start();
21081        let client = Client::builder(server.base_url())
21082            .timeout(Duration::from_secs(2))
21083            .build()
21084            .expect("client");
21085        let invalid_commands = [
21086            json!({
21087                "type": "complete_workflow",
21088                "result": {"codec": "json", "blob": null}
21089            }),
21090            json!({
21091                "type": "schedule_activity",
21092                "arguments": {"codec": "yaml", "blob": "ignored"}
21093            }),
21094            json!({
21095                "type": "start_child_workflow",
21096                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21097            }),
21098            json!({"type": "continue_as_new", "arguments": []}),
21099            json!({"type": "complete_update"}),
21100            json!({"type": "record_side_effect", "result": null}),
21101            json!({
21102                "type": "start_service_operation",
21103                "payload_codec": DEFAULT_CODEC,
21104                "request_payload": "raw-avro-bytes"
21105            }),
21106        ];
21107
21108        for command in invalid_commands {
21109            let error = client
21110                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21111                .await
21112                .expect_err("invalid durable payload must fail locally");
21113            let diagnostic = error.to_string();
21114            assert!(
21115                diagnostic.contains("unsupported_payload_codec")
21116                    || diagnostic.contains("invalid_payload_envelope")
21117                    || diagnostic.contains("untagged durable payload"),
21118                "unexpected validation diagnostic: {diagnostic}"
21119            );
21120        }
21121
21122        assert_eq!(
21123            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21124            0,
21125            "invalid command payloads must not reach HTTP transport"
21126        );
21127    }
21128
21129    #[test]
21130    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21131        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21132        let commands = [
21133            json!({"type": "complete_workflow", "result": envelope.clone()}),
21134            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21135            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21136            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21137            json!({"type": "complete_update", "result": envelope.clone()}),
21138            json!({"type": "record_side_effect", "result": envelope.clone()}),
21139            json!({
21140                "type": "start_service_operation",
21141                "payload_codec": DEFAULT_CODEC,
21142                "request_payload": envelope.clone()
21143            }),
21144            json!({
21145                "type": "complete_workflow",
21146                "result": envelope,
21147                "metadata": {
21148                    "codec": "json",
21149                    "payload_codec": "customer-codec",
21150                    "result": {"codec": "yaml", "blob": null}
21151                }
21152            }),
21153        ];
21154
21155        validate_workflow_task_commands(&commands)
21156            .expect("customer metadata must not become a protocol codec declaration");
21157    }
21158
21159    #[test]
21160    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21161        assert_eq!(
21162            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21163            AvroValue::Array(Vec::new())
21164        );
21165        assert_eq!(
21166            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21167            AvroValue::Array(Vec::new())
21168        );
21169
21170        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21171        signal.signal_name = Some("empty-signal".to_string());
21172        signal.signal_arguments = None;
21173        let decoded = decode_resume_signal(&signal)
21174            .expect("valid Avro signal")
21175            .expect("named signal resumes the workflow");
21176        assert!(decoded.arguments.is_empty());
21177    }
21178
21179    #[tokio::test]
21180    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21181        let client = Client::new("http://127.0.0.1:8080").expect("client");
21182        let mut worker = Worker::new(client, "rust-workers");
21183        let handler_calls = Arc::new(AtomicUsize::new(0));
21184
21185        let calls = Arc::clone(&handler_calls);
21186        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21187            calls.fetch_add(1, Ordering::SeqCst);
21188            async move { Ok(Value::Null) }
21189        });
21190        let calls = Arc::clone(&handler_calls);
21191        worker.register_activity("codec.activity", 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_query("codec.workflow", "known", move |_ctx, _args| {
21197            calls.fetch_add(1, Ordering::SeqCst);
21198            async move { Ok(Value::Null) }
21199        });
21200
21201        let mut failures = Vec::new();
21202        for codec_case in [
21203            InvalidTaskPayloadCodec::Missing,
21204            InvalidTaskPayloadCodec::Null,
21205            InvalidTaskPayloadCodec::NonString,
21206        ] {
21207            let mut workflow = json!({
21208                "task_id": format!("workflow-{}", codec_case.label()),
21209                "workflow_type": "codec.workflow"
21210            });
21211            codec_case.apply(&mut workflow);
21212            match serde_json::from_value::<WorkflowTask>(workflow) {
21213                Ok(task) => match worker.execute_workflow_task(task) {
21214                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21215                    outcome => failures.push(format!(
21216                        "workflow {} codec returned {outcome:?}",
21217                        codec_case.label()
21218                    )),
21219                },
21220                Err(error) => failures.push(format!(
21221                    "workflow {} codec failed transport deserialization: {error}",
21222                    codec_case.label()
21223                )),
21224            }
21225
21226            let mut activity = json!({
21227                "task_id": format!("activity-{}", codec_case.label()),
21228                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21229                "activity_type": "codec.activity",
21230                "attempt_number": 1
21231            });
21232            codec_case.apply(&mut activity);
21233            match serde_json::from_value::<ActivityTask>(activity) {
21234                Ok(task) => match worker.execute_activity_task(task).await {
21235                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21236                    outcome => failures.push(format!(
21237                        "activity {} codec returned {outcome:?}",
21238                        codec_case.label()
21239                    )),
21240                },
21241                Err(error) => failures.push(format!(
21242                    "activity {} codec failed transport deserialization: {error}",
21243                    codec_case.label()
21244                )),
21245            }
21246
21247            let mut query = json!({
21248                "query_task_id": format!("query-{}", codec_case.label()),
21249                "workflow_type": "codec.workflow",
21250                "query_name": "known"
21251            });
21252            codec_case.apply(&mut query);
21253            match serde_json::from_value::<QueryTask>(query) {
21254                Ok(task) => match worker.execute_query_task(task).await {
21255                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21256                    outcome => failures.push(format!(
21257                        "query {} codec returned {outcome:?}",
21258                        codec_case.label()
21259                    )),
21260                },
21261                Err(error) => failures.push(format!(
21262                    "query {} codec failed transport deserialization: {error}",
21263                    codec_case.label()
21264                )),
21265            }
21266        }
21267
21268        assert!(failures.is_empty(), "{}", failures.join("\n"));
21269        assert_eq!(
21270            handler_calls.load(Ordering::SeqCst),
21271            0,
21272            "invalid task codecs must not invoke a handler"
21273        );
21274    }
21275
21276    #[tokio::test]
21277    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21278        for codec_case in [
21279            InvalidTaskPayloadCodec::Missing,
21280            InvalidTaskPayloadCodec::Null,
21281            InvalidTaskPayloadCodec::NonString,
21282        ] {
21283            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21284            let client = Client::builder(server.base_url())
21285                .timeout(Duration::from_secs(2))
21286                .build()
21287                .expect("client");
21288            let mut worker = Worker::new(client, "rust-workers")
21289                .worker_id("codec-worker")
21290                .poll_timeout(Duration::from_millis(10));
21291            let handler_calls = Arc::new(AtomicUsize::new(0));
21292
21293            let calls = Arc::clone(&handler_calls);
21294            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21295                calls.fetch_add(1, Ordering::SeqCst);
21296                async move { Ok(Value::Null) }
21297            });
21298            let calls = Arc::clone(&handler_calls);
21299            worker.register_activity("codec.activity", 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_query("codec.workflow", "known", move |_ctx, _args| {
21305                calls.fetch_add(1, Ordering::SeqCst);
21306                async move { Ok(Value::Null) }
21307            });
21308
21309            assert_eq!(
21310                worker.run_once().await.expect("invalid tasks are settled"),
21311                3,
21312                "all {} codec tasks must be handled",
21313                codec_case.label()
21314            );
21315            assert_eq!(
21316                handler_calls.load(Ordering::SeqCst),
21317                0,
21318                "{} task codecs must fail before every handler",
21319                codec_case.label()
21320            );
21321
21322            for path in [
21323                "/api/worker/workflow-tasks/codec-workflow/fail",
21324                "/api/worker/activity-tasks/codec-activity/fail",
21325                "/api/worker/query-tasks/codec-query/fail",
21326            ] {
21327                let body = server.request_body(path);
21328                assert!(
21329                    body["failure"]["message"]
21330                        .as_str()
21331                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21332                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21333                    codec_case.label()
21334                );
21335            }
21336            assert_eq!(
21337                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21338                    ["reason"],
21339                "query_payload_decode_failed"
21340            );
21341            for path in [
21342                "/api/worker/workflow-tasks/codec-workflow/complete",
21343                "/api/worker/activity-tasks/codec-activity/complete",
21344                "/api/worker/query-tasks/codec-query/complete",
21345            ] {
21346                assert_eq!(
21347                    server.request_count(path),
21348                    0,
21349                    "invalid {} codec task reached {path}",
21350                    codec_case.label()
21351                );
21352            }
21353        }
21354    }
21355
21356    #[tokio::test]
21357    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
21358        let client = Client::new("http://127.0.0.1:8080").expect("client");
21359        let mut worker = Worker::new(client, "rust-workers");
21360        let handler_calls = Arc::new(AtomicUsize::new(0));
21361
21362        let calls = Arc::clone(&handler_calls);
21363        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21364            calls.fetch_add(1, Ordering::SeqCst);
21365            async move { Ok(Value::Null) }
21366        });
21367        let calls = Arc::clone(&handler_calls);
21368        worker.register_activity("codec.activity", 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_update("codec.workflow", "known", 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_query("codec.workflow", "known", move |_ctx, _args| {
21379            calls.fetch_add(1, Ordering::SeqCst);
21380            async move { Ok(Value::Null) }
21381        });
21382
21383        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21384        workflow.payload_codec = "json".to_string();
21385        workflow.arguments = None;
21386        let error = worker
21387            .execute_workflow_task(workflow)
21388            .expect_err("task codec must be checked before workflow invocation");
21389        assert!(error.to_string().contains("unsupported_payload_codec"));
21390
21391        let activity = ActivityTask {
21392            task_id: "activity-invalid-codec".to_string(),
21393            activity_attempt_id: None,
21394            attempt_id: None,
21395            activity_type: "codec.activity".to_string(),
21396            payload_codec: "unknown".to_string(),
21397            arguments: None,
21398            attempt_number: 1,
21399            lease_owner: None,
21400        };
21401        let error = worker
21402            .execute_activity_task(activity)
21403            .await
21404            .expect_err("task codec must be checked before activity invocation");
21405        assert!(error.to_string().contains("unsupported_payload_codec"));
21406
21407        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21408        update.workflow_update_id = Some("update-invalid-codec".to_string());
21409        update.update_name = Some("known".to_string());
21410        update.history_events.push(history_event(
21411            "UpdateAccepted",
21412            json!({
21413                "update_id": "update-invalid-codec",
21414                "update_name": "known",
21415                "arguments": {"codec": "json", "blob": null}
21416            }),
21417        ));
21418        let error = worker
21419            .execute_workflow_task(update)
21420            .expect_err("nested update codec must be checked before handler lookup");
21421        assert!(error.to_string().contains("unsupported_payload_codec"));
21422
21423        let query: QueryTask = serde_json::from_value(json!({
21424            "query_task_id": "query-invalid-codec",
21425            "workflow_type": "codec.workflow",
21426            "query_name": "known",
21427            "payload_codec": DEFAULT_CODEC,
21428            "workflow_arguments": null,
21429            "query_arguments": null,
21430            "history_export": {
21431                "payloads": {"codec": DEFAULT_CODEC},
21432                "signals": [{
21433                    "name": "empty",
21434                    "payload_codec": "json",
21435                    "arguments": null
21436                }]
21437            }
21438        }))
21439        .expect("query task");
21440        let failure = worker
21441            .execute_query_task(query)
21442            .await
21443            .expect_err("exported signal codec must be checked before query invocation");
21444        assert_eq!(failure.reason, "query_payload_decode_failed");
21445        assert!(failure.message.contains("unsupported_payload_codec"));
21446
21447        let exported_history: QueryTask = serde_json::from_value(json!({
21448            "query_task_id": "query-invalid-history-codec",
21449            "workflow_type": "codec.workflow",
21450            "query_name": "known",
21451            "payload_codec": DEFAULT_CODEC,
21452            "history_export": {
21453                "payloads": {"codec": DEFAULT_CODEC},
21454                "history_events": [{
21455                    "type": "ActivityCompleted",
21456                    "payload": {"payload_codec": "unknown", "result": null}
21457                }]
21458            }
21459        }))
21460        .expect("query task");
21461        let failure = worker
21462            .execute_query_task(exported_history)
21463            .await
21464            .expect_err("exported history codec must be checked before query invocation");
21465        assert_eq!(failure.reason, "query_payload_decode_failed");
21466        assert!(failure.message.contains("unsupported_payload_codec"));
21467        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21468
21469        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21470        unknown_workflow.arguments = None;
21471        unknown_workflow.history_events.push(history_event(
21472            "SignalReceived",
21473            json!({
21474                "signal_name": "empty",
21475                "payload_codec": "json",
21476                "arguments": null
21477            }),
21478        ));
21479        let error = worker
21480            .execute_workflow_task(unknown_workflow)
21481            .expect_err("history codec must precede unknown workflow outcome");
21482        assert!(error.to_string().contains("unsupported_payload_codec"));
21483
21484        let unknown_activity = ActivityTask {
21485            task_id: "activity-unknown".to_string(),
21486            activity_attempt_id: None,
21487            attempt_id: None,
21488            activity_type: "missing".to_string(),
21489            payload_codec: "json".to_string(),
21490            arguments: None,
21491            attempt_number: 1,
21492            lease_owner: None,
21493        };
21494        let error = worker
21495            .execute_activity_task(unknown_activity)
21496            .await
21497            .expect_err("codec must precede unknown activity outcome");
21498        assert!(error.to_string().contains("unsupported_payload_codec"));
21499
21500        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21501        unknown_update.payload_codec = "json".to_string();
21502        unknown_update.arguments = None;
21503        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21504        unknown_update.update_name = Some("missing".to_string());
21505        let error = worker
21506            .execute_workflow_task(unknown_update)
21507            .expect_err("codec must precede fail_update shortcut");
21508        assert!(error.to_string().contains("unsupported_payload_codec"));
21509
21510        let unknown_query: QueryTask = serde_json::from_value(json!({
21511            "query_task_id": "query-unknown",
21512            "workflow_type": "missing",
21513            "query_name": "missing",
21514            "payload_codec": "json",
21515            "workflow_arguments": null,
21516            "query_arguments": null
21517        }))
21518        .expect("query task");
21519        let failure = worker
21520            .execute_query_task(unknown_query)
21521            .await
21522            .expect_err("codec must precede unknown query outcome");
21523        assert_eq!(failure.reason, "query_payload_decode_failed");
21524        assert!(failure.message.contains("unsupported_payload_codec"));
21525    }
21526
21527    #[tokio::test]
21528    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21529        let client = Client::new("http://127.0.0.1:8080").expect("client");
21530        let worker = Worker::new(client, "rust-workers");
21531
21532        for event_type in ["SignalReceived", "SignalApplied"] {
21533            for (payload_field, codec) in [
21534                ("value", "json"),
21535                ("input", "unknown"),
21536                ("arguments", "json"),
21537            ] {
21538                let payload = json!({
21539                    "signal_name": "empty",
21540                    payload_field: {"codec": codec, "blob": null}
21541                });
21542                let workflow = workflow_task(
21543                    "missing",
21544                    vec![history_event(event_type, payload.clone())],
21545                    DEFAULT_CODEC,
21546                );
21547                let error = worker
21548                    .execute_workflow_task(workflow)
21549                    .expect_err("signal payload codec must precede unknown workflow outcome");
21550                assert!(
21551                    error.to_string().contains("unsupported_payload_codec"),
21552                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21553                );
21554
21555                let query: QueryTask = serde_json::from_value(json!({
21556                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21557                    "workflow_type": "missing",
21558                    "query_name": "missing",
21559                    "payload_codec": DEFAULT_CODEC,
21560                    "workflow_arguments": null,
21561                    "query_arguments": null,
21562                    "history_events": [{
21563                        "event_type": event_type,
21564                        "payload": payload
21565                    }]
21566                }))
21567                .expect("query task");
21568                let failure = worker
21569                    .execute_query_task(query)
21570                    .await
21571                    .expect_err("signal payload codec must precede unknown query outcome");
21572                assert_eq!(
21573                    failure.reason, "query_payload_decode_failed",
21574                    "{event_type}.{payload_field} returned an unrelated query outcome"
21575                );
21576                assert!(
21577                    failure.message.contains("unsupported_payload_codec"),
21578                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21579                    failure.message
21580                );
21581            }
21582        }
21583    }
21584
21585    #[test]
21586    fn workflow_context_schedules_activity_until_completion_is_in_history() {
21587        let ctx = WorkflowContext {
21588            cancellation_scope_id: "root".into(),
21589            state: Arc::new(Mutex::new(
21590                WorkflowState::new_with_identity(
21591                    Vec::new(),
21592                    Some("wf-parent".to_string()),
21593                    Some("run-parent".to_string()),
21594                    "rust-workers".to_string(),
21595                    DEFAULT_CODEC.to_string(),
21596                    None,
21597                )
21598                .expect("workflow state"),
21599            )),
21600        };
21601
21602        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
21603        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21604        assert!(matches!(
21605            call.as_mut().poll(&mut task_context),
21606            Poll::Pending
21607        ));
21608
21609        let commands = ctx.take_commands().expect("commands");
21610        assert_eq!(commands[0]["type"], "schedule_activity");
21611        assert_eq!(commands[0]["activity_type"], "hello.activity");
21612    }
21613
21614    #[test]
21615    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
21616        let ctx = workflow_context(Vec::new());
21617        let options = ActivityOptions::new()
21618            .task_queue("payments")
21619            .retry_policy(
21620                ActivityRetryPolicy::new(4)
21621                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
21622                    .non_retryable_error_type("ValidationError"),
21623            )
21624            .start_to_close_timeout(Duration::from_secs(120))
21625            .schedule_to_start_timeout(Duration::from_secs(10))
21626            .schedule_to_close_timeout(Duration::from_secs(300))
21627            .heartbeat_timeout(Duration::from_secs(15));
21628        let mut call = Box::pin(ctx.activity_with_options(
21629            "charge-card",
21630            options,
21631            json!([{"order_id": "o-1"}]),
21632        ));
21633        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21634
21635        assert!(matches!(
21636            call.as_mut().poll(&mut task_context),
21637            Poll::Pending
21638        ));
21639        assert!(matches!(
21640            call.as_mut().poll(&mut task_context),
21641            Poll::Pending
21642        ));
21643
21644        let commands = ctx.take_commands().expect("activity command");
21645        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
21646        assert_eq!(commands[0]["queue"], "payments");
21647        assert_eq!(
21648            commands[0]["retry_policy"],
21649            json!({
21650                "max_attempts": 4,
21651                "backoff_seconds": [1, 3, 9],
21652                "non_retryable_error_types": ["ValidationError"],
21653            })
21654        );
21655        assert_eq!(commands[0]["start_to_close_timeout"], 120);
21656        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
21657        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
21658        assert_eq!(commands[0]["heartbeat_timeout"], 15);
21659    }
21660
21661    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
21662        vec![
21663            history_event(
21664                "ActivityScheduled",
21665                json!({"sequence":1,"activity_type":"render",
21666                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
21667            ),
21668            history_event(
21669                "ActivityCompleted",
21670                json!({"sequence":1,"activity_type":"render",
21671                "payload_codec":DEFAULT_CODEC,
21672                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
21673            ),
21674        ]
21675    }
21676
21677    #[test]
21678    fn worker_session_activity_routes_to_session_queue_once() {
21679        let ctx = workflow_context(Vec::new());
21680        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21681        let mut call = Box::pin(
21682            ctx.activity("render", json!([]))
21683                .in_worker_session(session.clone()),
21684        );
21685        let mut cx = TaskContext::from_waker(noop_waker_ref());
21686        assert!(call.as_mut().poll(&mut cx).is_pending());
21687        assert!(call.as_mut().poll(&mut cx).is_pending());
21688        let commands = ctx.take_commands().unwrap();
21689        assert_eq!(commands.len(), 1);
21690        assert_eq!(commands[0]["queue"], "gpu-workers");
21691        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
21692    }
21693
21694    #[tokio::test]
21695    async fn worker_session_cold_replay_uses_recorded_avro_result() {
21696        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21697        for _replacement in 0..2 {
21698            let ctx = workflow_context(completed_worker_session_history(&session));
21699            let result: i64 = ctx
21700                .activity("render", json!([]))
21701                .in_worker_session(session.clone())
21702                .typed()
21703                .await
21704                .unwrap();
21705            assert_eq!(result, 42);
21706            assert!(ctx.take_commands().unwrap().is_empty());
21707        }
21708    }
21709
21710    #[test]
21711    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
21712        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21713        for changed in [
21714            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
21715            Some(original.clone().ttl_seconds(60)),
21716            Some(original.clone().requirements(["gpu:l4"])),
21717            None,
21718        ] {
21719            let ctx = workflow_context(completed_worker_session_history(&original));
21720            let mut call = ctx.activity_with_options(
21721                "render",
21722                ActivityOptions::new().task_queue("gpu-workers"),
21723                json!([]),
21724            );
21725            if let Some(changed) = changed {
21726                call = call.in_worker_session(changed);
21727            }
21728            let mut call = Box::pin(call);
21729            let mut cx = TaskContext::from_waker(noop_waker_ref());
21730            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21731                call.as_mut().poll(&mut cx)
21732            else {
21733                panic!("changed session must fail replay");
21734            };
21735            assert_eq!(failure.reason, "activity_worker_session_mismatch");
21736            assert!(ctx.take_commands().unwrap().is_empty());
21737        }
21738    }
21739
21740    #[test]
21741    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
21742        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21743        let ctx = workflow_context(Vec::new());
21744        let mut local = Box::pin(
21745            ctx.local_activity("render", json!([]))
21746                .in_worker_session(session.clone()),
21747        );
21748        let mut cx = TaskContext::from_waker(noop_waker_ref());
21749        assert!(matches!(
21750            local.as_mut().poll(&mut cx),
21751            Poll::Ready(Err(Error::WorkerLoop(_)))
21752        ));
21753        assert!(ctx.take_commands().unwrap().is_empty());
21754        let mut remote = Box::pin(
21755            ctx.activity_with_options(
21756                "render",
21757                ActivityOptions::new().task_queue("other"),
21758                json!([]),
21759            )
21760            .in_worker_session(session),
21761        );
21762        assert!(matches!(
21763            remote.as_mut().poll(&mut cx),
21764            Poll::Ready(Err(Error::WorkerLoop(_)))
21765        ));
21766        assert!(ctx.take_commands().unwrap().is_empty());
21767    }
21768
21769    #[test]
21770    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
21771        let ctx = workflow_context(Vec::new());
21772        let options = ActivityOptions::new().retry_policy(
21773            ActivityRetryPolicy::new(3)
21774                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
21775        );
21776        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21777        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21778
21779        assert!(matches!(
21780            call.as_mut().poll(&mut task_context),
21781            Poll::Pending
21782        ));
21783        assert_eq!(
21784            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
21785            json!([1, 2])
21786        );
21787    }
21788
21789    #[test]
21790    fn activity_options_preserve_unused_explicit_backoff_entries() {
21791        for max_attempts in [1, 2, 10] {
21792            let ctx = workflow_context(Vec::new());
21793            let options =
21794                ActivityOptions::new()
21795                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
21796                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
21797                    ));
21798            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21799            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21800            assert!(matches!(
21801                call.as_mut().poll(&mut task_context),
21802                Poll::Pending
21803            ));
21804            let commands = ctx.take_commands().expect("command");
21805            assert_eq!(commands.len(), 1);
21806            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
21807            assert_eq!(
21808                commands[0]["retry_policy"]["backoff_seconds"],
21809                json!([1, 2, 5, 10, 15, 30, 60, 120])
21810            );
21811        }
21812        let default_options = ActivityOptions::new().validate().expect("default options");
21813        let default_policy = current_activity_retry_snapshot(&default_options);
21814        assert_eq!(
21815            default_policy.max_attempts,
21816            RecordedSnapshotValue::Known(Some(1))
21817        );
21818        assert_eq!(
21819            default_policy.backoff_seconds,
21820            RecordedSnapshotValue::Known(Vec::new())
21821        );
21822    }
21823
21824    #[test]
21825    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
21826        let fixture: Value = serde_json::from_str(include_str!(
21827            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
21828        ))
21829        .expect("published PHP fixture");
21830        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
21831            .expect("unchanged published history");
21832        let matching = ActivityOptions::new().task_queue("default").retry_policy(
21833            ActivityRetryPolicy::new(1)
21834                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
21835        );
21836        let mut changed_tail = matching.clone();
21837        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
21838            [1, 2, 5, 10, 15, 30, 60, 121]
21839                .map(Duration::from_secs)
21840                .to_vec(),
21841        ));
21842        let mut changed_first = matching.clone();
21843        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
21844            [2, 2, 5, 10, 15, 30, 60, 120]
21845                .map(Duration::from_secs)
21846                .to_vec(),
21847        ));
21848        let mut changed_attempts = matching.clone();
21849        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
21850        let mut changed_types = matching.clone();
21851        changed_types
21852            .retry_policy
21853            .as_mut()
21854            .unwrap()
21855            .non_retryable_error_types = vec!["ChangedError".into()];
21856        let mut changed_start = matching.clone();
21857        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
21858        let mut changed_schedule_start = matching.clone();
21859        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
21860        let mut changed_schedule_close = matching.clone();
21861        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
21862        let mut changed_heartbeat = matching;
21863        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
21864        let unchanged_defaults = ActivityOptions::new().task_queue("default");
21865        for options in [
21866            changed_tail,
21867            changed_first,
21868            changed_attempts,
21869            changed_types,
21870            changed_start,
21871            changed_schedule_start,
21872            changed_schedule_close,
21873            changed_heartbeat,
21874            unchanged_defaults,
21875        ] {
21876            let ctx = workflow_context(history.clone());
21877            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
21878            assert!(!ctx.patched("frozen-zero").unwrap());
21879            ctx.deprecate_patch("frozen-zero").unwrap();
21880            let mut call =
21881                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
21882            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21883            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21884                call.as_mut().poll(&mut task_context)
21885            else {
21886                panic!("changed explicit policy must fail replay")
21887            };
21888            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
21889            assert_eq!(failure.sequence, Some(2));
21890            assert!(ctx.take_commands().unwrap().is_empty());
21891        }
21892    }
21893
21894    #[test]
21895    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
21896        let cases = [
21897            (
21898                ActivityOptions::new().task_queue("  "),
21899                ActivityOptionsErrorKind::EmptyTaskQueue,
21900            ),
21901            (
21902                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
21903                ActivityOptionsErrorKind::EmptyRetryPolicy,
21904            ),
21905            (
21906                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
21907                ActivityOptionsErrorKind::InvalidMaxAttempts,
21908            ),
21909            (
21910                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
21911                    max_attempts: None,
21912                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
21913                    non_retryable_error_types: Vec::new(),
21914                }),
21915                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
21916            ),
21917            (
21918                ActivityOptions::new().retry_policy(
21919                    ActivityRetryPolicy::new(2).exponential_backoff(
21920                        Duration::from_secs(1),
21921                        0,
21922                        None,
21923                    ),
21924                ),
21925                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
21926            ),
21927            (
21928                ActivityOptions::new()
21929                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
21930                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
21931            ),
21932            (
21933                ActivityOptions::new().retry_policy(
21934                    ActivityRetryPolicy::new(10_002).exponential_backoff(
21935                        Duration::from_secs(1),
21936                        1,
21937                        None,
21938                    ),
21939                ),
21940                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
21941            ),
21942            (
21943                ActivityOptions::new().retry_policy(
21944                    ActivityRetryPolicy::new(2)
21945                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
21946                ),
21947                ActivityOptionsErrorKind::BackoffOverflow,
21948            ),
21949        ];
21950
21951        for (options, expected_kind) in cases {
21952            let ctx = workflow_context(Vec::new());
21953            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21954            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21955            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
21956                call.as_mut().poll(&mut task_context)
21957            else {
21958                panic!("expected typed activity validation error");
21959            };
21960            assert_eq!(error.kind, expected_kind);
21961            assert!(ctx.take_commands().expect("commands").is_empty());
21962        }
21963    }
21964
21965    #[test]
21966    fn activity_options_validate_positive_and_ordered_timeouts() {
21967        let zero_timeout_cases = [
21968            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
21969            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
21970            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
21971            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
21972        ];
21973        for options in zero_timeout_cases {
21974            assert_eq!(
21975                options.validate().expect_err("zero timeout").kind,
21976                ActivityOptionsErrorKind::TimeoutNotPositive
21977            );
21978        }
21979
21980        let ordering_cases = [
21981            ActivityOptions::new()
21982                .heartbeat_timeout(Duration::from_secs(11))
21983                .start_to_close_timeout(Duration::from_secs(10)),
21984            ActivityOptions::new()
21985                .start_to_close_timeout(Duration::from_secs(31))
21986                .schedule_to_close_timeout(Duration::from_secs(30)),
21987            ActivityOptions::new()
21988                .schedule_to_start_timeout(Duration::from_secs(31))
21989                .schedule_to_close_timeout(Duration::from_secs(30)),
21990        ];
21991        for options in ordering_cases {
21992            assert_eq!(
21993                options.validate().expect_err("timeout order").kind,
21994                ActivityOptionsErrorKind::TimeoutOrder
21995            );
21996        }
21997
21998        assert_eq!(
21999            ActivityOptions::new()
22000                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
22001                .validate()
22002                .expect_err("protocol integer overflow")
22003                .kind,
22004            ActivityOptionsErrorKind::TimeoutOverflow
22005        );
22006    }
22007
22008    #[test]
22009    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
22010        let ctx = workflow_context(completed_retry_activity_history());
22011        let mut call =
22012            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22013        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22014
22015        assert!(matches!(
22016            call.as_mut().poll(&mut task_context),
22017            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22018        ));
22019        assert!(ctx.take_commands().expect("commands").is_empty());
22020        ctx.ensure_history_consumed().expect("history consumed");
22021    }
22022
22023    #[test]
22024    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
22025        let mut options = retry_activity_options();
22026        options
22027            .retry_policy
22028            .as_mut()
22029            .expect("retry policy")
22030            .non_retryable_error_types
22031            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
22032
22033        let new_ctx = workflow_context(Vec::new());
22034        let mut new_call =
22035            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
22036        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22037        assert!(matches!(
22038            new_call.as_mut().poll(&mut task_context),
22039            Poll::Pending
22040        ));
22041        let commands = new_ctx.take_commands().expect("commands");
22042        assert_eq!(commands.len(), 1);
22043        assert_eq!(
22044            commands[0]["retry_policy"]["non_retryable_error_types"],
22045            json!(["PermanentError"])
22046        );
22047
22048        let replay_ctx = workflow_context(completed_retry_activity_history());
22049        let mut replay_call =
22050            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
22051        assert!(matches!(
22052            replay_call.as_mut().poll(&mut task_context),
22053            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22054        ));
22055        assert!(replay_ctx.take_commands().expect("commands").is_empty());
22056        replay_ctx
22057            .ensure_history_consumed()
22058            .expect("history consumed");
22059    }
22060
22061    #[test]
22062    fn replayed_intermediate_retry_remains_pending_across_restarts() {
22063        let history = completed_retry_activity_history()
22064            .into_iter()
22065            .take(3)
22066            .collect::<Vec<_>>();
22067
22068        for _restart in 0..2 {
22069            let ctx = workflow_context(history.clone());
22070            let mut call =
22071                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22072            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22073            assert!(matches!(
22074                call.as_mut().poll(&mut task_context),
22075                Poll::Pending
22076            ));
22077            assert!(ctx.take_commands().expect("commands").is_empty());
22078        }
22079    }
22080
22081    #[test]
22082    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
22083        let mut changed_queue = retry_activity_options();
22084        changed_queue.task_queue = Some("different-queue".to_string());
22085
22086        let mut changed_max_attempts = retry_activity_options();
22087        let retry_policy = changed_max_attempts
22088            .retry_policy
22089            .as_mut()
22090            .expect("retry policy");
22091        retry_policy.max_attempts = Some(4);
22092
22093        let mut changed_backoff = retry_activity_options();
22094        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
22095        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
22096            Duration::from_secs(3),
22097            Duration::from_secs(4),
22098        ]));
22099
22100        let mut changed_non_retryable_types = retry_activity_options();
22101        let retry_policy = changed_non_retryable_types
22102            .retry_policy
22103            .as_mut()
22104            .expect("retry policy");
22105        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
22106
22107        let mut changed_start_to_close = retry_activity_options();
22108        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
22109        let mut changed_schedule_to_start = retry_activity_options();
22110        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
22111        let mut changed_schedule_to_close = retry_activity_options();
22112        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
22113        let mut changed_heartbeat = retry_activity_options();
22114        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
22115
22116        let cases = [
22117            (changed_queue, "activity_task_queue_mismatch"),
22118            (changed_max_attempts, "activity_retry_policy_mismatch"),
22119            (changed_backoff, "activity_retry_policy_mismatch"),
22120            (
22121                changed_non_retryable_types,
22122                "activity_retry_policy_mismatch",
22123            ),
22124            (changed_start_to_close, "activity_retry_policy_mismatch"),
22125            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22126            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22127            (changed_heartbeat, "activity_retry_policy_mismatch"),
22128        ];
22129
22130        for (options, expected_reason) in cases {
22131            let ctx = workflow_context(completed_retry_activity_history());
22132            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22133            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22134            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22135                call.as_mut().poll(&mut task_context)
22136            else {
22137                panic!("changed activity options must fail replay");
22138            };
22139            assert_eq!(failure.reason, expected_reason);
22140            assert_eq!(failure.sequence, Some(1));
22141            assert!(ctx.take_commands().expect("commands").is_empty());
22142        }
22143    }
22144
22145    #[test]
22146    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22147        let cases = [
22148            (
22149                "execution_mode",
22150                json!("local"),
22151                "activity_execution_mode_mismatch",
22152            ),
22153            (
22154                "snapshot_version",
22155                json!(2),
22156                "activity_retry_policy_mismatch",
22157            ),
22158        ];
22159
22160        for (field, value, expected_reason) in cases {
22161            let mut history = completed_retry_activity_history();
22162            let activity = history[0].payload["activity"]
22163                .as_object_mut()
22164                .expect("activity snapshot");
22165            if field == "execution_mode" {
22166                activity.insert(field.to_string(), value);
22167            } else {
22168                activity["retry_policy"]
22169                    .as_object_mut()
22170                    .expect("retry snapshot")
22171                    .insert(field.to_string(), value);
22172            }
22173
22174            let ctx = workflow_context(history);
22175            let mut call =
22176                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22177            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22178            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22179                call.as_mut().poll(&mut task_context)
22180            else {
22181                panic!("changed {field} must fail replay");
22182            };
22183            assert_eq!(failure.reason, expected_reason);
22184            assert_eq!(failure.sequence, Some(1));
22185            assert!(ctx.take_commands().expect("commands").is_empty());
22186        }
22187    }
22188
22189    #[test]
22190    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22191        for (nested, field, value, terminal_only) in [
22192            (false, "execution_mode", json!("local"), false),
22193            (false, "local_activity", json!(true), false),
22194            (true, "local_activity", json!(true), false),
22195            (false, "local_activity", json!(true), true),
22196        ] {
22197            let mut history = completed_retry_activity_history();
22198            history[0]
22199                .payload
22200                .as_object_mut()
22201                .unwrap()
22202                .remove("activity");
22203            let event = if terminal_only {
22204                history.last_mut().unwrap()
22205            } else {
22206                &mut history[0]
22207            };
22208            if nested {
22209                event.payload["activity"] = json!({(field): value});
22210            } else {
22211                event.payload[field] = value;
22212            }
22213            let ctx = workflow_context(history);
22214            let mut call =
22215                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22216            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22217            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22218                call.as_mut().poll(&mut task_context)
22219            else {
22220                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22221            };
22222            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22223            assert_eq!(failure.sequence, Some(1));
22224            assert!(ctx.take_commands().expect("commands").is_empty());
22225        }
22226    }
22227
22228    #[test]
22229    fn activity_history_rejects_conflicting_local_execution_markers() {
22230        let mut history = completed_retry_activity_history();
22231        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22232        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22233            .expect_err("remote schedule cannot become a local completion");
22234        assert!(
22235            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22236            if reason == "activity_execution_mode_conflict")
22237        );
22238    }
22239
22240    #[test]
22241    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22242        let mut history = completed_retry_activity_history();
22243        let activity = history[0].payload["activity"]
22244            .as_object_mut()
22245            .expect("activity snapshot");
22246        activity.remove("execution_mode");
22247        activity.remove("retry_policy");
22248
22249        let mut current = retry_activity_options();
22250        current.start_to_close_timeout = Some(Duration::from_secs(45));
22251        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22252        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22253        current.heartbeat_timeout = Some(Duration::from_secs(12));
22254
22255        let ctx = workflow_context(history);
22256        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22257        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22258        assert!(matches!(
22259            call.as_mut().poll(&mut task_context),
22260            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22261        ));
22262        assert!(ctx.take_commands().expect("commands").is_empty());
22263        ctx.ensure_history_consumed().expect("history consumed");
22264    }
22265
22266    #[test]
22267    fn terminal_activity_failed_after_start_returns_typed_failure() {
22268        let history = vec![
22269            history_event(
22270                "ActivityScheduled",
22271                json!({
22272                    "sequence": 1,
22273                    "activity_type": "flaky",
22274                    "activity_execution_id": "act-terminal",
22275                    "activity": {
22276                        "id": "act-terminal",
22277                        "sequence": 1,
22278                        "type": "flaky",
22279                        "queue": "critical-activities",
22280                        "retry_policy": {
22281                            "snapshot_version": 1,
22282                            "max_attempts": 3,
22283                            "backoff_seconds": [2, 4],
22284                            "non_retryable_error_types": ["PermanentError"]
22285                        }
22286                    }
22287                }),
22288            ),
22289            history_event(
22290                "ActivityStarted",
22291                json!({
22292                    "sequence": 1,
22293                    "activity_type": "flaky",
22294                    "activity_execution_id": "act-terminal",
22295                    "activity_attempt_id": "attempt-1",
22296                    "attempt_number": 1
22297                }),
22298            ),
22299            history_event(
22300                "ActivityFailed",
22301                json!({
22302                    "sequence": 1,
22303                    "activity_type": "flaky",
22304                    "activity_execution_id": "act-terminal",
22305                    "activity_attempt_id": "attempt-1",
22306                    "attempt_number": 1,
22307                    "failure_id": "failure-terminal",
22308                    "failure_category": "activity",
22309                    "exception_type": "PermanentError",
22310                    "message": "cannot retry",
22311                    "non_retryable": true
22312                }),
22313            ),
22314        ];
22315        let ctx = workflow_context(history);
22316        let mut call =
22317            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22318        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22319
22320        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22321            call.as_mut().poll(&mut task_context)
22322        else {
22323            panic!("terminal ActivityFailed must settle the activity future");
22324        };
22325        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22326        assert_eq!(
22327            failure.activity_execution_id.as_deref(),
22328            Some("act-terminal")
22329        );
22330        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22331        assert!(failure.non_retryable);
22332        assert!(ctx.take_commands().expect("commands").is_empty());
22333        ctx.ensure_history_consumed().expect("history consumed");
22334    }
22335
22336    #[test]
22337    fn activity_terminal_events_return_machine_readable_failures() {
22338        let cases = [
22339            (
22340                "ActivityFailed",
22341                json!({
22342                    "sequence": 1,
22343                    "activity_type": "charge-card",
22344                    "activity_execution_id": "act-1",
22345                    "activity_attempt_id": "attempt-2",
22346                    "attempt_number": 2,
22347                    "failure_id": "failure-1",
22348                    "failure_category": "activity",
22349                    "exception_type": "PaymentDeclined",
22350                    "exception_class": "payments.PaymentDeclined",
22351                    "message": "card declined",
22352                    "non_retryable": true
22353                }),
22354                ActivityFailureKind::Failed,
22355                "activity",
22356            ),
22357            (
22358                "ActivityCancelled",
22359                json!({
22360                    "sequence": 1,
22361                    "activity_type": "charge-card",
22362                    "activity_execution_id": "act-1",
22363                    "activity_attempt_id": "attempt-1"
22364                }),
22365                ActivityFailureKind::Cancelled,
22366                "cancelled",
22367            ),
22368        ];
22369
22370        for (event_type, payload, expected_kind, expected_reason) in cases {
22371            let ctx = workflow_context(vec![history_event(event_type, payload)]);
22372            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
22373            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22374            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22375                call.as_mut().poll(&mut task_context)
22376            else {
22377                panic!("expected terminal activity failure");
22378            };
22379            assert_eq!(failure.kind, expected_kind);
22380            assert_eq!(failure.reason, expected_reason);
22381            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
22382            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
22383        }
22384    }
22385
22386    #[test]
22387    fn every_activity_timeout_class_is_typed() {
22388        for timeout_kind in [
22389            "start_to_close",
22390            "schedule_to_start",
22391            "schedule_to_close",
22392            "heartbeat",
22393        ] {
22394            let ctx = workflow_context(vec![history_event(
22395                "ActivityTimedOut",
22396                json!({
22397                    "sequence": 1,
22398                    "activity_type": "slow",
22399                    "activity_execution_id": "act-timeout",
22400                    "activity_attempt_id": "attempt-timeout",
22401                    "failure_category": "timeout",
22402                    "timeout_kind": timeout_kind,
22403                    "message": "deadline expired"
22404                }),
22405            )]);
22406            let mut call = Box::pin(ctx.activity("slow", json!([])));
22407            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22408            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22409                call.as_mut().poll(&mut task_context)
22410            else {
22411                panic!("expected timeout failure");
22412            };
22413            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
22414            assert_eq!(failure.reason, timeout_kind);
22415            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
22416            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
22417        }
22418    }
22419
22420    #[test]
22421    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
22422        let ctx = workflow_context(Vec::new());
22423        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
22424        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22425
22426        assert!(matches!(
22427            sleep.as_mut().poll(&mut task_context),
22428            Poll::Pending
22429        ));
22430        assert!(matches!(
22431            sleep.as_mut().poll(&mut task_context),
22432            Poll::Pending
22433        ));
22434
22435        let commands = ctx.take_commands().expect("timer command");
22436        assert_eq!(
22437            commands,
22438            vec![json!({
22439                "type": "start_timer",
22440                "delay_seconds": 2,
22441            })]
22442        );
22443    }
22444
22445    #[test]
22446    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
22447        let history = vec![
22448            history_event(
22449                "TimerScheduled",
22450                json!({
22451                    "sequence": 1,
22452                    "timer_id": "timer-1",
22453                    "delay_seconds": 5,
22454                    "fire_at": "2026-07-11T12:00:05Z",
22455                }),
22456            ),
22457            history_event(
22458                "TimerFired",
22459                json!({
22460                    "sequence": 1,
22461                    "timer_id": "timer-1",
22462                    "delay_seconds": 5,
22463                    "fire_at": "2026-07-11T12:00:05Z",
22464                    "fired_at": "2026-07-11T12:00:05Z",
22465                }),
22466            ),
22467        ];
22468
22469        for _restart in 0..2 {
22470            let ctx = workflow_context(history.clone());
22471            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
22472            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22473            assert!(matches!(
22474                sleep.as_mut().poll(&mut task_context),
22475                Poll::Ready(Ok(()))
22476            ));
22477            assert!(ctx.take_commands().expect("commands").is_empty());
22478            ctx.ensure_history_consumed().expect("history consumed");
22479        }
22480    }
22481
22482    #[test]
22483    fn workflow_sleep_rejects_changed_delay_during_replay() {
22484        let ctx = workflow_context(vec![
22485            history_event(
22486                "TimerScheduled",
22487                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22488            ),
22489            history_event(
22490                "TimerFired",
22491                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22492            ),
22493        ]);
22494        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
22495        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22496
22497        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22498            sleep.as_mut().poll(&mut task_context)
22499        else {
22500            panic!("changed timer delay must be rejected");
22501        };
22502        assert_eq!(failure.reason, "timer_delay_mismatch");
22503        assert_eq!(failure.sequence, Some(1));
22504    }
22505
22506    #[test]
22507    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
22508        let ctx = workflow_context(Vec::new());
22509        let mut wait = Box::pin(
22510            ctx.wait_condition(
22511                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
22512                    .timeout(Duration::from_millis(60_001)),
22513                || Ok(false),
22514            ),
22515        );
22516        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22517
22518        assert!(matches!(
22519            wait.as_mut().poll(&mut task_context),
22520            Poll::Pending
22521        ));
22522        assert!(matches!(
22523            wait.as_mut().poll(&mut task_context),
22524            Poll::Pending
22525        ));
22526        assert_eq!(
22527            ctx.take_commands().expect("condition command"),
22528            vec![json!({
22529                "type": "open_condition_wait",
22530                "condition_wait_occurrence_id": "rust:condition-wait:0",
22531                "condition_key": "approval.ready",
22532                "condition_definition_fingerprint": "sha256:approval-v1",
22533                "timeout_seconds": 61,
22534            })]
22535        );
22536    }
22537
22538    #[test]
22539    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22540        let ctx = workflow_context(Vec::new());
22541        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22542        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22543        assert!(matches!(
22544            satisfied.as_mut().poll(&mut task_context),
22545            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22546        ));
22547
22548        let mut timed_out = Box::pin(wait_condition!(
22549            ctx,
22550            "no-wait",
22551            timeout: Duration::ZERO,
22552            || Ok(false),
22553        ));
22554        assert!(matches!(
22555            timed_out.as_mut().poll(&mut task_context),
22556            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22557        ));
22558        assert!(ctx.take_commands().expect("commands").is_empty());
22559    }
22560
22561    #[test]
22562    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22563        let signal_history = vec![
22564            history_event(
22565                "ConditionWaitOpened",
22566                json!({
22567                    "sequence": 4,
22568                    "condition_wait_id": "condition:4",
22569                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22570                    "condition_key": "approval",
22571                    "condition_definition_fingerprint": "sha256:approval-v1",
22572                    "timeout_seconds": 30,
22573                }),
22574            ),
22575            history_event(
22576                "SignalReceived",
22577                json!({
22578                    "workflow_sequence": 4,
22579                    "signal_name": "approve",
22580                    "arguments": fixture_envelope(json!(["Ada"])),
22581                }),
22582            ),
22583        ];
22584        for _worker_before_or_after_restart in 0..2 {
22585            let ctx = workflow_context(signal_history.clone());
22586            let predicate_ctx = ctx.clone();
22587            let mut wait = Box::pin(
22588                ctx.wait_condition(
22589                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
22590                        .timeout(Duration::from_secs(30)),
22591                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
22592                ),
22593            );
22594            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22595            assert!(matches!(
22596                wait.as_mut().poll(&mut task_context),
22597                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22598            ));
22599            assert!(ctx.take_commands().expect("commands").is_empty());
22600            ctx.ensure_history_consumed().expect("condition consumed");
22601        }
22602
22603        let update_history = vec![
22604            history_event(
22605                "ConditionWaitOpened",
22606                json!({
22607                    "sequence": 7,
22608                    "condition_wait_id": "condition:7",
22609                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22610                    "condition_key": "update-approval",
22611                    "condition_definition_fingerprint": "sha256:update-approval-v1",
22612                }),
22613            ),
22614            history_event(
22615                "UpdateApplied",
22616                json!({
22617                    "sequence": 7,
22618                    "update_id": "update-1",
22619                    "update_name": "approve",
22620                    "arguments": fixture_envelope(json!([true])),
22621                }),
22622            ),
22623        ];
22624        let ctx = workflow_context(update_history);
22625        let predicate_ctx = ctx.clone();
22626        let mut wait = Box::pin(ctx.wait_condition(
22627            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
22628            move || {
22629                Ok(predicate_ctx
22630                    .updates("approve")?
22631                    .first()
22632                    .and_then(|arguments| arguments.first())
22633                    .and_then(Value::as_bool)
22634                    == Some(true))
22635            },
22636        ));
22637        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22638        assert!(matches!(
22639            wait.as_mut().poll(&mut task_context),
22640            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22641        ));
22642        assert!(ctx.take_commands().expect("commands").is_empty());
22643        ctx.ensure_history_consumed().expect("condition consumed");
22644    }
22645
22646    #[test]
22647    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
22648        let open_history = vec![
22649            history_event(
22650                "ConditionWaitOpened",
22651                json!({
22652                    "sequence": 3,
22653                    "condition_wait_id": "condition:3",
22654                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22655                    "condition_key": "two-votes",
22656                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22657                    "timeout_seconds": 120,
22658                }),
22659            ),
22660            history_event(
22661                "SignalReceived",
22662                json!({
22663                    "workflow_sequence": 3,
22664                    "signal_name": "vote",
22665                    "arguments": fixture_envelope(json!(["first"])),
22666                }),
22667            ),
22668        ];
22669        for _worker_before_or_after_restart in 0..2 {
22670            let ctx = workflow_context(open_history.clone());
22671            let predicate_ctx = ctx.clone();
22672            let mut wait = Box::pin(
22673                ctx.wait_condition(
22674                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22675                        .timeout(Duration::from_secs(120)),
22676                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22677                ),
22678            );
22679            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22680            assert!(matches!(
22681                wait.as_mut().poll(&mut task_context),
22682                Poll::Pending
22683            ));
22684            assert_eq!(
22685                ctx.take_commands().expect("reopened condition"),
22686                vec![json!({
22687                    "type": "open_condition_wait",
22688                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22689                    "condition_key": "two-votes",
22690                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22691                    "timeout_seconds": 120,
22692                })]
22693            );
22694        }
22695
22696        let satisfied_ctx = workflow_context(vec![
22697            history_event(
22698                "ConditionWaitOpened",
22699                json!({
22700                    "sequence": 5,
22701                    "condition_wait_id": "condition:5",
22702                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22703                    "condition_key": "approval",
22704                    "condition_definition_fingerprint": "sha256:approval-v1",
22705                }),
22706            ),
22707            history_event(
22708                "ConditionWaitSatisfied",
22709                json!({
22710                    "sequence": 5,
22711                    "condition_wait_id": "condition:5",
22712                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22713                    "condition_key": "approval",
22714                    "condition_definition_fingerprint": "sha256:approval-v1",
22715                }),
22716            ),
22717        ]);
22718        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
22719            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
22720            || Ok(false),
22721        ));
22722        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22723        assert!(matches!(
22724            satisfied.as_mut().poll(&mut task_context),
22725            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22726        ));
22727
22728        let timed_out_ctx = workflow_context(vec![
22729            history_event(
22730                "ConditionWaitOpened",
22731                json!({
22732                    "sequence": 8,
22733                    "condition_wait_id": "condition:8",
22734                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22735                    "condition_key": "approval-timeout",
22736                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
22737                    "timeout_seconds": 5,
22738                }),
22739            ),
22740            history_event(
22741                "TimerScheduled",
22742                json!({
22743                    "sequence": 9,
22744                    "timer_id": "condition-timer:9",
22745                    "timer_kind": "condition_timeout",
22746                    "condition_wait_id": "condition:8",
22747                    "delay_seconds": 5,
22748                }),
22749            ),
22750            history_event(
22751                "TimerFired",
22752                json!({
22753                    "sequence": 9,
22754                    "timer_id": "condition-timer:9",
22755                    "timer_kind": "condition_timeout",
22756                    "condition_wait_id": "condition:8",
22757                    "delay_seconds": 5,
22758                }),
22759            ),
22760        ]);
22761        let mut timed_out = Box::pin(
22762            timed_out_ctx.wait_condition(
22763                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
22764                    .timeout(Duration::from_secs(5)),
22765                || Ok(true),
22766            ),
22767        );
22768        assert!(matches!(
22769            timed_out.as_mut().poll(&mut task_context),
22770            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22771        ));
22772    }
22773
22774    #[test]
22775    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
22776        let ctx = workflow_context(reopened_selection_condition_history());
22777        {
22778            let state = ctx.state.lock().unwrap();
22779            assert!(matches!(
22780                selection_member_recorded_command(&state, 2),
22781                Some(RecordedCommand::ConditionWait {
22782                    sequence: 3,
22783                    result: None,
22784                    ..
22785                })
22786            ));
22787        }
22788        let mut selected = Box::pin(ctx.select_keyed(vec![
22789            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22790            (
22791                "votes",
22792                ParallelOperation::condition(
22793                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22794                    || Ok(true),
22795                ),
22796            ),
22797        ]));
22798        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22799        assert!(selected.as_mut().poll(&mut task_context).is_pending());
22800        assert!(
22801            ctx.take_commands().unwrap().is_empty(),
22802            "true predicate must not reopen the recorded wait"
22803        );
22804        ctx.ensure_history_consumed()
22805            .expect("physical reopens are consumed while canonical selection is pending");
22806    }
22807
22808    #[test]
22809    fn reopened_selection_condition_replays_its_latest_physical_winner() {
22810        for (terminal_type, acknowledge_timeout) in [
22811            ("ConditionWaitSatisfied", false),
22812            ("ConditionWaitTimedOut", false),
22813            ("TimerFired", false),
22814            ("TimerFired", true),
22815        ] {
22816            let mut history = reopened_selection_condition_history();
22817            let original_identity = history[1].payload["condition_wait_id"].clone();
22818            let uses_timer = terminal_type == "TimerFired";
22819            let mut resolution_payload = history[3].payload.clone();
22820            if uses_timer {
22821                for event in &mut history[1..] {
22822                    event.payload["timeout_seconds"] = json!(3);
22823                }
22824                resolution_payload = history[3].payload.clone();
22825                resolution_payload["timer_kind"] = json!("condition_timeout");
22826                resolution_payload["timer_id"] = json!("condition-timeout-3");
22827                resolution_payload["delay_seconds"] = json!(3);
22828                history.push(history_event("TimerScheduled", resolution_payload.clone()));
22829            }
22830            let mut resolution = history_event(terminal_type, resolution_payload.clone());
22831            resolution
22832                .raw
22833                .insert("id".into(), json!("latest-condition-resolution"));
22834            history.push(resolution);
22835            history.push(history_event(
22836                "SelectionResolved",
22837                json!({
22838                    "selection_group_id": "select-calls:1:2",
22839                    "selection_group_base_sequence": 1,
22840                    "selection_group_size": 2,
22841                    "member_key": "votes",
22842                    "member_index": 1,
22843                    "member_base_sequence": 2,
22844                    "member_size": 1,
22845                    "operation_kind": "condition",
22846                    "operation_identity": original_identity,
22847                    "outcome": "completed",
22848                    "resolution_event_id": "latest-condition-resolution",
22849                    "resolution_event_type": terminal_type,
22850                }),
22851            ));
22852            if acknowledge_timeout {
22853                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
22854            }
22855            let ctx = workflow_context(history);
22856            let mut selected = Box::pin(ctx.select_keyed(vec![
22857                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22858                (
22859                    "votes",
22860                    ParallelOperation::condition(
22861                        if uses_timer {
22862                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22863                                .timeout(Duration::from_secs(3))
22864                        } else {
22865                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22866                        },
22867                        || Ok(true),
22868                    ),
22869                ),
22870            ]));
22871            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22872            match selected.as_mut().poll(&mut task_context) {
22873                Poll::Ready(Ok(result)) => {
22874                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
22875                    let expected = if terminal_type == "ConditionWaitSatisfied" {
22876                        ConditionWaitResult::Satisfied
22877                    } else {
22878                        ConditionWaitResult::TimedOut
22879                    };
22880                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
22881                }
22882                other => panic!("latest physical winner must replay: {other:?}"),
22883            }
22884            assert!(ctx.take_commands().unwrap().is_empty());
22885            ctx.ensure_history_consumed()
22886                .expect("winner history consumed");
22887        }
22888    }
22889
22890    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
22891        let fixture: Value = serde_json::from_str(include_str!(
22892            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22893        ))
22894        .expect("grouped condition fixture");
22895        fixture["history"]
22896            .as_array()
22897            .unwrap()
22898            .iter()
22899            .map(|event| {
22900                let mut payload = event["payload"].clone();
22901                let index = payload["parallel_group_index"].as_u64().unwrap();
22902                payload["parallel_group_id"] = json!("select-calls:1:2");
22903                payload["parallel_group_mode"] = json!("select");
22904                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
22905                payload["selection_member_index"] = json!(index);
22906                payload["selection_member_base_sequence"] = json!(index + 1);
22907                payload["selection_member_size"] = json!(1);
22908                payload["selection_member_kind"] =
22909                    json!(if index == 0 { "timer" } else { "condition" });
22910                history_event(event["event_type"].as_str().unwrap(), payload)
22911            })
22912            .collect()
22913    }
22914
22915    #[test]
22916    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
22917        let fixture: Value = serde_json::from_str(include_str!(
22918            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22919        ))
22920        .expect("grouped condition fixture");
22921        let original = fixture["history"].as_array().expect("fixture history");
22922        let decode = |events: &[Value]| {
22923            let history = events
22924                .iter()
22925                .map(|event| {
22926                    history_event(
22927                        event["event_type"].as_str().unwrap(),
22928                        event["payload"].clone(),
22929                    )
22930                })
22931                .collect::<Vec<_>>();
22932            recorded_commands(
22933                &history,
22934                DEFAULT_CODEC,
22935                WorkflowIdentity {
22936                    workflow_id: None,
22937                    run_id: None,
22938                },
22939            )
22940        };
22941        assert!(decode(original).is_ok());
22942        for field in [
22943            "condition_wait_occurrence_id",
22944            "condition_key",
22945            "condition_definition_fingerprint",
22946            "timeout_seconds",
22947            "parallel_group_id",
22948            "parallel_group_size",
22949            "parallel_group_index",
22950        ] {
22951            let mut changed = original.clone();
22952            changed[3]["payload"][field] = match field {
22953                "timeout_seconds" | "parallel_group_size" => json!(30),
22954                "parallel_group_index" => json!(0),
22955                _ => json!("changed"),
22956            };
22957            assert!(
22958                decode(&changed).is_err(),
22959                "reopen must reject changed {field}"
22960            );
22961        }
22962        let mut unsettled = original.clone();
22963        unsettled.remove(2);
22964        assert!(
22965            decode(&unsettled).is_err(),
22966            "physical predecessor must be resolved"
22967        );
22968        let mut timed_out = original.clone();
22969        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
22970        assert!(decode(&timed_out).is_err(), "timeout is terminal");
22971        let mut late_resolution = original.clone();
22972        late_resolution.swap(2, 3);
22973        assert!(
22974            decode(&late_resolution).is_err(),
22975            "later history cannot authorize a reopen"
22976        );
22977    }
22978
22979    #[test]
22980    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
22981        let history = vec![
22982            history_event(
22983                "ConditionWaitOpened",
22984                json!({
22985                    "sequence": 3,
22986                    "condition_wait_id": "condition:3",
22987                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22988                    "condition_key": "two-votes",
22989                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22990                }),
22991            ),
22992            history_event(
22993                "SignalReceived",
22994                json!({
22995                    "workflow_sequence": 3,
22996                    "signal_name": "vote",
22997                    "arguments": fixture_envelope(json!(["first"])),
22998                }),
22999            ),
23000            history_event(
23001                "ConditionWaitSatisfied",
23002                json!({
23003                    "sequence": 3,
23004                    "condition_wait_id": "condition:3",
23005                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23006                    "condition_key": "two-votes",
23007                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23008                }),
23009            ),
23010            history_event(
23011                "ConditionWaitOpened",
23012                json!({
23013                    "sequence": 5,
23014                    "condition_wait_id": "condition:5",
23015                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23016                    "condition_key": "two-votes",
23017                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23018                }),
23019            ),
23020            history_event(
23021                "SignalReceived",
23022                json!({
23023                    "workflow_sequence": 5,
23024                    "signal_name": "vote",
23025                    "arguments": fixture_envelope(json!(["second"])),
23026                }),
23027            ),
23028            history_event(
23029                "ConditionWaitSatisfied",
23030                json!({
23031                    "sequence": 5,
23032                    "condition_wait_id": "condition:5",
23033                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23034                    "condition_key": "two-votes",
23035                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23036                }),
23037            ),
23038        ];
23039        for _cold_worker_or_restart in 0..2 {
23040            let ctx = workflow_context(history.clone());
23041            let predicate_ctx = ctx.clone();
23042            let mut wait = Box::pin(ctx.wait_condition(
23043                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23044                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23045            ));
23046            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23047
23048            assert!(matches!(
23049                wait.as_mut().poll(&mut task_context),
23050                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23051            ));
23052            assert!(ctx.take_commands().expect("commands").is_empty());
23053            ctx.ensure_history_consumed()
23054                .expect("every physical wait-open is consumed");
23055        }
23056    }
23057
23058    #[test]
23059    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
23060        let history = vec![
23061            history_event(
23062                "ConditionWaitOpened",
23063                json!({
23064                    "sequence": 3,
23065                    "condition_wait_id": "condition:3",
23066                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23067                    "condition_key": "approved",
23068                    "condition_definition_fingerprint": "sha256:approved-v1",
23069                }),
23070            ),
23071            history_event(
23072                "UpdateApplied",
23073                json!({
23074                    "sequence": 3,
23075                    "update_id": "update-1",
23076                    "update_name": "approve",
23077                    "arguments": fixture_envelope(json!([false])),
23078                }),
23079            ),
23080            history_event(
23081                "ConditionWaitOpened",
23082                json!({
23083                    "sequence": 5,
23084                    "condition_wait_id": "condition:5",
23085                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23086                    "condition_key": "approved",
23087                    "condition_definition_fingerprint": "sha256:approved-v1",
23088                }),
23089            ),
23090            history_event(
23091                "UpdateApplied",
23092                json!({
23093                    "sequence": 5,
23094                    "update_id": "update-2",
23095                    "update_name": "approve",
23096                    "arguments": fixture_envelope(json!([true])),
23097                }),
23098            ),
23099        ];
23100
23101        for _cold_worker_or_restart in 0..2 {
23102            let ctx = workflow_context(history.clone());
23103            let predicate_ctx = ctx.clone();
23104            let mut wait = Box::pin(ctx.wait_condition(
23105                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
23106                move || {
23107                    Ok(predicate_ctx
23108                        .updates("approve")?
23109                        .last()
23110                        .and_then(|arguments| arguments.first())
23111                        .and_then(Value::as_bool)
23112                        == Some(true))
23113                },
23114            ));
23115            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23116
23117            assert!(matches!(
23118                wait.as_mut().poll(&mut task_context),
23119                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23120            ));
23121            assert!(ctx.take_commands().expect("commands").is_empty());
23122            ctx.ensure_history_consumed()
23123                .expect("every update-driven reopen is consumed");
23124        }
23125    }
23126
23127    #[test]
23128    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23129        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23130            ("shared", "sha256:first", "shared", "sha256:second"),
23131            ("first", "sha256:shared", "second", "sha256:shared"),
23132            ("shared", "sha256:shared", "shared", "sha256:shared"),
23133            ("first", "sha256:first", "second", "sha256:second"),
23134        ] {
23135            let history = vec![
23136                history_event(
23137                    "ConditionWaitOpened",
23138                    json!({
23139                        "sequence": 3,
23140                        "condition_wait_id": "condition:3",
23141                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23142                        "condition_key": first_key,
23143                        "condition_definition_fingerprint": first_fingerprint,
23144                    }),
23145                ),
23146                history_event(
23147                    "ConditionWaitSatisfied",
23148                    json!({
23149                        "sequence": 3,
23150                        "condition_wait_id": "condition:3",
23151                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23152                        "condition_key": first_key,
23153                        "condition_definition_fingerprint": first_fingerprint,
23154                    }),
23155                ),
23156                history_event(
23157                    "ConditionWaitOpened",
23158                    json!({
23159                        "sequence": 4,
23160                        "condition_wait_id": "condition:4",
23161                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23162                        "condition_key": second_key,
23163                        "condition_definition_fingerprint": second_fingerprint,
23164                    }),
23165                ),
23166                history_event(
23167                    "ConditionWaitSatisfied",
23168                    json!({
23169                        "sequence": 4,
23170                        "condition_wait_id": "condition:4",
23171                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23172                        "condition_key": second_key,
23173                        "condition_definition_fingerprint": second_fingerprint,
23174                    }),
23175                ),
23176            ];
23177            for _cold_worker_or_restart in 0..2 {
23178                let ctx = workflow_context(history.clone());
23179                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23180                let mut first = Box::pin(ctx.wait_condition(
23181                    ConditionWaitOptions::new(first_key, first_fingerprint),
23182                    || Ok(false),
23183                ));
23184                assert!(matches!(
23185                    first.as_mut().poll(&mut task_context),
23186                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23187                ));
23188
23189                let mut second = Box::pin(ctx.wait_condition(
23190                    ConditionWaitOptions::new(second_key, second_fingerprint),
23191                    || Ok(false),
23192                ));
23193                assert!(matches!(
23194                    second.as_mut().poll(&mut task_context),
23195                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23196                ));
23197                assert!(ctx.take_commands().expect("commands").is_empty());
23198                ctx.ensure_history_consumed()
23199                    .expect("each authored wait consumes one occurrence");
23200            }
23201        }
23202    }
23203
23204    #[test]
23205    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23206        fn worker() -> Worker {
23207            let client = Client::new("http://127.0.0.1:8080").expect("client");
23208            let mut worker = Worker::new(client, "rust-workers");
23209            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23210                let mut outcomes = Vec::new();
23211                for _ in 0..2 {
23212                    outcomes.push(
23213                        ctx.wait_condition(
23214                            ConditionWaitOptions::new("shared", "sha256:shared"),
23215                            || Ok(false),
23216                        )
23217                        .await?,
23218                    );
23219                }
23220                Ok(json!(outcomes))
23221            });
23222            worker
23223        }
23224
23225        let task = workflow_task(
23226            "rust.condition-loop",
23227            vec![
23228                history_event(
23229                    "ConditionWaitOpened",
23230                    json!({
23231                        "sequence": 1,
23232                        "condition_wait_id": "condition:1",
23233                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23234                        "condition_key": "shared",
23235                        "condition_definition_fingerprint": "sha256:shared",
23236                    }),
23237                ),
23238                history_event(
23239                    "ConditionWaitSatisfied",
23240                    json!({
23241                        "sequence": 1,
23242                        "condition_wait_id": "condition:1",
23243                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23244                        "condition_key": "shared",
23245                        "condition_definition_fingerprint": "sha256:shared",
23246                    }),
23247                ),
23248                history_event(
23249                    "ConditionWaitOpened",
23250                    json!({
23251                        "sequence": 2,
23252                        "condition_wait_id": "condition:2",
23253                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23254                        "condition_key": "shared",
23255                        "condition_definition_fingerprint": "sha256:shared",
23256                    }),
23257                ),
23258                history_event(
23259                    "ConditionWaitSatisfied",
23260                    json!({
23261                        "sequence": 2,
23262                        "condition_wait_id": "condition:2",
23263                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23264                        "condition_key": "shared",
23265                        "condition_definition_fingerprint": "sha256:shared",
23266                    }),
23267                ),
23268            ],
23269            DEFAULT_CODEC,
23270        );
23271
23272        for _cold_worker_or_restart in 0..2 {
23273            let commands = worker()
23274                .execute_workflow_task(task.clone())
23275                .expect("adjacent loop waits replay deterministically");
23276            assert_eq!(commands.len(), 1);
23277            assert_eq!(commands[0]["type"], "complete_workflow");
23278            assert_eq!(
23279                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23280                json!(["satisfied", "satisfied"])
23281            );
23282        }
23283    }
23284
23285    #[test]
23286    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23287        let history = vec![history_event(
23288            "ConditionWaitOpened",
23289            json!({
23290                "sequence": 12,
23291                "condition_wait_id": "condition:12",
23292                "condition_wait_occurrence_id": "rust:condition-wait:0",
23293                "condition_key": "approval",
23294                "condition_definition_fingerprint": "sha256:approval-v1",
23295                "timeout_seconds": 30,
23296            }),
23297        )];
23298        for (options, expected_reason) in [
23299            (
23300                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23301                    .timeout(Duration::from_secs(30)),
23302                "condition_wait_key_mismatch",
23303            ),
23304            (
23305                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23306                    .timeout(Duration::from_secs(30)),
23307                "condition_wait_predicate_mismatch",
23308            ),
23309            (
23310                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23311                    .timeout(Duration::from_secs(29)),
23312                "condition_wait_timeout_mismatch",
23313            ),
23314        ] {
23315            let ctx = workflow_context(history.clone());
23316            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23317            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23318            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23319                wait.as_mut().poll(&mut task_context)
23320            else {
23321                panic!("changed condition definition must fail replay");
23322            };
23323            assert_eq!(failure.reason, expected_reason);
23324            assert_eq!(failure.sequence, Some(12));
23325        }
23326    }
23327
23328    #[test]
23329    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23330        let error = WorkflowState::new(
23331            vec![history_event(
23332                "ConditionWaitOpened",
23333                json!({
23334                    "sequence": 12,
23335                    "condition_wait_id": "condition:12",
23336                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23337                    "condition_key": "approval",
23338                }),
23339            )],
23340            "rust-workers".to_string(),
23341            DEFAULT_CODEC.to_string(),
23342            None,
23343        )
23344        .expect_err("condition history without a predicate fingerprint must fail");
23345
23346        assert!(matches!(
23347            error,
23348            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23349                if reason == "condition_wait_predicate_fingerprint_missing"
23350        ));
23351    }
23352
23353    #[test]
23354    fn condition_wait_history_requires_authored_occurrence_identity() {
23355        let error = WorkflowState::new(
23356            vec![history_event(
23357                "ConditionWaitOpened",
23358                json!({
23359                    "sequence": 12,
23360                    "condition_wait_id": "condition:12",
23361                    "condition_key": "approval",
23362                    "condition_definition_fingerprint": "sha256:approval-v1",
23363                }),
23364            )],
23365            "rust-workers".to_string(),
23366            DEFAULT_CODEC.to_string(),
23367            None,
23368        )
23369        .expect_err("condition history without occurrence identity must fail");
23370
23371        assert!(matches!(
23372            error,
23373            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23374                if reason == "condition_wait_occurrence_id_missing"
23375        ));
23376    }
23377
23378    #[test]
23379    fn typed_search_attribute_updates_validate_emit_and_replay() {
23380        let update = SearchAttributeUpdate::new()
23381            .keyword("OrderStatus", " waiting ")
23382            .expect("keyword")
23383            .int("Attempt", 3)
23384            .expect("int")
23385            .bool("Escalated", false)
23386            .expect("bool")
23387            .keyword_list("Regions", ["us-east", "eu-west"])
23388            .expect("list")
23389            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
23390            .expect("datetime")
23391            .delete("LegacyStatus")
23392            .expect("delete");
23393        let ctx = workflow_context(Vec::new());
23394        ctx.upsert_search_attributes(update.clone())
23395            .expect("typed update");
23396        assert_eq!(
23397            ctx.take_commands().expect("search-attribute command"),
23398            vec![json!({
23399                "type": "upsert_search_attributes",
23400                "attributes": {
23401                    "Attempt": 3,
23402                    "Escalated": false,
23403                    "LegacyStatus": null,
23404                    "OrderStatus": "waiting",
23405                    "Regions": ["us-east", "eu-west"],
23406                    "UpdatedAt": "2026-08-22T04:00:00Z",
23407                },
23408                "attribute_types": {
23409                    "Attempt": "int",
23410                    "Escalated": "bool",
23411                    "OrderStatus": "keyword",
23412                    "Regions": "keyword_list",
23413                    "UpdatedAt": "datetime",
23414                },
23415            })]
23416        );
23417
23418        let replay = workflow_context(vec![history_event(
23419            "SearchAttributesUpserted",
23420            json!({
23421                "sequence": 6,
23422                "attributes": {
23423                    "Attempt": 3,
23424                    "Escalated": false,
23425                    "LegacyStatus": null,
23426                    "OrderStatus": "waiting",
23427                    "Regions": ["us-east", "eu-west"],
23428                    "UpdatedAt": "2026-08-22T04:00:00Z",
23429                },
23430                "attribute_types": {
23431                    "Attempt": "int",
23432                    "Escalated": "bool",
23433                    "OrderStatus": "keyword",
23434                    "Regions": "keyword_list",
23435                    "UpdatedAt": "datetime",
23436                },
23437                "merged": {},
23438            }),
23439        )]);
23440        replay
23441            .upsert_search_attributes(update)
23442            .expect("matching update replays");
23443        assert!(replay.take_commands().expect("commands").is_empty());
23444        replay.ensure_history_consumed().expect("history consumed");
23445
23446        let type_drift = workflow_context(vec![history_event(
23447            "SearchAttributesUpserted",
23448            json!({
23449                "sequence": 7,
23450                "attributes": {"OrderStatus": "waiting"},
23451                "attribute_types": {"OrderStatus": "keyword"},
23452                "merged": {"OrderStatus": "waiting"},
23453            }),
23454        )]);
23455        let error = type_drift
23456            .upsert_search_attributes(
23457                SearchAttributeUpdate::new()
23458                    .string("OrderStatus", "waiting")
23459                    .expect("string update"),
23460            )
23461            .expect_err("same JSON value with a changed type must fail replay");
23462        assert!(matches!(
23463            error,
23464            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23465                if reason == "search_attribute_type_mismatch"
23466        ));
23467
23468        let malformed_types = WorkflowState::new(
23469            vec![history_event(
23470                "SearchAttributesUpserted",
23471                json!({
23472                    "sequence": 8,
23473                    "attributes": {"OrderStatus": "waiting"},
23474                    "attribute_types": {"OrderStatus": "unsupported"},
23475                    "merged": {"OrderStatus": "waiting"},
23476                }),
23477            )],
23478            "rust-workers".to_string(),
23479            DEFAULT_CODEC.to_string(),
23480            None,
23481        )
23482        .expect_err("unsupported search-attribute type metadata must fail");
23483        assert!(matches!(
23484            malformed_types,
23485            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23486                if reason == "search_attribute_types_malformed"
23487        ));
23488
23489        assert!(matches!(
23490            SearchAttributeUpdate::new().keyword("bad key", "value"),
23491            Err(SearchAttributeUpdateError::InvalidKey(_))
23492        ));
23493        assert!(matches!(
23494            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
23495            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
23496        ));
23497        assert!(matches!(
23498            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
23499            Err(SearchAttributeUpdateError::ValueTooLong { .. })
23500        ));
23501        assert!(matches!(
23502            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
23503            Err(SearchAttributeUpdateError::InvalidDateTime(_))
23504        ));
23505        assert!(matches!(
23506            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
23507            Err(Error::InvalidSearchAttributeUpdate(
23508                SearchAttributeUpdateError::Empty
23509            ))
23510        ));
23511    }
23512
23513    #[test]
23514    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23515        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23516        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23517
23518        assert!(SearchAttributeUpdate::new()
23519            .string("AsciiDescription", ascii)
23520            .is_ok());
23521        assert!(SearchAttributeUpdate::new()
23522            .string("Utf8Description", utf8)
23523            .is_ok());
23524        assert!(matches!(
23525            SearchAttributeUpdate::new().string(
23526                "TooLongDescription",
23527                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23528            ),
23529            Err(SearchAttributeUpdateError::ValueTooLong {
23530                kind: "string",
23531                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23532                ..
23533            })
23534        ));
23535    }
23536
23537    #[test]
23538    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23539        let lone_fire = WorkflowState::new(
23540            vec![history_event(
23541                "TimerFired",
23542                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23543            )],
23544            "rust-workers".to_string(),
23545            DEFAULT_CODEC.to_string(),
23546            None,
23547        )
23548        .expect_err("TimerFired requires TimerScheduled");
23549        assert!(matches!(
23550            lone_fire,
23551            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23552                if reason == "timer_schedule_missing_or_duplicate"
23553        ));
23554
23555        let wrong_identity = WorkflowState::new(
23556            vec![
23557                history_event(
23558                    "TimerScheduled",
23559                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23560                ),
23561                history_event(
23562                    "TimerFired",
23563                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23564                ),
23565            ],
23566            "rust-workers".to_string(),
23567            DEFAULT_CODEC.to_string(),
23568            None,
23569        )
23570        .expect_err("fire must match scheduled timer identity");
23571        assert!(matches!(
23572            wrong_identity,
23573            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23574                if reason == "timer_identity_mismatch"
23575        ));
23576
23577        let duplicate_fire = WorkflowState::new(
23578            vec![
23579                history_event(
23580                    "TimerScheduled",
23581                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23582                ),
23583                history_event(
23584                    "TimerFired",
23585                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23586                ),
23587                history_event(
23588                    "TimerFired",
23589                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23590                ),
23591            ],
23592            "rust-workers".to_string(),
23593            DEFAULT_CODEC.to_string(),
23594            None,
23595        )
23596        .expect_err("a durable timer cannot fire twice");
23597        assert!(matches!(
23598            duplicate_fire,
23599            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23600                if reason == "duplicate_timer_fire"
23601        ));
23602
23603        let wrong_fired_delay = WorkflowState::new(
23604            vec![
23605                history_event(
23606                    "TimerScheduled",
23607                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23608                ),
23609                history_event(
23610                    "TimerFired",
23611                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
23612                ),
23613            ],
23614            "rust-workers".to_string(),
23615            DEFAULT_CODEC.to_string(),
23616            None,
23617        )
23618        .expect_err("timer schedule and fire delays must agree");
23619        assert!(matches!(
23620            wrong_fired_delay,
23621            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23622                if reason == "timer_history_delay_mismatch"
23623        ));
23624    }
23625
23626    #[test]
23627    fn replay_rejects_activity_moved_before_recorded_timer() {
23628        let ctx = workflow_context(vec![
23629            history_event(
23630                "TimerScheduled",
23631                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23632            ),
23633            history_event(
23634                "TimerFired",
23635                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23636            ),
23637            history_event(
23638                "ActivityCompleted",
23639                json!({
23640                    "sequence": 2,
23641                    "activity_type": "after-timer",
23642                    "payload_codec": DEFAULT_CODEC,
23643                    "result": fixture_envelope(json!("done")),
23644                }),
23645            ),
23646        ]);
23647        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
23648        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23649
23650        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23651            activity.as_mut().poll(&mut task_context)
23652        else {
23653            panic!("reordered durable command must be rejected");
23654        };
23655        assert_eq!(failure.reason, "recorded_command_mismatch");
23656        assert_eq!(failure.sequence, Some(1));
23657        assert_eq!(failure.expected.as_deref(), Some("timer"));
23658        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
23659    }
23660
23661    #[test]
23662    fn workflow_context_emits_a_typed_named_signal_wait() {
23663        let ctx = workflow_context(Vec::new());
23664        let mut signal = Box::pin(ctx.wait_signal("finish"));
23665        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23666
23667        assert!(matches!(
23668            signal.as_mut().poll(&mut task_context),
23669            Poll::Pending
23670        ));
23671        assert_eq!(
23672            ctx.take_commands().expect("signal-wait command"),
23673            vec![json!({
23674                "type": "open_signal_wait",
23675                "signal_name": "finish",
23676            })]
23677        );
23678    }
23679
23680    #[test]
23681    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
23682        let ctx = workflow_context(Vec::new());
23683        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
23684        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23685
23686        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
23687        else {
23688            panic!("runtime-reserved signal should be rejected");
23689        };
23690        assert!(message.contains("reserved by the workflow runtime"));
23691        assert!(ctx.take_commands().expect("commands").is_empty());
23692    }
23693
23694    #[tokio::test]
23695    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
23696        let client = Client::builder("http://127.0.0.1:9")
23697            .build()
23698            .expect("client");
23699        let error = client
23700            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
23701            .await
23702            .expect_err("runtime-reserved signal should be rejected before transport");
23703
23704        assert!(
23705            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
23706        );
23707    }
23708
23709    #[test]
23710    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
23711        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23712            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23713                value.to_string(),
23714            )]))
23715            .expect("message payload");
23716            json!({
23717                "schema": MESSAGE_STREAM_SCHEMA,
23718                "stream_name": "orders",
23719                "message_id": message_id,
23720                "position": position,
23721                "payload_envelope": payload,
23722            })
23723        }
23724
23725        fn opened(sequence: u64) -> HistoryEvent {
23726            history_event(
23727                "SignalWaitOpened",
23728                json!({
23729                    "sequence": sequence,
23730                    "signal_name": MESSAGE_STREAM_SIGNAL,
23731                }),
23732            )
23733        }
23734
23735        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23736            history_event(
23737                "SignalApplied",
23738                json!({
23739                    "sequence": sequence,
23740                    "signal_name": MESSAGE_STREAM_SIGNAL,
23741                    "value": fixture_envelope(json!([delivery])),
23742                }),
23743            )
23744        }
23745
23746        fn received(delivery: Value) -> HistoryEvent {
23747            history_event(
23748                "SignalReceived",
23749                json!({
23750                    "signal_name": MESSAGE_STREAM_SIGNAL,
23751                    "arguments": fixture_envelope(json!([delivery])),
23752                    "payload_codec": DEFAULT_CODEC,
23753                }),
23754            )
23755        }
23756
23757        let client = Client::new("http://127.0.0.1:8080").expect("client");
23758        let mut worker = Worker::new(client, "rust-workers");
23759        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
23760            let messages = ctx.message_stream("orders")?.receive(2).await?;
23761            Ok(json!(messages
23762                .into_iter()
23763                .map(|message| message.message_id)
23764                .collect::<Vec<_>>()))
23765        });
23766
23767        let first = delivery("message-1", 1, "one");
23768        let second = delivery("message-2", 2, "two");
23769        let batch = worker
23770            .execute_workflow_task_decision(workflow_task(
23771                "rust.message-stream-batch",
23772                vec![
23773                    opened(1),
23774                    received(first.clone()),
23775                    applied(1, first.clone()),
23776                    received(first.clone()),
23777                    received(second),
23778                ],
23779                DEFAULT_CODEC,
23780            ))
23781            .expect("worker task consumes the available batch");
23782
23783        assert_eq!(batch.commands.len(), 1);
23784        assert_eq!(batch.commands[0]["type"], "complete_workflow");
23785        assert_eq!(
23786            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
23787                .expect("workflow result"),
23788            json!(["message-1", "message-2"])
23789        );
23790        assert_eq!(
23791            batch.message_stream_cursors,
23792            vec![json!({"stream_name": "orders", "through_position": 2})]
23793        );
23794        assert!(batch.message_stream_waits.is_empty());
23795
23796        let partial = worker
23797            .execute_workflow_task_decision(workflow_task(
23798                "rust.message-stream-batch",
23799                vec![opened(1), received(first.clone()), applied(1, first)],
23800                DEFAULT_CODEC,
23801            ))
23802            .expect("worker task returns without waiting for a missing second item");
23803        assert_eq!(partial.commands.len(), 1);
23804        assert_eq!(partial.commands[0]["type"], "complete_workflow");
23805        assert_eq!(
23806            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
23807                .expect("workflow result"),
23808            json!(["message-1"])
23809        );
23810        assert_eq!(
23811            partial.message_stream_cursors,
23812            vec![json!({"stream_name": "orders", "through_position": 1})]
23813        );
23814        assert!(partial.message_stream_waits.is_empty());
23815    }
23816
23817    #[test]
23818    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
23819        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23820            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23821                value.to_string(),
23822            )]))
23823            .expect("message payload");
23824            json!({
23825                "schema": MESSAGE_STREAM_SCHEMA,
23826                "stream_name": "orders",
23827                "message_id": message_id,
23828                "position": position,
23829                "payload_envelope": payload,
23830            })
23831        }
23832
23833        fn opened(sequence: u64) -> HistoryEvent {
23834            history_event(
23835                "SignalWaitOpened",
23836                json!({
23837                    "sequence": sequence,
23838                    "signal_name": MESSAGE_STREAM_SIGNAL,
23839                }),
23840            )
23841        }
23842
23843        fn received(delivery: Value) -> HistoryEvent {
23844            history_event(
23845                "SignalReceived",
23846                json!({
23847                    "signal_name": MESSAGE_STREAM_SIGNAL,
23848                    "arguments": fixture_envelope(json!([delivery])),
23849                    "payload_codec": DEFAULT_CODEC,
23850                }),
23851            )
23852        }
23853
23854        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23855            history_event(
23856                "SignalApplied",
23857                json!({
23858                    "sequence": sequence,
23859                    "signal_name": MESSAGE_STREAM_SIGNAL,
23860                    "value": fixture_envelope(json!([delivery])),
23861                }),
23862            )
23863        }
23864
23865        let client = Client::new("http://127.0.0.1:8080").expect("client");
23866        let mut worker = Worker::new(client, "rust-workers");
23867        worker.register_workflow(
23868            "rust.message-stream-partial-batches",
23869            |ctx, _input| async move {
23870                let stream = ctx.message_stream("orders")?;
23871                let first = stream.receive(10).await?;
23872                let second = stream.receive(10).await?;
23873                Ok(json!([
23874                    first
23875                        .into_iter()
23876                        .map(|message| message.message_id)
23877                        .collect::<Vec<_>>(),
23878                    second
23879                        .into_iter()
23880                        .map(|message| message.message_id)
23881                        .collect::<Vec<_>>(),
23882                ]))
23883            },
23884        );
23885
23886        let first = delivery("message-1", 1, "one");
23887        let second = delivery("message-2", 2, "two");
23888        let decision = worker
23889            .execute_workflow_task_decision(workflow_task(
23890                "rust.message-stream-partial-batches",
23891                vec![
23892                    opened(1),
23893                    received(first.clone()),
23894                    applied(1, first),
23895                    opened(2),
23896                    received(second.clone()),
23897                    applied(2, second),
23898                ],
23899                DEFAULT_CODEC,
23900            ))
23901            .expect("cold replay preserves both authored receive boundaries");
23902
23903        assert_eq!(decision.commands.len(), 1);
23904        assert_eq!(decision.commands[0]["type"], "complete_workflow");
23905        assert_eq!(
23906            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
23907                .expect("workflow result"),
23908            json!([["message-1"], ["message-2"]])
23909        );
23910        assert_eq!(
23911            decision.message_stream_cursors,
23912            vec![json!({"stream_name": "orders", "through_position": 2})]
23913        );
23914        assert!(decision.message_stream_waits.is_empty());
23915    }
23916
23917    #[test]
23918    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
23919        let ctx = workflow_context(Vec::new());
23920        let stream = ctx.message_stream("orders").expect("message stream");
23921        let mut receive = Box::pin(stream.receive(10));
23922        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23923
23924        assert!(matches!(
23925            receive.as_mut().poll(&mut task_context),
23926            Poll::Pending
23927        ));
23928        assert_eq!(
23929            ctx.take_commands().expect("message-stream wait command"),
23930            vec![json!({
23931                "type": "open_signal_wait",
23932                "signal_name": MESSAGE_STREAM_SIGNAL,
23933            })]
23934        );
23935        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23936        assert!(cursors.is_empty());
23937        assert_eq!(
23938            waits,
23939            vec![json!({"stream_name": "orders", "after_position": 0})]
23940        );
23941    }
23942
23943    #[test]
23944    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
23945        let ctx = workflow_context(vec![history_event(
23946            "SignalReceived",
23947            json!({
23948                "signal_name": MESSAGE_STREAM_SIGNAL,
23949                "arguments": fixture_envelope(json!([{
23950                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
23951                    "stream_name": "orders",
23952                    "through_position": 2,
23953                }])),
23954                "payload_codec": DEFAULT_CODEC,
23955            }),
23956        )]);
23957        let stream = ctx.message_stream("orders").expect("message stream");
23958        let mut receive = Box::pin(stream.receive(10));
23959        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23960
23961        assert!(matches!(
23962            receive.as_mut().poll(&mut task_context),
23963            Poll::Pending
23964        ));
23965        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23966        assert_eq!(
23967            cursors,
23968            vec![json!({"stream_name": "orders", "through_position": 2})]
23969        );
23970        assert_eq!(
23971            waits,
23972            vec![json!({"stream_name": "orders", "after_position": 2})]
23973        );
23974    }
23975
23976    #[test]
23977    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
23978        let mut empty_map = BTreeMap::new();
23979        let mut nested = BTreeMap::new();
23980        nested.insert(
23981            "value".to_string(),
23982            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
23983        );
23984        let values = vec![
23985            AvroValue::Bytes(vec![0, 255]),
23986            AvroValue::Long(1),
23987            AvroValue::Double(1.0),
23988            AvroValue::Array(Vec::new()),
23989            AvroValue::Map(std::mem::take(&mut empty_map)),
23990            AvroValue::Map(nested),
23991        ];
23992        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
23993        let transport = vec![json!({
23994            "schema": MESSAGE_STREAM_SCHEMA,
23995            "stream_name": "orders",
23996            "message_id": "message-1",
23997            "position": 1,
23998            "payload_envelope": payload,
23999        })];
24000
24001        for _ in 0..2 {
24002            let Some(MessageStreamDelivery::Message(message)) =
24003                decode_message_stream_delivery(transport.clone()).expect("delivery")
24004            else {
24005                panic!("message delivery expected");
24006            };
24007            assert_eq!(message.arguments, values);
24008            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
24009            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
24010        }
24011    }
24012
24013    #[test]
24014    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
24015        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24016            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24017                value.to_string(),
24018            )]))
24019            .expect("message payload");
24020            json!({
24021                "schema": MESSAGE_STREAM_SCHEMA,
24022                "stream_name": "orders",
24023                "message_id": message_id,
24024                "position": position,
24025                "payload_envelope": payload,
24026            })
24027        }
24028
24029        fn opened(sequence: u64) -> HistoryEvent {
24030            history_event(
24031                "SignalWaitOpened",
24032                json!({
24033                    "sequence": sequence,
24034                    "signal_name": MESSAGE_STREAM_SIGNAL,
24035                }),
24036            )
24037        }
24038
24039        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24040            history_event(
24041                "SignalApplied",
24042                json!({
24043                    "sequence": sequence,
24044                    "signal_name": MESSAGE_STREAM_SIGNAL,
24045                    "value": fixture_envelope(json!([delivery])),
24046                }),
24047            )
24048        }
24049
24050        fn worker() -> Worker {
24051            let client = Client::new("http://127.0.0.1:8080").expect("client");
24052            let mut worker = Worker::new(client, "rust-workers");
24053            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
24054                let stream = ctx.message_stream("orders")?;
24055                let first = stream.receive_one().await?;
24056                let second = stream.receive_one().await?;
24057                Ok(json!([first.message_id, second.message_id]))
24058            });
24059            worker
24060        }
24061
24062        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
24063            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
24064            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
24065            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
24066            task
24067        }
24068
24069        let waiting = worker()
24070            .execute_workflow_task_decision(workflow_task(
24071                "rust.message-stream",
24072                Vec::new(),
24073                DEFAULT_CODEC,
24074            ))
24075            .expect("first worker opens the stream wait");
24076        assert_eq!(
24077            waiting.commands,
24078            vec![json!({
24079                "type": "open_signal_wait",
24080                "signal_name": MESSAGE_STREAM_SIGNAL,
24081            })]
24082        );
24083        assert!(waiting.message_stream_cursors.is_empty());
24084        assert_eq!(
24085            waiting.message_stream_waits,
24086            vec![json!({"stream_name": "orders", "after_position": 0})]
24087        );
24088
24089        let first_delivery = delivery("message-1", 1, "one");
24090        let first_arrival = worker()
24091            .execute_workflow_task_decision(task_with_resume(
24092                vec![opened(1)],
24093                first_delivery.clone(),
24094            ))
24095            .expect("replacement worker consumes the first arrival");
24096        assert_eq!(
24097            first_arrival.commands,
24098            vec![json!({
24099                "type": "open_signal_wait",
24100                "signal_name": MESSAGE_STREAM_SIGNAL,
24101            })]
24102        );
24103        assert_eq!(
24104            first_arrival.message_stream_cursors,
24105            vec![json!({"stream_name": "orders", "through_position": 1})]
24106        );
24107        assert_eq!(
24108            first_arrival.message_stream_waits,
24109            vec![json!({"stream_name": "orders", "after_position": 1})]
24110        );
24111
24112        let second_delivery = delivery("message-2", 2, "two");
24113        let first_applied = applied(1, first_delivery);
24114        let completed = worker()
24115            .execute_workflow_task_decision(task_with_resume(
24116                vec![opened(1), first_applied.clone(), opened(2)],
24117                second_delivery.clone(),
24118            ))
24119            .expect("next replacement worker consumes the second arrival");
24120        assert_eq!(completed.commands.len(), 1);
24121        assert_eq!(completed.commands[0]["type"], "complete_workflow");
24122        assert_eq!(
24123            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24124                .expect("workflow result"),
24125            json!(["message-1", "message-2"])
24126        );
24127        assert_eq!(
24128            completed.message_stream_cursors,
24129            vec![json!({"stream_name": "orders", "through_position": 2})]
24130        );
24131        assert!(completed.message_stream_waits.is_empty());
24132
24133        let replay_history = vec![
24134            opened(1),
24135            first_applied,
24136            opened(2),
24137            applied(2, second_delivery),
24138        ];
24139        for _cold_worker_or_restart in 0..2 {
24140            let replayed = worker()
24141                .execute_workflow_task_decision(workflow_task(
24142                    "rust.message-stream",
24143                    replay_history.clone(),
24144                    DEFAULT_CODEC,
24145                ))
24146                .expect("cold worker replays each logical message exactly once");
24147            assert_eq!(replayed.commands.len(), 1);
24148            assert_eq!(
24149                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24150                    .expect("replayed workflow result"),
24151                json!(["message-1", "message-2"])
24152            );
24153            assert_eq!(
24154                replayed.message_stream_cursors,
24155                vec![json!({"stream_name": "orders", "through_position": 2})]
24156            );
24157            assert!(replayed.message_stream_waits.is_empty());
24158        }
24159    }
24160
24161    #[test]
24162    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24163        assert!(!worker_protocol_supports_message_streams("1.14"));
24164        assert!(worker_protocol_supports_message_streams("1.15"));
24165        assert!(worker_protocol_supports_message_streams("1.16"));
24166        assert!(worker_protocol_supports_message_streams(
24167            WORKER_PROTOCOL_VERSION
24168        ));
24169        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24170    }
24171
24172    #[test]
24173    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24174        let ctx = workflow_context(vec![
24175            history_event(
24176                "ConditionWaitOpened",
24177                json!({
24178                    "sequence": 1,
24179                    "condition_wait_id": "condition:1",
24180                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24181                    "condition_key": "signal:finish",
24182                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24183                }),
24184            ),
24185            history_event(
24186                "ConditionWaitSatisfied",
24187                json!({
24188                    "sequence": 1,
24189                    "condition_wait_id": "condition:1",
24190                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24191                    "condition_key": "signal:finish",
24192                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24193                }),
24194            ),
24195            history_event(
24196                "SignalReceived",
24197                json!({"signal_name": "finish", "arguments": []}),
24198            ),
24199        ]);
24200        let mut signal = Box::pin(ctx.wait_signal("finish"));
24201        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24202
24203        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24204            signal.as_mut().poll(&mut task_context)
24205        else {
24206            panic!("condition history must not resolve as a typed signal wait");
24207        };
24208        assert_eq!(failure.reason, "recorded_command_mismatch");
24209        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24210    }
24211
24212    #[test]
24213    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24214        let signal_then_timer = vec![
24215            history_event(
24216                "SignalWaitOpened",
24217                json!({"sequence": 1, "signal_name": "go"}),
24218            ),
24219            history_event(
24220                "SignalApplied",
24221                json!({
24222                    "sequence": 1,
24223                    "signal_name": "go",
24224                    "value": fixture_envelope(json!(["now"])),
24225                }),
24226            ),
24227            history_event(
24228                "TimerScheduled",
24229                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24230            ),
24231            history_event(
24232                "TimerFired",
24233                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24234            ),
24235        ];
24236
24237        let ctx = workflow_context(signal_then_timer.clone());
24238        let mut signal = Box::pin(ctx.wait_signal("go"));
24239        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24240        assert!(matches!(
24241            signal.as_mut().poll(&mut task_context),
24242            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24243        ));
24244        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24245        assert!(matches!(
24246            timer.as_mut().poll(&mut task_context),
24247            Poll::Ready(Ok(()))
24248        ));
24249        ctx.ensure_history_consumed()
24250            .expect("signal and timer history consumed in order");
24251
24252        let reordered = workflow_context(signal_then_timer);
24253        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24254        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24255            timer_first.as_mut().poll(&mut task_context)
24256        else {
24257            panic!("timer cannot consume signal-wait-first history");
24258        };
24259        assert_eq!(failure.reason, "recorded_command_mismatch");
24260        assert_eq!(failure.sequence, Some(1));
24261        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24262
24263        let timer_then_signal = vec![
24264            history_event(
24265                "TimerScheduled",
24266                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24267            ),
24268            history_event(
24269                "TimerFired",
24270                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24271            ),
24272            history_event(
24273                "SignalWaitOpened",
24274                json!({"sequence": 2, "signal_name": "go"}),
24275            ),
24276            history_event(
24277                "SignalApplied",
24278                json!({
24279                    "sequence": 2,
24280                    "signal_name": "go",
24281                    "value": fixture_envelope(json!([])),
24282                }),
24283            ),
24284        ];
24285        let reordered = workflow_context(timer_then_signal);
24286        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24287        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24288            signal_first.as_mut().poll(&mut task_context)
24289        else {
24290            panic!("signal wait cannot consume timer-first history");
24291        };
24292        assert_eq!(failure.reason, "recorded_command_mismatch");
24293        assert_eq!(failure.sequence, Some(1));
24294        assert_eq!(failure.expected.as_deref(), Some("timer"));
24295    }
24296
24297    #[test]
24298    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24299        let duplicate_timer = WorkflowState::new(
24300            vec![
24301                history_event(
24302                    "TimerScheduled",
24303                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24304                ),
24305                history_event(
24306                    "TimerScheduled",
24307                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24308                ),
24309            ],
24310            "rust-workers".to_string(),
24311            DEFAULT_CODEC.to_string(),
24312            None,
24313        )
24314        .expect_err("one workflow sequence cannot schedule two timers");
24315        assert!(matches!(
24316            duplicate_timer,
24317            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24318                if reason == "timer_schedule_missing_or_duplicate"
24319        ));
24320
24321        let colliding_kinds = WorkflowState::new(
24322            vec![
24323                history_event(
24324                    "TimerScheduled",
24325                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24326                ),
24327                history_event(
24328                    "ActivityCompleted",
24329                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24330                ),
24331            ],
24332            "rust-workers".to_string(),
24333            DEFAULT_CODEC.to_string(),
24334            None,
24335        )
24336        .expect_err("one workflow sequence cannot identify two command kinds");
24337        assert!(matches!(
24338            colliding_kinds,
24339            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24340                if reason == "durable_command_sequence_collision"
24341        ));
24342
24343        let duplicate_signal_wait = WorkflowState::new(
24344            vec![
24345                history_event(
24346                    "SignalWaitOpened",
24347                    json!({"sequence": 1, "signal_name": "go"}),
24348                ),
24349                history_event(
24350                    "SignalWaitOpened",
24351                    json!({"sequence": 1, "signal_name": "go"}),
24352                ),
24353            ],
24354            "rust-workers".to_string(),
24355            DEFAULT_CODEC.to_string(),
24356            None,
24357        )
24358        .expect_err("one workflow sequence cannot open two signal waits");
24359        assert!(matches!(
24360            duplicate_signal_wait,
24361            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24362                if reason == "signal_wait_open_missing_or_duplicate"
24363        ));
24364    }
24365
24366    #[test]
24367    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
24368        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
24369            .expect("side-effect result");
24370        let ctx = workflow_context(vec![history_event(
24371            "SideEffectRecorded",
24372            json!({"sequence": 99, "result": result}),
24373        )]);
24374
24375        let replayed: Value = ctx
24376            .side_effect(|| panic!("recorded side effect must not run"))
24377            .expect("positive global workflow sequence is valid");
24378        assert_eq!(replayed, json!({"captured": true}));
24379        ctx.ensure_history_consumed().expect("history consumed");
24380    }
24381
24382    #[test]
24383    fn workflow_history_rejects_zero_and_descending_command_sequences() {
24384        let result =
24385            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
24386        let zero = WorkflowState::new(
24387            vec![history_event(
24388                "SideEffectRecorded",
24389                json!({"sequence": 0, "result": result.clone()}),
24390            )],
24391            "rust-workers".to_string(),
24392            DEFAULT_CODEC.to_string(),
24393            None,
24394        )
24395        .expect_err("durable command sequences must be positive");
24396        assert!(matches!(
24397            zero,
24398            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24399                if reason == "durable_command_sequence_invalid"
24400        ));
24401
24402        let descending = WorkflowState::new(
24403            vec![
24404                history_event(
24405                    "SideEffectRecorded",
24406                    json!({"sequence": 3, "result": result}),
24407                ),
24408                history_event(
24409                    "VersionMarkerRecorded",
24410                    json!({
24411                        "sequence": 2,
24412                        "change_id": "descending-marker",
24413                        "version": 1,
24414                        "min_supported": 1,
24415                        "max_supported": 1,
24416                    }),
24417                ),
24418            ],
24419            "rust-workers".to_string(),
24420            DEFAULT_CODEC.to_string(),
24421            None,
24422        )
24423        .expect_err("new durable commands must remain strictly ordered");
24424        let Error::NonDeterministicReplay(failure) = descending else {
24425            panic!("expected typed replay failure");
24426        };
24427        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
24428        assert_eq!(failure.sequence, Some(2));
24429        assert_eq!(
24430            failure.expected.as_deref(),
24431            Some("workflow sequence greater than 3")
24432        );
24433        assert_eq!(failure.actual.as_deref(), Some("2"));
24434    }
24435
24436    #[test]
24437    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
24438        fn worker() -> Worker {
24439            let client = Client::new("http://127.0.0.1:8080").expect("client");
24440            let mut worker = Worker::new(client, "rust-workers");
24441            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
24442                ctx.wait_signal("finish").await?;
24443                let marker: String =
24444                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
24445                assert_eq!(marker, "after-finish");
24446                Ok(json!("finished"))
24447            });
24448            worker
24449        }
24450
24451        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
24452            .expect("side-effect result");
24453        let task = workflow_task(
24454            "rust.finish-after-gaps",
24455            vec![
24456                history_event(
24457                    "SignalWaitOpened",
24458                    json!({"sequence": 1, "signal_name": "finish"}),
24459                ),
24460                history_event(
24461                    "SignalReceived",
24462                    json!({
24463                        "signal_id": "increment-3",
24464                        "signal_name": "increment",
24465                        "workflow_sequence": 2,
24466                        "payload_codec": DEFAULT_CODEC,
24467                        "arguments": fixture_envelope(json!([3])),
24468                    }),
24469                ),
24470                history_event(
24471                    "SignalReceived",
24472                    json!({
24473                        "signal_id": "increment-5",
24474                        "signal_name": "increment",
24475                        "workflow_sequence": 3,
24476                        "payload_codec": DEFAULT_CODEC,
24477                        "arguments": fixture_envelope(json!([5])),
24478                    }),
24479                ),
24480                history_event(
24481                    "SignalReceived",
24482                    json!({
24483                        "signal_id": "finish",
24484                        "signal_name": "finish",
24485                        "workflow_sequence": 4,
24486                        "payload_codec": DEFAULT_CODEC,
24487                        "arguments": fixture_envelope(json!([])),
24488                    }),
24489                ),
24490                history_event(
24491                    "SignalApplied",
24492                    json!({
24493                        "sequence": 1,
24494                        "signal_id": "finish",
24495                        "signal_name": "finish",
24496                        "payload_codec": DEFAULT_CODEC,
24497                        "value": fixture_envelope(json!([])),
24498                    }),
24499                ),
24500                history_event(
24501                    "SideEffectRecorded",
24502                    json!({"sequence": 5, "result": marker}),
24503                ),
24504            ],
24505            DEFAULT_CODEC,
24506        );
24507
24508        for _original_or_cold_worker in 0..2 {
24509            let commands = worker()
24510                .execute_workflow_task(task.clone())
24511                .expect("signal gaps preserve deterministic replay");
24512            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24513            assert_eq!(commands[0]["type"], "complete_workflow");
24514            assert_eq!(
24515                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24516                json!("finished")
24517            );
24518        }
24519    }
24520
24521    #[test]
24522    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24523        let ctx = workflow_context(Vec::new());
24524        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24525        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24526        assert!(matches!(
24527            sleep.as_mut().poll(&mut task_context),
24528            Poll::Ready(Err(Error::TimerDurationOverflow))
24529        ));
24530        assert!(ctx.take_commands().expect("commands").is_empty());
24531    }
24532
24533    #[test]
24534    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24535        let entries = AvroValue::Map(BTreeMap::from([
24536            ("text".to_string(), AvroValue::String("same".to_string())),
24537            (
24538                "nested".to_string(),
24539                AvroValue::Map(BTreeMap::from([
24540                    ("beta".to_string(), AvroValue::Long(2)),
24541                    ("alpha".to_string(), AvroValue::Long(1)),
24542                ])),
24543            ),
24544            ("long".to_string(), AvroValue::Long(7)),
24545            ("double".to_string(), AvroValue::Double(7.0)),
24546            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24547        ]));
24548        let ctx = workflow_context(Vec::new());
24549        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24550        let commands = ctx.take_commands().expect("commands");
24551
24552        assert_eq!(commands.len(), 1);
24553        assert_eq!(commands[0]["type"], "upsert_memo");
24554        let server_entries = json!({
24555            "codec": "avro",
24556            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24557        });
24558        assert_eq!(
24559            commands[0]["entries"]
24560                .as_object()
24561                .expect("entries envelope")
24562                .keys()
24563                .collect::<Vec<_>>(),
24564            vec!["blob", "codec"]
24565        );
24566        assert_eq!(commands[0]["entries"], server_entries);
24567        let wire_entries =
24568            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24569        assert_eq!(wire_entries, entries);
24570
24571        let history = vec![history_event(
24572            "MemoUpserted",
24573            json!({
24574                "sequence": 1,
24575                "entries": server_entries.clone(),
24576                "merged": server_entries,
24577            }),
24578        )];
24579        let replay = workflow_context(history.clone());
24580        replay
24581            .upsert_memo(entries.clone())
24582            .expect("matching replay identity");
24583        assert!(replay.take_commands().expect("replay commands").is_empty());
24584
24585        let changed_types = AvroValue::Map(BTreeMap::from([
24586            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
24587            (
24588                "nested".to_string(),
24589                AvroValue::Map(BTreeMap::from([
24590                    ("alpha".to_string(), AvroValue::Long(1)),
24591                    ("beta".to_string(), AvroValue::Long(2)),
24592                ])),
24593            ),
24594            ("long".to_string(), AvroValue::Double(7.0)),
24595            ("double".to_string(), AvroValue::Long(7)),
24596            ("binary".to_string(), AvroValue::String("same".to_string())),
24597        ]));
24598        let error = workflow_context(history)
24599            .upsert_memo(changed_types)
24600            .expect_err("memo replay identity must preserve Avro value types");
24601        assert!(matches!(
24602            error,
24603            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24604        ));
24605    }
24606
24607    #[test]
24608    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
24609        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
24610            .expect("memo envelope");
24611        let replay = workflow_context(vec![history_event(
24612            "MemoUpserted",
24613            json!({
24614                "sequence": 1,
24615                "entries": original.clone(),
24616                "merged": original
24617            }),
24618        )]);
24619        let error = replay
24620            .upsert_memo(json!({"stage": "changed"}))
24621            .expect_err("changed memo update must fail replay");
24622        assert!(matches!(
24623            error,
24624            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24625        ));
24626
24627        let invalid = workflow_context(Vec::new())
24628            .upsert_memo(
24629                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
24630            )
24631            .expect_err("oversized key");
24632        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
24633    }
24634
24635    #[test]
24636    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
24637        let negative_zero = AvroValue::Map(BTreeMap::from([(
24638            "reading".to_string(),
24639            AvroValue::Double(-0.0),
24640        )]));
24641        let negative_zero_envelope =
24642            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
24643        let history = vec![history_event(
24644            "MemoUpserted",
24645            json!({
24646                "sequence": 1,
24647                "entries": negative_zero_envelope.clone(),
24648                "merged": negative_zero_envelope,
24649            }),
24650        )];
24651
24652        workflow_context(history.clone())
24653            .upsert_memo(negative_zero)
24654            .expect("matching negative-zero history identity");
24655
24656        let error = workflow_context(history)
24657            .upsert_memo(AvroValue::Map(BTreeMap::from([(
24658                "reading".to_string(),
24659                AvroValue::Double(0.0),
24660            )])))
24661            .expect_err("positive zero must not consume negative-zero memo history");
24662        assert!(matches!(
24663            error,
24664            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24665        ));
24666    }
24667
24668    #[test]
24669    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
24670        let supported = json!({
24671            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
24672            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
24673        });
24674        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
24675        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
24676            "workflow_memo_updates": {"supported": false},
24677            "supported_workflow_task_commands": ["upsert_memo"]
24678        }))));
24679        assert!(commands_use_workflow_memo_updates(&[json!({
24680            "type": "upsert_memo",
24681            "entries": {"stage": "processing"}
24682        })]));
24683    }
24684
24685    #[test]
24686    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
24687        let client = Client::new("http://127.0.0.1:8080").expect("client");
24688        let mut worker = Worker::new(client, "rust-workers");
24689        worker.register_workflow("rust.timer", |ctx, _input| async move {
24690            ctx.sleep(Duration::from_secs(5)).await?;
24691            ctx.activity("after-timer", json!([])).await
24692        });
24693
24694        let task = |history_events| WorkflowTask {
24695            task_id: "wft-rust-timer-1".to_string(),
24696            workflow_command_id: None,
24697            workflow_id: Some("wf-rust-timer".to_string()),
24698            run_id: Some("run-rust-timer".to_string()),
24699            workflow_type: "rust.timer".to_string(),
24700            cancel_requested: false,
24701            payload_codec: DEFAULT_CODEC.to_string(),
24702            arguments: Some(
24703                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24704            ),
24705            history_events,
24706            total_history_events: None,
24707            history_size_bytes: None,
24708            continue_as_new_recommended: None,
24709            history_budget_pressure: None,
24710            next_history_page_token: None,
24711            workflow_task_attempt: 1,
24712            workflow_signal_id: None,
24713            signal_name: None,
24714            signal_arguments: None,
24715            workflow_update_id: None,
24716            update_name: None,
24717            lease_owner: Some("rust-worker".to_string()),
24718        };
24719
24720        let initial = worker
24721            .execute_workflow_task(task(Vec::new()))
24722            .expect("initial timer task");
24723        assert_eq!(
24724            initial,
24725            vec![json!({"type": "start_timer", "delay_seconds": 5})]
24726        );
24727
24728        let activity_result =
24729            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
24730        let replayed = worker
24731            .execute_workflow_task(task(vec![
24732                history_event(
24733                    "TimerScheduled",
24734                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24735                ),
24736                history_event(
24737                    "TimerFired",
24738                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24739                ),
24740                history_event(
24741                    "ActivityCompleted",
24742                    json!({
24743                        "sequence": 2,
24744                        "activity_type": "after-timer",
24745                        "payload_codec": DEFAULT_CODEC,
24746                        "result": activity_result,
24747                    }),
24748                ),
24749            ]))
24750            .expect("replayed workflow task");
24751        assert_eq!(replayed.len(), 1);
24752        assert_eq!(replayed[0]["type"], "complete_workflow");
24753        assert_eq!(
24754            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
24755            json!("done")
24756        );
24757    }
24758
24759    #[test]
24760    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
24761        let client = Client::new("http://127.0.0.1:8080").expect("client");
24762        let mut worker = Worker::new(client, "rust-workers");
24763        worker.register_workflow("rust.continue", |ctx, _input| async move {
24764            ctx.continue_as_new_with_options(
24765                ContinueAsNewOptions::new()
24766                    .workflow_type("rust.next")
24767                    .task_queue("next-workers"),
24768                json!([2, {"cursor": "next"}]),
24769            )
24770        });
24771
24772        let commands = worker
24773            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
24774            .expect("continue-as-new command");
24775
24776        assert_eq!(commands.len(), 1);
24777        assert_eq!(commands[0]["type"], "continue_as_new");
24778        assert_eq!(commands[0]["workflow_type"], "rust.next");
24779        assert_eq!(commands[0]["queue"], "next-workers");
24780        assert_eq!(
24781            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
24782                .expect("continue-as-new arguments"),
24783            json!([2, {"cursor": "next"}])
24784        );
24785    }
24786
24787    #[test]
24788    fn continue_as_new_preserves_typed_arguments() {
24789        let client = Client::new("http://127.0.0.1:8080").expect("client");
24790        let mut worker = Worker::new(client, "rust-workers");
24791        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
24792            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
24793            unreachable!("continue-as-new returns a control-flow error")
24794        });
24795
24796        let commands = worker
24797            .execute_workflow_task(workflow_task(
24798                "rust.typed-continue",
24799                Vec::new(),
24800                DEFAULT_CODEC,
24801            ))
24802            .expect("typed continue-as-new command");
24803
24804        assert_eq!(commands[0]["type"], "continue_as_new");
24805        assert_eq!(
24806            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
24807                .expect("typed continue arguments"),
24808            AvroValue::Array(vec![typed_fidelity_probe()])
24809        );
24810    }
24811
24812    #[test]
24813    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
24814        let client = Client::new("http://127.0.0.1:8080").expect("client");
24815        let mut worker = Worker::new(client, "rust-workers");
24816        worker.register_workflow("rust.continue", |ctx, _input| async move {
24817            ctx.continue_as_new(json!([2]))
24818        });
24819        let task = workflow_task(
24820            "rust.continue",
24821            vec![history_event(
24822                "WorkflowContinuedAsNew",
24823                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
24824            )],
24825            DEFAULT_CODEC,
24826        );
24827
24828        for _worker_restart_or_redelivery in 0..2 {
24829            let commands = worker
24830                .execute_workflow_task(task.clone())
24831                .expect("recorded transition replays");
24832            assert!(
24833                commands.is_empty(),
24834                "replay must not emit another successor"
24835            );
24836        }
24837    }
24838
24839    #[test]
24840    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
24841        let ctx = workflow_context(Vec::new());
24842        let error = ctx
24843            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
24844            .expect_err("blank queue must be rejected");
24845
24846        let Error::InvalidContinueAsNewOptions(error) = error else {
24847            panic!("expected typed continue-as-new validation error");
24848        };
24849        assert_eq!(error.field, "task_queue");
24850        assert!(ctx.take_commands().expect("commands").is_empty());
24851    }
24852
24853    #[test]
24854    fn workflow_context_exposes_server_history_budget() {
24855        let client = Client::new("http://127.0.0.1:8080").expect("client");
24856        let mut worker = Worker::new(client, "rust-workers");
24857        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
24858            let budget = ctx.history_budget()?;
24859            Ok(json!({
24860                "events": budget.event_count,
24861                "bytes": budget.size_bytes,
24862                "recommended": budget.continue_as_new_recommended,
24863                "pressure": budget.pressure,
24864            }))
24865        });
24866        let task: WorkflowTask = serde_json::from_value(json!({
24867            "task_id": "task-history-budget",
24868            "workflow_type": "rust.history-budget",
24869            "payload_codec": DEFAULT_CODEC,
24870            "history_events": [],
24871            "total_history_events": 480,
24872            "history_size_bytes": 1_048_576,
24873            "continue_as_new_recommended": true,
24874            "history_budget_pressure": "continue_as_new_recommended",
24875        }))
24876        .expect("published workflow task");
24877
24878        let commands = worker
24879            .execute_workflow_task(task)
24880            .expect("history-budget workflow");
24881        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
24882        assert_eq!(result["events"], 480);
24883        assert_eq!(result["bytes"], 1_048_576);
24884        assert_eq!(result["recommended"], true);
24885        assert_eq!(result["pressure"], "continue_as_new_recommended");
24886    }
24887
24888    #[test]
24889    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
24890        let client = Client::new("http://127.0.0.1:8080").expect("client");
24891        let mut worker = Worker::new(client, "rust-workers");
24892        worker.register_workflow("rust.failing", |_ctx, _input| async move {
24893            Err(Error::Codec("rust_conformance_failure".to_string()))
24894        });
24895        let task = WorkflowTask {
24896            task_id: "wft-rust-failing-1".to_string(),
24897            workflow_command_id: None,
24898            workflow_id: Some("wf-rust-failing".to_string()),
24899            run_id: Some("run-rust-failing".to_string()),
24900            workflow_type: "rust.failing".to_string(),
24901            cancel_requested: false,
24902            payload_codec: DEFAULT_CODEC.to_string(),
24903            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24904            history_events: Vec::new(),
24905            total_history_events: Some(0),
24906            history_size_bytes: None,
24907            continue_as_new_recommended: None,
24908            history_budget_pressure: None,
24909            next_history_page_token: None,
24910            workflow_task_attempt: 1,
24911            workflow_signal_id: None,
24912            signal_name: None,
24913            signal_arguments: None,
24914            workflow_update_id: None,
24915            update_name: None,
24916            lease_owner: Some("rust-worker".to_string()),
24917        };
24918
24919        let commands = worker
24920            .execute_workflow_task(task)
24921            .expect("handler failure becomes a workflow command");
24922
24923        assert_eq!(commands.len(), 1);
24924        assert_eq!(commands[0]["type"], "fail_workflow");
24925        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
24926        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
24927        assert_eq!(commands[0]["non_retryable"], false);
24928        assert_eq!(
24929            commands[0]["message"],
24930            "codec error: rust_conformance_failure"
24931        );
24932        assert_eq!(
24933            commands[0]["exception"]["message"],
24934            "codec error: rust_conformance_failure"
24935        );
24936    }
24937
24938    #[test]
24939    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
24940        let client = Client::new("http://127.0.0.1:8080").expect("client");
24941        let mut worker = Worker::new(client, "rust-workers");
24942        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
24943            let _: String = ctx.side_effect(|| "captured".to_string())?;
24944            Err(Error::WorkerLoop("application failure".to_string()))
24945        });
24946
24947        let commands = worker
24948            .execute_workflow_task(workflow_task(
24949                "rust.failing-after-side-effect",
24950                Vec::new(),
24951                DEFAULT_CODEC,
24952            ))
24953            .expect("ordinary failure remains a workflow decision");
24954
24955        assert_eq!(commands.len(), 2);
24956        assert_eq!(commands[0]["type"], "record_side_effect");
24957        assert_eq!(commands[1]["type"], "fail_workflow");
24958    }
24959
24960    #[test]
24961    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
24962        let client = Client::new("http://127.0.0.1:8080").expect("client");
24963        let mut worker = Worker::new(client, "rust-workers");
24964        worker.register_workflow("rust.redrive", |ctx, _input| async move {
24965            ctx.activity("greet", json!([])).await?;
24966            Ok(Value::Null)
24967        });
24968        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
24969            match ctx.activity("greet", json!([])).await {
24970                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
24971                result => result,
24972            }
24973        });
24974
24975        let failed = history_event(
24976            "ActivityFailed",
24977            json!({
24978                "sequence": 1,
24979                "activity_type": "greet",
24980                "activity_execution_id": "activity-1",
24981                "message": "failed"
24982            }),
24983        );
24984        let commands = worker
24985            .execute_workflow_task(workflow_task(
24986                "rust.redrive",
24987                vec![failed.clone()],
24988                DEFAULT_CODEC,
24989            ))
24990            .expect("recorded failure becomes a workflow command");
24991        assert_eq!(commands[0]["type"], "fail_workflow");
24992        assert_eq!(commands[0]["failed_step_sequence"], 1);
24993        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
24994
24995        let translated = worker
24996            .execute_workflow_task(workflow_task(
24997                "rust.redrive-translated",
24998                vec![failed],
24999                DEFAULT_CODEC,
25000            ))
25001            .expect("translated failure becomes a workflow command");
25002        assert_eq!(translated[0]["type"], "fail_workflow");
25003        assert!(translated[0].get("failed_step_sequence").is_none());
25004        assert!(translated[0].get("failed_activity_execution_id").is_none());
25005
25006        let without_identity = worker
25007            .execute_workflow_task(workflow_task(
25008                "rust.redrive",
25009                vec![history_event(
25010                    "ActivityFailed",
25011                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
25012                )],
25013                DEFAULT_CODEC,
25014            ))
25015            .expect("incomplete identity still fails the workflow");
25016        assert!(without_identity[0].get("failed_step_sequence").is_none());
25017
25018        let timed_out = worker
25019            .execute_workflow_task(workflow_task(
25020                "rust.redrive",
25021                vec![history_event(
25022                    "ActivityTimedOut",
25023                    json!({
25024                        "sequence": 1,
25025                        "activity_type": "greet",
25026                        "activity_execution_id": "activity-timeout",
25027                    }),
25028                )],
25029                DEFAULT_CODEC,
25030            ))
25031            .expect("timeout still fails the workflow");
25032        assert!(timed_out[0].get("failed_step_sequence").is_none());
25033    }
25034
25035    #[test]
25036    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
25037        let client = Client::new("http://127.0.0.1:8080").expect("client");
25038        let mut worker = Worker::new(client, "rust-workers");
25039        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
25040            let first = ctx.activity("first", json!([])).await?;
25041            let second = ctx.activity("second", json!([first.clone()])).await?;
25042            Ok(json!({"first": first, "second": second}))
25043        });
25044        let first = history_event(
25045            "ActivityCompleted",
25046            json!({
25047                "sequence": 1,
25048                "activity_type": "first",
25049                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
25050                "payload_codec": DEFAULT_CODEC,
25051                "reused_from_run_id": "failed-run",
25052                "reused_activity_execution_id": "original-first",
25053            }),
25054        );
25055
25056        let retry = worker
25057            .execute_workflow_task(workflow_task(
25058                "rust.redrive-successor",
25059                vec![first.clone()],
25060                DEFAULT_CODEC,
25061            ))
25062            .expect("reused result replays before failed step");
25063        assert_eq!(retry.len(), 1);
25064        assert_eq!(retry[0]["type"], "schedule_activity");
25065        assert_eq!(retry[0]["activity_type"], "second");
25066        assert_eq!(
25067            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
25068            json!(["recorded"]),
25069        );
25070
25071        let second = history_event(
25072            "ActivityCompleted",
25073            json!({
25074                "sequence": 2,
25075                "activity_type": "second",
25076                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
25077                "payload_codec": DEFAULT_CODEC,
25078            }),
25079        );
25080        let completed = worker
25081            .execute_workflow_task(workflow_task(
25082                "rust.redrive-successor",
25083                vec![first, second],
25084                DEFAULT_CODEC,
25085            ))
25086            .expect("retried step completes the successor");
25087        assert_eq!(completed.len(), 1);
25088        assert_eq!(completed[0]["type"], "complete_workflow");
25089        assert_eq!(
25090            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
25091            json!({"first": "recorded", "second": "retried"}),
25092        );
25093    }
25094
25095    #[test]
25096    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
25097        let client = Client::new("http://127.0.0.1:8080").expect("client");
25098        let mut worker = Worker::new(client, "rust-workers");
25099        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
25100            Err(Error::WorkerLoop("application failure".to_string()))
25101        });
25102        let result =
25103            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
25104
25105        let error = worker
25106            .execute_workflow_task(workflow_task(
25107                "rust.removed-side-effect",
25108                vec![history_event(
25109                    "SideEffectRecorded",
25110                    json!({"sequence": 1, "result": result}),
25111                )],
25112                DEFAULT_CODEC,
25113            ))
25114            .expect_err("removed committed history must not become fail_workflow");
25115
25116        let Error::NonDeterministicReplay(failure) = error else {
25117            panic!("expected typed replay failure");
25118        };
25119        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25120        assert_eq!(failure.sequence, Some(1));
25121        assert_eq!(failure.expected.as_deref(), Some("side effect"));
25122    }
25123
25124    #[test]
25125    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25126        let client = Client::new("http://127.0.0.1:8080").expect("client");
25127        let mut worker = Worker::new(client, "rust-workers");
25128        worker.register_workflow(
25129            "rust.side-effect-before-marker-error",
25130            |ctx, _input| async move {
25131                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25132                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25133                ctx.get_version("restart-safe", 2, 2)?;
25134                Ok(Value::Null)
25135            },
25136        );
25137
25138        let error = worker
25139            .execute_workflow_task(workflow_task(
25140                "rust.side-effect-before-marker-error",
25141                vec![history_event(
25142                    "VersionMarkerRecorded",
25143                    json!({
25144                        "sequence": 1,
25145                        "change_id": "restart-safe",
25146                        "version": 1,
25147                        "min_supported": 1,
25148                        "max_supported": 1,
25149                    }),
25150                )],
25151                DEFAULT_CODEC,
25152            ))
25153            .expect_err("replay error must return no queued workflow commands");
25154
25155        let Error::NonDeterministicReplay(failure) = error else {
25156            panic!("expected typed replay failure");
25157        };
25158        assert_eq!(failure.reason, "version_marker_incompatible_range");
25159        assert_eq!(failure.sequence, Some(1));
25160    }
25161
25162    #[test]
25163    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25164        let client = Client::new("http://127.0.0.1:8080").expect("client");
25165        let mut worker = Worker::new(client, "rust-workers");
25166        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25167            ctx.sleep(Duration::from_secs(5)).await?;
25168            Ok(json!({"status": "timer fired"}))
25169        });
25170
25171        let task = WorkflowTask {
25172            task_id: "wft-rust-timer-pending".to_string(),
25173            workflow_command_id: None,
25174            workflow_id: Some("wf-rust-timer".to_string()),
25175            run_id: Some("run-rust-timer".to_string()),
25176            workflow_type: "rust.timer.pending".to_string(),
25177            cancel_requested: false,
25178            payload_codec: DEFAULT_CODEC.to_string(),
25179            arguments: Some(
25180                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25181            ),
25182            history_events: vec![history_event(
25183                "TimerScheduled",
25184                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25185            )],
25186            total_history_events: Some(1),
25187            history_size_bytes: None,
25188            continue_as_new_recommended: None,
25189            history_budget_pressure: None,
25190            next_history_page_token: None,
25191            workflow_task_attempt: 1,
25192            workflow_signal_id: None,
25193            signal_name: None,
25194            signal_arguments: None,
25195            workflow_update_id: None,
25196            update_name: None,
25197            lease_owner: Some("rust-worker".to_string()),
25198        };
25199
25200        for _redelivery_or_restart in 0..2 {
25201            let commands = worker
25202                .execute_workflow_task(task.clone())
25203                .expect("recorded timer remains pending");
25204            assert!(
25205                commands.is_empty(),
25206                "recorded timer must not be rescheduled"
25207            );
25208        }
25209    }
25210
25211    #[test]
25212    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25213        let client = Client::new("http://127.0.0.1:8080").expect("client");
25214        let mut worker = Worker::new(client, "rust-workers");
25215        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25216            Ok(json!({"status": "completed"}))
25217        });
25218        let task = WorkflowTask {
25219            task_id: "wft-rust-timer-removed".to_string(),
25220            workflow_command_id: None,
25221            workflow_id: Some("wf-rust-timer".to_string()),
25222            run_id: Some("run-rust-timer".to_string()),
25223            workflow_type: "rust.timer.removed".to_string(),
25224            cancel_requested: false,
25225            payload_codec: DEFAULT_CODEC.to_string(),
25226            arguments: Some(
25227                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25228            ),
25229            history_events: vec![
25230                history_event(
25231                    "TimerScheduled",
25232                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25233                ),
25234                history_event(
25235                    "TimerFired",
25236                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25237                ),
25238            ],
25239            total_history_events: Some(2),
25240            history_size_bytes: None,
25241            continue_as_new_recommended: None,
25242            history_budget_pressure: None,
25243            next_history_page_token: None,
25244            workflow_task_attempt: 1,
25245            workflow_signal_id: None,
25246            signal_name: None,
25247            signal_arguments: None,
25248            workflow_update_id: None,
25249            update_name: None,
25250            lease_owner: Some("rust-worker".to_string()),
25251        };
25252
25253        let Error::NonDeterministicReplay(failure) = worker
25254            .execute_workflow_task(task)
25255            .expect_err("removed timer must fail replay")
25256        else {
25257            panic!("expected typed replay failure");
25258        };
25259        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25260        assert_eq!(failure.sequence, Some(1));
25261    }
25262
25263    #[test]
25264    fn workflow_context_emits_explicit_child_workflow_contract() {
25265        let ctx = WorkflowContext {
25266            cancellation_scope_id: "root".into(),
25267            state: Arc::new(Mutex::new(
25268                WorkflowState::new_with_identity(
25269                    Vec::new(),
25270                    Some("wf-parent".to_string()),
25271                    Some("run-parent".to_string()),
25272                    "parent-workers".to_string(),
25273                    DEFAULT_CODEC.to_string(),
25274                    None,
25275                )
25276                .expect("workflow state"),
25277            )),
25278        };
25279        let options = ChildWorkflowOptions::new("python-workers")
25280            .parent_close_policy(ParentClosePolicy::RequestCancel)
25281            .retry_policy(ChildWorkflowRetryPolicy {
25282                max_attempts: Some(3),
25283                backoff_seconds: vec![1, 5],
25284                non_retryable_error_types: vec!["ValidationError".to_string()],
25285            })
25286            .execution_timeout_seconds(600)
25287            .run_timeout_seconds(120);
25288        let mut call = Box::pin(ctx.start_child_workflow(
25289            "python.fulfil-order",
25290            options,
25291            json!([{"order_id": "order-42"}]),
25292        ));
25293        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25294
25295        assert!(matches!(
25296            call.as_mut().poll(&mut task_context),
25297            Poll::Pending
25298        ));
25299        let commands = ctx.take_commands().expect("commands");
25300        assert_eq!(commands.len(), 1);
25301        let command = &commands[0];
25302        assert_eq!(command["type"], "start_child_workflow");
25303        assert_eq!(command["workflow_type"], "python.fulfil-order");
25304        assert_eq!(command["queue"], "python-workers");
25305        assert_eq!(command["parent_close_policy"], "request_cancel");
25306        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25307        assert_eq!(command["execution_timeout_seconds"], 600);
25308        assert_eq!(command["run_timeout_seconds"], 120);
25309        assert_eq!(
25310            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25311            json!([{"order_id": "order-42"}])
25312        );
25313    }
25314
25315    fn child_parent_worker() -> Worker {
25316        let client = Client::new("http://127.0.0.1:8080").expect("client");
25317        let mut worker = Worker::new(client, "rust-parent-workers");
25318        worker.register_workflow("rust.parent", |ctx, _input| async move {
25319            let child = ctx
25320                .start_child_workflow(
25321                    "python.child",
25322                    ChildWorkflowOptions::new("python-child-workers")
25323                        .parent_close_policy(ParentClosePolicy::Terminate),
25324                    json!([{"codec_probe": [1, true, "rust"]}]),
25325                )
25326                .await?;
25327            Ok(json!({
25328                "parent_workflow_id": child.parent.workflow_id,
25329                "parent_run_id": child.parent.run_id,
25330                "child_workflow_id": child.child.workflow_id,
25331                "child_run_id": child.child.run_id,
25332                "child_workflow_type": child.child_workflow_type,
25333                "result": child.result,
25334            }))
25335        });
25336        worker
25337    }
25338
25339    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
25340        WorkflowTask {
25341            task_id: "wft-child-parent".to_string(),
25342            workflow_command_id: None,
25343            workflow_id: Some("wf-parent".to_string()),
25344            run_id: Some("run-parent".to_string()),
25345            workflow_type: "rust.parent".to_string(),
25346            cancel_requested: false,
25347            payload_codec: DEFAULT_CODEC.to_string(),
25348            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25349            history_events: vec![
25350                HistoryEvent {
25351                    event_type: "ChildWorkflowScheduled".to_string(),
25352                    payload: json!({
25353                        "sequence": 1,
25354                        "child_call_id": "call-child",
25355                        "child_workflow_instance_id": "wf-child",
25356                        "child_workflow_run_id": "run-child",
25357                        "child_workflow_type": "python.child",
25358                        "parent_close_policy": "terminate",
25359                    }),
25360                    raw: HashMap::new(),
25361                },
25362                HistoryEvent {
25363                    event_type: event_type.to_string(),
25364                    payload,
25365                    raw: HashMap::new(),
25366                },
25367            ],
25368            total_history_events: Some(2),
25369            history_size_bytes: None,
25370            continue_as_new_recommended: None,
25371            history_budget_pressure: None,
25372            next_history_page_token: None,
25373            workflow_task_attempt: 1,
25374            workflow_signal_id: None,
25375            signal_name: None,
25376            signal_arguments: None,
25377            workflow_update_id: None,
25378            update_name: None,
25379            lease_owner: Some("rust-worker".to_string()),
25380        }
25381    }
25382
25383    #[test]
25384    fn committed_child_result_replays_without_starting_a_duplicate() {
25385        let worker = child_parent_worker();
25386        let task = child_parent_task(
25387            "ChildRunCompleted",
25388            json!({
25389                "sequence": 1,
25390                "child_call_id": "call-child",
25391                "child_workflow_instance_id": "wf-child",
25392                "child_workflow_run_id": "run-child",
25393                "child_workflow_type": "python.child",
25394                "payload_codec": DEFAULT_CODEC,
25395                "result": fixture_envelope(json!({"from":"python","ok":true})),
25396            }),
25397        );
25398
25399        for _restart in 0..2 {
25400            let commands = worker
25401                .execute_workflow_task(task.clone())
25402                .expect("replayed parent task");
25403            assert_eq!(commands.len(), 1);
25404            assert_eq!(commands[0]["type"], "complete_workflow");
25405            assert!(!commands
25406                .iter()
25407                .any(|command| command["type"] == "start_child_workflow"));
25408            let output =
25409                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25410            assert_eq!(output["parent_workflow_id"], "wf-parent");
25411            assert_eq!(output["parent_run_id"], "run-parent");
25412            assert_eq!(output["child_workflow_id"], "wf-child");
25413            assert_eq!(output["child_run_id"], "run-child");
25414            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
25415        }
25416    }
25417
25418    #[test]
25419    fn typed_child_arguments_and_results_survive_replay() {
25420        let client = Client::new("http://127.0.0.1:8080").expect("client");
25421        let mut worker = Worker::new(client, "rust-parent-workers");
25422        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
25423            let child = ctx
25424                .start_child_workflow_avro_value(
25425                    "python.typed-child",
25426                    ChildWorkflowOptions::new("python-workers"),
25427                    AvroValue::Array(vec![typed_fidelity_probe()]),
25428                )
25429                .await?;
25430            Ok(child.result)
25431        });
25432
25433        let initial = worker
25434            .execute_workflow_task(workflow_task(
25435                "rust.typed-parent",
25436                Vec::new(),
25437                DEFAULT_CODEC,
25438            ))
25439            .expect("typed child start");
25440        assert_eq!(initial[0]["type"], "start_child_workflow");
25441        assert_eq!(
25442            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
25443                .expect("typed child arguments"),
25444            AvroValue::Array(vec![typed_fidelity_probe()])
25445        );
25446
25447        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
25448            .expect("typed child result");
25449        let task = workflow_task(
25450            "rust.typed-parent",
25451            vec![
25452                history_event(
25453                    "ChildWorkflowScheduled",
25454                    json!({
25455                        "sequence": 1,
25456                        "child_call_id": "call-typed",
25457                        "child_workflow_instance_id": "wf-child",
25458                        "child_workflow_run_id": "run-child",
25459                        "child_workflow_type": "python.typed-child",
25460                    }),
25461                ),
25462                history_event(
25463                    "ChildRunCompleted",
25464                    json!({
25465                        "sequence": 1,
25466                        "child_call_id": "call-typed",
25467                        "child_workflow_instance_id": "wf-child",
25468                        "child_workflow_run_id": "run-child",
25469                        "child_workflow_type": "python.typed-child",
25470                        "payload_codec": DEFAULT_CODEC,
25471                        "result": result,
25472                    }),
25473                ),
25474            ],
25475            DEFAULT_CODEC,
25476        );
25477
25478        let commands = worker
25479            .execute_workflow_task(task)
25480            .expect("typed child replay");
25481        assert_eq!(commands[0]["type"], "complete_workflow");
25482        assert_eq!(
25483            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
25484                .expect("typed parent result"),
25485            typed_fidelity_probe()
25486        );
25487    }
25488
25489    #[test]
25490    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
25491        let worker = child_parent_worker();
25492        let mut task = child_parent_task("unused", Value::Null);
25493        task.history_events.truncate(1);
25494        task.total_history_events = Some(1);
25495
25496        for _redelivery_or_restart in 0..2 {
25497            let commands = worker
25498                .execute_workflow_task(task.clone())
25499                .expect("recorded child remains pending");
25500            assert!(
25501                commands.is_empty(),
25502                "recorded pending child must not be started again"
25503            );
25504        }
25505    }
25506
25507    #[test]
25508    fn child_cancellation_becomes_stable_parent_failure_command() {
25509        let worker = child_parent_worker();
25510        let task = child_parent_task(
25511            "ChildRunCancelled",
25512            json!({
25513                "sequence": 1,
25514                "child_workflow_instance_id": "wf-child",
25515                "child_workflow_run_id": "run-child",
25516                "child_workflow_type": "python.child",
25517                "failure_id": "failure-child",
25518                "failure_category": "cancelled",
25519                "message": "cancelled by parent-close policy",
25520            }),
25521        );
25522
25523        let commands = worker
25524            .execute_workflow_task(task)
25525            .expect("parent settlement");
25526        assert_eq!(commands.len(), 1);
25527        assert_eq!(commands[0]["type"], "fail_workflow");
25528        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25529        assert_eq!(
25530            commands[0]["exception"]["properties"]["reason"],
25531            "cancelled"
25532        );
25533        assert_eq!(
25534            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25535            "run-child"
25536        );
25537    }
25538
25539    #[test]
25540    fn workflow_can_handle_typed_child_failure() {
25541        let client = Client::new("http://127.0.0.1:8080").expect("client");
25542        let mut worker = Worker::new(client, "rust-parent-workers");
25543        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25544            match ctx
25545                .start_child_workflow(
25546                    "python.child",
25547                    ChildWorkflowOptions::new("python-child-workers"),
25548                    json!([]),
25549                )
25550                .await
25551            {
25552                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25553                    "reason": failure.reason,
25554                    "failure_id": failure.failure_id,
25555                    "exception_class": failure.exception_class,
25556                    "child_run_id": failure.child_workflow_run_id,
25557                })),
25558                Err(error) => Err(error),
25559                Ok(_) => Err(Error::WorkerLoop(
25560                    "child unexpectedly succeeded".to_string(),
25561                )),
25562            }
25563        });
25564        let mut task = child_parent_task(
25565            "ChildRunFailed",
25566            json!({
25567                "sequence": 1,
25568                "child_workflow_instance_id": "wf-child",
25569                "child_workflow_run_id": "run-child",
25570                "child_workflow_type": "python.child",
25571                "failure_id": "failure-child",
25572                "failure_category": "child_workflow",
25573                "message": "payment rejected",
25574                "exception": {
25575                    "type": "PaymentRejected",
25576                    "class": "payments.PaymentRejected",
25577                    "message": "payment rejected"
25578                }
25579            }),
25580        );
25581        task.workflow_type = "rust.handled-parent".to_string();
25582        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25583
25584        let commands = worker.execute_workflow_task(task).expect("handled failure");
25585        assert_eq!(commands[0]["type"], "complete_workflow");
25586        let output =
25587            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25588        assert_eq!(output["reason"], "child_workflow");
25589        assert_eq!(output["failure_id"], "failure-child");
25590        assert_eq!(output["exception_class"], "payments.PaymentRejected");
25591        assert_eq!(output["child_run_id"], "run-child");
25592    }
25593
25594    #[test]
25595    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
25596        let client = Client::new("http://127.0.0.1:8080").expect("client");
25597        let mut worker = Worker::new(client, "rust-workers");
25598
25599        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
25600            let signal = ctx.wait_signal("start").await?;
25601            let name = signal
25602                .first()
25603                .and_then(|value| value.as_str())
25604                .unwrap_or("world");
25605            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
25606            Ok(json!({
25607                "greeting": greeting,
25608                "language": "rust"
25609            }))
25610        });
25611
25612        let signal_arguments =
25613            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
25614        let task = WorkflowTask {
25615            task_id: "wft-rust-signal-1".to_string(),
25616            workflow_command_id: None,
25617            workflow_id: Some("wf-rust-hello".to_string()),
25618            run_id: Some("run-rust-hello".to_string()),
25619            workflow_type: "rust.hello_workflow".to_string(),
25620            cancel_requested: false,
25621            payload_codec: DEFAULT_CODEC.to_string(),
25622            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25623            history_events: vec![HistoryEvent {
25624                event_type: "SignalReceived".to_string(),
25625                payload: json!({
25626                    "signal_id": "sig-rust-1",
25627                    "signal_name": "start"
25628                }),
25629                raw: HashMap::new(),
25630            }],
25631            total_history_events: Some(1),
25632            history_size_bytes: None,
25633            continue_as_new_recommended: None,
25634            history_budget_pressure: None,
25635            next_history_page_token: None,
25636            workflow_task_attempt: 1,
25637            workflow_signal_id: Some("sig-rust-1".to_string()),
25638            signal_name: Some("start".to_string()),
25639            signal_arguments: Some(signal_arguments),
25640            workflow_update_id: None,
25641            update_name: None,
25642            lease_owner: Some("rust-worker".to_string()),
25643        };
25644
25645        let commands = worker.execute_workflow_task(task).expect("workflow task");
25646
25647        assert_eq!(commands.len(), 1);
25648        assert_eq!(commands[0]["type"], "schedule_activity");
25649        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
25650        assert_eq!(
25651            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
25652            json!(["Rust"])
25653        );
25654    }
25655
25656    #[test]
25657    fn workflow_task_appends_paginated_history_events() {
25658        let mut task = WorkflowTask {
25659            task_id: "wft-rust-pages-1".to_string(),
25660            workflow_command_id: None,
25661            workflow_id: Some("wf-rust-pages".to_string()),
25662            run_id: Some("run-rust-pages".to_string()),
25663            workflow_type: "rust.hello_workflow".to_string(),
25664            cancel_requested: false,
25665            payload_codec: DEFAULT_CODEC.to_string(),
25666            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25667            history_events: vec![HistoryEvent {
25668                event_type: "WorkflowStarted".to_string(),
25669                payload: json!({}),
25670                raw: HashMap::new(),
25671            }],
25672            total_history_events: Some(3),
25673            history_size_bytes: None,
25674            continue_as_new_recommended: None,
25675            history_budget_pressure: None,
25676            next_history_page_token: Some("MQ==".to_string()),
25677            workflow_task_attempt: 1,
25678            workflow_signal_id: None,
25679            signal_name: None,
25680            signal_arguments: None,
25681            workflow_update_id: None,
25682            update_name: None,
25683            lease_owner: Some("rust-worker".to_string()),
25684        };
25685
25686        task.append_history_page(WorkflowTaskHistoryPage {
25687            history_events: vec![
25688                HistoryEvent {
25689                    event_type: "SignalReceived".to_string(),
25690                    payload: json!({
25691                        "signal_id": "sig-rust-1",
25692                        "signal_name": "start",
25693                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
25694                            .expect("signal arguments")
25695                    }),
25696                    raw: HashMap::new(),
25697                },
25698                HistoryEvent {
25699                    event_type: "MarkerRecorded".to_string(),
25700                    payload: json!({"sequence": 3}),
25701                    raw: HashMap::new(),
25702                },
25703            ],
25704            total_history_events: Some(3),
25705            next_history_page_token: None,
25706        });
25707
25708        assert_eq!(task.history_events.len(), 3);
25709        assert_eq!(task.total_history_events, Some(3));
25710        assert_eq!(task.next_history_page_token, None);
25711
25712        let signal = task
25713            .history_events
25714            .iter()
25715            .find(|event| event.event_type == "SignalReceived")
25716            .expect("signal event");
25717        assert_eq!(
25718            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
25719            vec![AvroValue::String("Rust".to_string())]
25720        );
25721    }
25722
25723    #[tokio::test]
25724    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
25725        let client = Client::new("http://127.0.0.1:8080").expect("client");
25726        let mut worker = Worker::new(client, "rust-workers");
25727        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25728        worker.register_query("counter", "current", |ctx, _args| async move {
25729            let mut count = 0_i64;
25730            for signal in ctx.signal_events() {
25731                let value = signal
25732                    .arguments
25733                    .first()
25734                    .and_then(Value::as_i64)
25735                    .unwrap_or_default();
25736                match signal.name.as_str() {
25737                    "increment" => count += value,
25738                    "set" => count = value,
25739                    _ => {}
25740                }
25741            }
25742            Ok(json!(count))
25743        });
25744
25745        let task = QueryTask {
25746            query_task_id: "query-rust-counter".to_string(),
25747            query_task_attempt: 1,
25748            lease_owner: Some("rust-worker".to_string()),
25749            workflow_id: Some("counter-1".to_string()),
25750            run_id: Some("run-counter-1".to_string()),
25751            workflow_type: "counter".to_string(),
25752            query_name: "current".to_string(),
25753            payload_codec: DEFAULT_CODEC.to_string(),
25754            workflow_arguments: Some(
25755                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25756            ),
25757            query_arguments: Some(
25758                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
25759            ),
25760            history_events: vec![
25761                HistoryEvent {
25762                    event_type: "SignalReceived".to_string(),
25763                    payload: json!({
25764                        "signal_id": "php-signal-1",
25765                        "signal_name": "increment",
25766                        "workflow_sequence": 1,
25767                        "payload_codec": DEFAULT_CODEC,
25768                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
25769                    }),
25770                    raw: HashMap::new(),
25771                },
25772                HistoryEvent {
25773                    event_type: "SignalReceived".to_string(),
25774                    payload: json!({
25775                        "signal_id": "python-signal-2",
25776                        "signal_name": "increment",
25777                        "workflow_sequence": 2,
25778                        "payload_codec": DEFAULT_CODEC,
25779                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
25780                    }),
25781                    raw: HashMap::new(),
25782                },
25783                HistoryEvent {
25784                    event_type: "SignalReceived".to_string(),
25785                    payload: json!({
25786                        "signal_id": "rust-signal-3",
25787                        "signal_name": "set",
25788                        "workflow_sequence": 3,
25789                        "payload_codec": DEFAULT_CODEC,
25790                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
25791                    }),
25792                    raw: HashMap::new(),
25793                },
25794            ],
25795            history_export: None,
25796            run_status: Some("completed".to_string()),
25797        };
25798
25799        let result = worker.execute_query_task(task).await.expect("query result");
25800        assert_eq!(result.into_json().expect("query projection"), json!(0));
25801    }
25802
25803    #[tokio::test]
25804    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
25805        let worker = replay_counter_worker();
25806        let running_history = json!([
25807            {
25808                "type": "ActivityCompleted",
25809                "payload": {
25810                    "sequence": 1,
25811                    "activity_type": "load-counter",
25812                    "payload_codec": DEFAULT_CODEC,
25813                    "result": fixture_envelope(json!("loaded"))
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                    "payload_codec": DEFAULT_CODEC,
25830                    "arguments": fixture_envelope(json!([3]))
25831                }
25832            },
25833            {
25834                "type": "SignalApplied",
25835                "payload": {
25836                    "sequence": 3,
25837                    "signal_id": "signal-3",
25838                    "signal_name": "increment",
25839                    "payload_codec": DEFAULT_CODEC,
25840                    "value": fixture_envelope(json!([3]))
25841                }
25842            }
25843        ]);
25844
25845        let running = worker
25846            .execute_query_task(replay_counter_query(
25847                "current",
25848                running_history.clone(),
25849                "running",
25850            ))
25851            .await
25852            .expect("running replay query");
25853        assert_eq!(
25854            running.clone().into_json().expect("query projection"),
25855            json!({"loaded": "loaded", "count": 3, "finished": false})
25856        );
25857
25858        let detached = worker
25859            .execute_query_task(replay_counter_query(
25860                "detached-mutation",
25861                running_history.clone(),
25862                "running",
25863            ))
25864            .await
25865            .expect("query mutates only its detached state clone");
25866        assert_eq!(detached.into_json().expect("query projection"), json!(999));
25867        let failed = worker
25868            .execute_query_task(replay_counter_query(
25869                "failed-mutation",
25870                running_history.clone(),
25871                "running",
25872            ))
25873            .await
25874            .expect_err("failed query");
25875        assert_eq!(failed.reason, "query_rejected");
25876        let unchanged = worker
25877            .execute_query_task(replay_counter_query("current", running_history, "running"))
25878            .await
25879            .expect("later query reconstructs unchanged state");
25880        assert_eq!(unchanged, running);
25881
25882        let restarted_worker = replay_counter_worker();
25883        let empty_arguments = fixture_envelope(json!([]));
25884        let loaded_result = fixture_envelope(json!("loaded"));
25885        let signal_three = fixture_blob(json!([3]));
25886        let signal_five = fixture_blob(json!([5]));
25887        let restarted_task: QueryTask = serde_json::from_value(json!({
25888            "query_task_id": "query-after-restart",
25889            "workflow_id": "counter-1",
25890            "run_id": "run-counter-1",
25891            "workflow_type": "replay-counter",
25892            "query_name": "current",
25893            "payload_codec": DEFAULT_CODEC,
25894            "workflow_arguments": empty_arguments.clone(),
25895            "query_arguments": empty_arguments,
25896            "history_events": [],
25897            "history_export": {
25898                "payloads": {"codec": DEFAULT_CODEC},
25899                "history_events": [
25900                    {
25901                        "type": "ActivityCompleted",
25902                        "payload": {
25903                            "sequence": 1,
25904                            "activity_type": "load-counter",
25905                            "payload_codec": DEFAULT_CODEC,
25906                            "result": null
25907                        }
25908                    },
25909                    {
25910                        "type": "SignalWaitOpened",
25911                        "payload": {
25912                            "sequence": 3,
25913                            "signal_name": "increment"
25914                        }
25915                    },
25916                    {
25917                        "type": "SignalReceived",
25918                        "payload": {
25919                            "signal_id": "signal-3",
25920                            "signal_name": "increment",
25921                            "workflow_sequence": 2
25922                        }
25923                    },
25924                    {
25925                        "type": "SignalApplied",
25926                        "payload": {
25927                            "sequence": 3,
25928                            "signal_id": "signal-3",
25929                            "signal_name": "increment"
25930                        }
25931                    },
25932                    {
25933                        "type": "SignalWaitOpened",
25934                        "payload": {
25935                            "sequence": 5,
25936                            "signal_name": "increment"
25937                        }
25938                    },
25939                    {
25940                        "type": "SignalReceived",
25941                        "payload": {
25942                            "signal_id": "signal-5",
25943                            "signal_name": "increment",
25944                            "workflow_sequence": 4
25945                        }
25946                    },
25947                    {
25948                        "type": "SignalApplied",
25949                        "payload": {
25950                            "sequence": 5,
25951                            "signal_id": "signal-5",
25952                            "signal_name": "increment"
25953                        }
25954                    }
25955                ],
25956                "activities": [{
25957                    "sequence": 1,
25958                    "activity_type": "load-counter",
25959                    "payload_codec": DEFAULT_CODEC,
25960                    "result": loaded_result
25961                }],
25962                "signals": [
25963                    {
25964                        "id": "signal-3",
25965                        "name": "increment",
25966                        "workflow_sequence": 2,
25967                        "payload_codec": DEFAULT_CODEC,
25968                        "arguments": signal_three
25969                    },
25970                    {
25971                        "id": "signal-5",
25972                        "name": "increment",
25973                        "workflow_sequence": 4,
25974                        "payload_codec": DEFAULT_CODEC,
25975                        "arguments": signal_five
25976                    }
25977                ]
25978            },
25979            "run_status": "completed"
25980        }))
25981        .expect("cold replay query task");
25982        let completed = restarted_worker
25983            .execute_query_task(restarted_task)
25984            .await
25985            .expect("completed cold replay query");
25986        assert_eq!(
25987            completed.into_json().expect("query projection"),
25988            json!({"loaded": "loaded", "count": 8, "finished": true})
25989        );
25990    }
25991
25992    #[tokio::test]
25993    async fn replayed_query_replay_failures_are_machine_readable() {
25994        let worker = replay_counter_worker();
25995        let task = replay_counter_query(
25996            "current",
25997            json!([{
25998                "type": "ActivityCompleted",
25999                "payload": {
26000                    "sequence": 1,
26001                    "payload_codec": DEFAULT_CODEC,
26002                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
26003                }
26004            }]),
26005            "running",
26006        );
26007        let failure = worker
26008            .execute_query_task(task)
26009            .await
26010            .expect_err("invalid replay history payload");
26011        assert_eq!(failure.reason, "query_payload_decode_failed");
26012        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
26013        assert!(failure.message.contains("invalid_payload_framing"));
26014    }
26015
26016    #[tokio::test]
26017    async fn query_task_restores_compact_history_from_export() {
26018        let client = Client::new("http://127.0.0.1:8080").expect("client");
26019        let mut worker = Worker::new(client, "rust-workers");
26020        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26021        worker.register_query("counter", "current", |ctx, _args| async move {
26022            Ok(json!(ctx.signals("increment")[0][0]))
26023        });
26024        let empty_arguments = fixture_envelope(json!([]));
26025        let exported_signal = fixture_blob(json!([9]));
26026        let task: QueryTask = serde_json::from_value(json!({
26027            "query_task_id": "query-export",
26028            "workflow_type": "counter",
26029            "query_name": "current",
26030            "payload_codec": DEFAULT_CODEC,
26031            "workflow_arguments": empty_arguments.clone(),
26032            "query_arguments": empty_arguments,
26033            "history_events": [],
26034            "history_export": {
26035                "payloads": {"codec": DEFAULT_CODEC},
26036                "history_events": [{
26037                    "type": "SignalReceived",
26038                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
26039                }],
26040                "signals": [{
26041                    "id": "signal-export",
26042                    "name": "increment",
26043                    "status": "applied",
26044                    "workflow_sequence": 1,
26045                    "payload_codec": DEFAULT_CODEC,
26046                    "arguments": exported_signal
26047                }]
26048            }
26049        }))
26050        .expect("query task");
26051
26052        let result = worker.execute_query_task(task).await.expect("query result");
26053        assert_eq!(result.into_json().expect("query projection"), json!(9));
26054    }
26055
26056    #[tokio::test]
26057    async fn query_task_failures_have_stable_reasons() {
26058        let client = Client::new("http://127.0.0.1:8080").expect("client");
26059        let mut worker = Worker::new(client, "rust-workers");
26060        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26061        worker.register_query(
26062            "counter",
26063            "current",
26064            |_ctx, _args| async move { Ok(json!(0)) },
26065        );
26066
26067        let base_task = QueryTask {
26068            query_task_id: "query-errors".to_string(),
26069            query_task_attempt: 1,
26070            lease_owner: None,
26071            workflow_id: Some("counter-errors".to_string()),
26072            run_id: Some("run-errors".to_string()),
26073            workflow_type: "counter".to_string(),
26074            query_name: "missing".to_string(),
26075            payload_codec: DEFAULT_CODEC.to_string(),
26076            workflow_arguments: Some(fixture_envelope(json!([]))),
26077            query_arguments: Some(fixture_envelope(json!([]))),
26078            history_events: Vec::new(),
26079            history_export: None,
26080            run_status: Some("running".to_string()),
26081        };
26082
26083        let unknown = worker
26084            .execute_query_task(base_task.clone())
26085            .await
26086            .expect_err("unknown query");
26087        assert_eq!(unknown.reason, "rejected_unknown_query");
26088
26089        let mut malformed = base_task;
26090        malformed.query_name = "current".to_string();
26091        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
26092        let malformed = worker
26093            .execute_query_task(malformed)
26094            .await
26095            .expect_err("malformed payload");
26096        assert_eq!(malformed.reason, "query_payload_decode_failed");
26097
26098        let client = Client::new("http://127.0.0.1:8080").expect("client");
26099        let mut unavailable_worker = Worker::new(client, "rust-workers");
26100        unavailable_worker
26101            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26102        let empty_arguments = fixture_envelope(json!([]));
26103        let unavailable_task: QueryTask = serde_json::from_value(json!({
26104            "query_task_id": "query-unavailable",
26105            "workflow_type": "counter",
26106            "query_name": "current",
26107            "payload_codec": DEFAULT_CODEC,
26108            "workflow_arguments": empty_arguments.clone(),
26109            "query_arguments": empty_arguments
26110        }))
26111        .expect("query task");
26112        let unavailable = unavailable_worker
26113            .execute_query_task(unavailable_task)
26114            .await
26115            .expect_err("query handler unavailable");
26116        assert_eq!(unavailable.reason, "query_handler_unavailable");
26117    }
26118
26119    #[tokio::test]
26120    async fn client_query_decodes_result_and_typed_failure() {
26121        let server = MockWorkerServer::start();
26122        let client = Client::builder(server.base_url())
26123            .timeout(Duration::from_secs(2))
26124            .build()
26125            .expect("client");
26126
26127        let result = client
26128            .query_workflow("counter-1", "current", json!([]))
26129            .await
26130            .expect("query result");
26131        assert_eq!(result, json!({"count": 8}));
26132
26133        let error = client
26134            .query_workflow("counter-1", "missing", json!([]))
26135            .await
26136            .expect_err("unknown query");
26137        let Error::QueryFailed(failure) = error else {
26138            panic!("expected typed query failure");
26139        };
26140        assert_eq!(failure.status, 404);
26141        assert_eq!(failure.reason, "rejected_unknown_query");
26142    }
26143
26144    #[tokio::test]
26145    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26146        let server = MockWorkerServer::start();
26147        let client = Client::builder(server.base_url())
26148            .timeout(Duration::from_secs(2))
26149            .build()
26150            .expect("client");
26151        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26152
26153        client
26154            .start_workflow(
26155                "typed.echo",
26156                "rust-workers",
26157                "typed-start",
26158                arguments.clone(),
26159            )
26160            .await
26161            .expect("typed workflow start");
26162        assert_eq!(
26163            decode_wire_avro_value(
26164                &server.request_body("/api/workflows")["input"],
26165                DEFAULT_CODEC,
26166            )
26167            .expect("typed start input"),
26168            arguments
26169        );
26170
26171        client
26172            .signal_workflow("typed-1", "changed", arguments.clone())
26173            .await
26174            .expect("typed signal");
26175        assert_eq!(
26176            decode_wire_avro_value(
26177                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26178                DEFAULT_CODEC,
26179            )
26180            .expect("typed signal input"),
26181            arguments
26182        );
26183
26184        assert_eq!(
26185            client
26186                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26187                .await
26188                .expect("typed query"),
26189            typed_fidelity_probe()
26190        );
26191        assert_eq!(
26192            decode_wire_avro_value(
26193                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26194                DEFAULT_CODEC,
26195            )
26196            .expect("typed query input"),
26197            arguments
26198        );
26199
26200        assert_eq!(
26201            client
26202                .update_workflow_avro_value(
26203                    "typed-1",
26204                    "replace",
26205                    arguments.clone(),
26206                    Some("typed-request"),
26207                )
26208                .await
26209                .expect("typed update"),
26210            typed_fidelity_probe()
26211        );
26212        let update = server.request_body("/api/workflows/typed-1/update/replace");
26213        assert_eq!(update["request_id"], "typed-request");
26214        assert_eq!(
26215            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26216            arguments
26217        );
26218
26219        let handle = WorkflowHandle {
26220            client: client.clone(),
26221            workflow_id: "typed-1".to_string(),
26222            run_id: Some("run-typed-1".to_string()),
26223            workflow_type: "typed.echo".to_string(),
26224        };
26225        assert_eq!(
26226            handle
26227                .result_avro_value(WorkflowResultOptions::default())
26228                .await
26229                .expect("typed workflow result"),
26230            typed_fidelity_probe()
26231        );
26232
26233        client
26234            .complete_activity_task(
26235                "activity-typed",
26236                "attempt-typed",
26237                "rust-worker",
26238                typed_fidelity_probe(),
26239                DEFAULT_CODEC,
26240            )
26241            .await
26242            .expect("typed activity completion");
26243        assert_eq!(
26244            decode_wire_avro_value(
26245                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26246                    ["result"],
26247                DEFAULT_CODEC,
26248            )
26249            .expect("typed activity result"),
26250            typed_fidelity_probe()
26251        );
26252        client
26253            .fail_activity_task(
26254                "activity-typed",
26255                "attempt-typed",
26256                "rust-worker",
26257                "typed failure",
26258                true,
26259            )
26260            .await
26261            .expect("activity failure");
26262    }
26263
26264    #[tokio::test]
26265    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26266        let server = MockWorkerServer::start();
26267        let client = Client::builder(server.base_url())
26268            .timeout(Duration::from_secs(2))
26269            .build()
26270            .expect("client");
26271
26272        let options = WorkflowCommandOptions::new()
26273            .reason("cleanup requested")
26274            .request_id("cancel-17");
26275        let cancelled = client
26276            .cancel_workflow("wf-lifecycle", options)
26277            .await
26278            .expect("instance cancellation");
26279        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26280        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26281        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26282        assert_eq!(
26283            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26284            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26285        );
26286
26287        let terminated = client
26288            .terminate_workflow(
26289                "wf-lifecycle",
26290                WorkflowCommandOptions::new().reason("forced stop"),
26291            )
26292            .await
26293            .expect("instance termination");
26294        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26295        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26296
26297        client
26298            .cancel_workflow_run(
26299                "wf-lifecycle",
26300                "run-current",
26301                WorkflowCommandOptions::default(),
26302            )
26303            .await
26304            .expect("selected run cancellation");
26305        client
26306            .terminate_workflow_run(
26307                "wf-lifecycle",
26308                "run-current",
26309                WorkflowCommandOptions::default(),
26310            )
26311            .await
26312            .expect("selected run termination");
26313
26314        for (command, error) in [
26315            (
26316                WorkflowCommandKind::Cancel,
26317                client
26318                    .cancel_workflow_run(
26319                        "wf-lifecycle",
26320                        "run-stale",
26321                        WorkflowCommandOptions::default(),
26322                    )
26323                    .await
26324                    .expect_err("stale cancellation must be rejected"),
26325            ),
26326            (
26327                WorkflowCommandKind::Terminate,
26328                client
26329                    .terminate_workflow_run(
26330                        "wf-lifecycle",
26331                        "run-stale",
26332                        WorkflowCommandOptions::default(),
26333                    )
26334                    .await
26335                    .expect_err("stale termination must be rejected"),
26336            ),
26337        ] {
26338            let Error::WorkflowCommandRejected(rejection) = error else {
26339                panic!("expected typed command rejection");
26340            };
26341            assert_eq!(rejection.command, command);
26342            assert_eq!(rejection.status, 409);
26343            assert_eq!(rejection.reason, "historical_run_command_rejected");
26344            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
26345            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
26346        }
26347    }
26348
26349    #[tokio::test]
26350    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
26351        let server = MockWorkerServer::start();
26352        let client = Client::builder(server.base_url())
26353            .timeout(Duration::from_secs(2))
26354            .build()
26355            .expect("client");
26356
26357        let result = client
26358            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
26359            .await
26360            .expect("redrive accepted");
26361        assert_eq!(result.workflow_id, "wf-lifecycle");
26362        assert_eq!(result.source_run_id, "run-failed");
26363        assert_eq!(result.run_id, "run-successor");
26364        assert_eq!(result.resume_step_sequence, 2);
26365        assert_eq!(
26366            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
26367            json!({"request_id":"retry-1"})
26368        );
26369
26370        let repeated = client
26371            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
26372            .await
26373            .expect("idempotent redrive response accepted");
26374        assert_eq!(repeated.run_id, "run-successor");
26375
26376        let error = client
26377            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
26378            .await
26379            .expect_err("completed run must be rejected");
26380        let Error::Http { status, body } = error else {
26381            panic!("expected HTTP redrive rejection");
26382        };
26383        assert_eq!(status.as_u16(), 409);
26384        assert!(body.contains("run_not_failed"));
26385        assert_eq!(
26386            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
26387            json!({})
26388        );
26389
26390        let handle = WorkflowHandle {
26391            client: client.clone(),
26392            workflow_id: "wf-lifecycle".to_string(),
26393            run_id: Some("run-failed".to_string()),
26394            workflow_type: "test".to_string(),
26395        };
26396        assert_eq!(
26397            handle.redrive(None).await.expect("handle redrive").run_id,
26398            "run-successor"
26399        );
26400        let missing_run = WorkflowHandle {
26401            run_id: None,
26402            ..handle
26403        };
26404        assert!(matches!(
26405            missing_run.redrive(None).await,
26406            Err(Error::Codec(_))
26407        ));
26408    }
26409
26410    #[tokio::test]
26411    async fn workflow_start_options_send_server_enforced_deadlines() {
26412        let server = MockWorkerServer::start();
26413        let client = Client::builder(server.base_url())
26414            .timeout(Duration::from_secs(2))
26415            .build()
26416            .expect("client");
26417
26418        let handle = client
26419            .start_workflow_with_options(
26420                "rust.timeout",
26421                "rust-timeouts",
26422                "wf-start-options",
26423                WorkflowStartOptions::new()
26424                    .execution_timeout_seconds(30)
26425                    .run_timeout_seconds(1),
26426                json!([]),
26427            )
26428            .await
26429            .expect("workflow start");
26430
26431        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
26432        let body = server.request_body("/api/workflows");
26433        assert_eq!(body["execution_timeout_seconds"], 30);
26434        assert_eq!(body["run_timeout_seconds"], 1);
26435
26436        let invalid = client
26437            .start_workflow_with_options(
26438                "rust.timeout",
26439                "rust-timeouts",
26440                "wf-invalid-options",
26441                WorkflowStartOptions::new()
26442                    .execution_timeout_seconds(1)
26443                    .run_timeout_seconds(2),
26444                json!([]),
26445            )
26446            .await
26447            .expect_err("invalid deadline ordering");
26448        assert!(invalid
26449            .to_string()
26450            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
26451    }
26452
26453    #[tokio::test]
26454    async fn workflow_result_returns_each_typed_terminal_outcome() {
26455        let server = MockWorkerServer::start();
26456        let client = Client::builder(server.base_url())
26457            .timeout(Duration::from_secs(2))
26458            .build()
26459            .expect("client");
26460        let options = WorkflowResultOptions {
26461            poll_interval: Duration::ZERO,
26462            timeout: Duration::from_secs(1),
26463        };
26464
26465        let failed = WorkflowHandle {
26466            client: client.clone(),
26467            workflow_id: "wf-failed".to_string(),
26468            run_id: Some("run-failed".to_string()),
26469            workflow_type: "failure".to_string(),
26470        }
26471        .result(options)
26472        .await
26473        .expect_err("failed outcome");
26474        let Error::WorkflowFailed(failure) = failed else {
26475            panic!("expected WorkflowFailed");
26476        };
26477        assert_eq!(failure.workflow_id, "wf-failed");
26478        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
26479        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
26480        assert_eq!(failure.failure_category.as_deref(), Some("application"));
26481        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
26482        assert_eq!(
26483            failure.exception_class.as_deref(),
26484            Some("billing::PaymentError")
26485        );
26486        assert_eq!(failure.non_retryable, Some(true));
26487
26488        for (workflow_id, expected_kind, expected_reason) in [
26489            (
26490                "wf-cancelled",
26491                WorkflowTerminalKind::Cancelled,
26492                "cleanup requested",
26493            ),
26494            (
26495                "wf-terminated",
26496                WorkflowTerminalKind::Terminated,
26497                "forced stop",
26498            ),
26499            (
26500                "wf-timed-out",
26501                WorkflowTerminalKind::TimedOut,
26502                "run_timeout",
26503            ),
26504        ] {
26505            let error = WorkflowHandle {
26506                client: client.clone(),
26507                workflow_id: workflow_id.to_string(),
26508                run_id: None,
26509                workflow_type: "terminal".to_string(),
26510            }
26511            .result(options)
26512            .await
26513            .expect_err("typed terminal outcome");
26514            let outcome = match error {
26515                Error::WorkflowCancelled(outcome) => outcome,
26516                Error::WorkflowTerminated(outcome) => outcome,
26517                Error::WorkflowTimedOut(outcome) => outcome,
26518                other => panic!("unexpected terminal error: {other}"),
26519            };
26520            assert_eq!(outcome.kind, expected_kind);
26521            assert_eq!(outcome.workflow_id, workflow_id);
26522            assert_eq!(outcome.reason, expected_reason);
26523        }
26524
26525        let wait_timeout = WorkflowHandle {
26526            client,
26527            workflow_id: "wf-waiting".to_string(),
26528            run_id: Some("run-waiting".to_string()),
26529            workflow_type: "waiting".to_string(),
26530        }
26531        .result(WorkflowResultOptions {
26532            poll_interval: Duration::ZERO,
26533            timeout: Duration::ZERO,
26534        })
26535        .await
26536        .expect_err("client wait timeout");
26537        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26538            panic!("expected typed client timeout");
26539        };
26540        assert_eq!(timeout.reason, "result_wait_timeout");
26541        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26542        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26543    }
26544
26545    #[tokio::test]
26546    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26547        let server = MockWorkerServer::start();
26548        let client = Client::builder(server.base_url())
26549            .timeout(Duration::from_secs(2))
26550            .build()
26551            .expect("client");
26552
26553        let handle = WorkflowHandle {
26554            client,
26555            workflow_id: "wf-selected".to_string(),
26556            run_id: Some("run-selected".to_string()),
26557            workflow_type: "selected".to_string(),
26558        };
26559        let options = WorkflowResultOptions {
26560            poll_interval: Duration::ZERO,
26561            timeout: Duration::from_secs(1),
26562        };
26563
26564        let current = handle
26565            .result(options)
26566            .await
26567            .expect("instance result follows the current run");
26568        assert_eq!(current, json!("current run output"));
26569
26570        let error = handle
26571            .result_selected_run(options)
26572            .await
26573            .expect_err("the selected run is cancelled even though the current run completed");
26574
26575        let Error::WorkflowCancelled(outcome) = error else {
26576            panic!("expected selected run cancellation");
26577        };
26578        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26579        assert_eq!(outcome.reason, "selected run cancelled");
26580        assert_eq!(
26581            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26582            1
26583        );
26584        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
26585    }
26586
26587    #[tokio::test]
26588    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
26589        let server = MockWorkerServer::draining_polls();
26590        let client = Client::builder(server.base_url())
26591            .timeout(Duration::from_secs(2))
26592            .build()
26593            .expect("client");
26594
26595        let workflow = client
26596            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
26597            .await
26598            .expect("workflow drain response");
26599        let activity = client
26600            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
26601            .await
26602            .expect("activity drain response");
26603        let query = client
26604            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
26605            .await
26606            .expect("query drain response");
26607
26608        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
26609            assert_eq!(
26610                outcome,
26611                WorkerPollOutcome::Stop {
26612                    poll_status: Some("draining".to_string()),
26613                    reason: Some("worker_draining".to_string()),
26614                }
26615            );
26616        }
26617
26618        assert!(client
26619            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
26620            .await
26621            .expect("compatibility poll")
26622            .is_none());
26623    }
26624
26625    #[tokio::test]
26626    async fn managed_worker_honors_drain_stop_for_every_task_family() {
26627        let server = MockWorkerServer::draining_polls();
26628        let client = Client::builder(server.base_url())
26629            .timeout(Duration::from_secs(2))
26630            .build()
26631            .expect("client");
26632
26633        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
26634            .worker_id("draining-workflow-worker")
26635            .poll_timeout(Duration::ZERO);
26636        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
26637        workflow_worker
26638            .run()
26639            .await
26640            .expect("workflow drain is a clean stop");
26641
26642        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
26643            .worker_id("draining-activity-worker")
26644            .poll_timeout(Duration::ZERO);
26645        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
26646        activity_worker
26647            .run()
26648            .await
26649            .expect("activity drain is a clean stop");
26650
26651        let mut query_worker = Worker::new(client, "rust-workers")
26652            .worker_id("draining-query-worker")
26653            .poll_timeout(Duration::ZERO);
26654        query_worker.register_query("counter", "current", |_ctx, _args| async {
26655            Ok(Value::Null)
26656        });
26657        query_worker
26658            .run()
26659            .await
26660            .expect("query drain is a clean stop");
26661    }
26662
26663    #[tokio::test]
26664    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
26665        let server = MockWorkerServer::start();
26666        let client = Client::builder(server.base_url())
26667            .timeout(Duration::from_secs(2))
26668            .build()
26669            .expect("client");
26670
26671        let details: Value = serde_json::from_str(include_str!(
26672            "../tests/fixtures/activity-heartbeat-progress.json"
26673        ))
26674        .expect("heartbeat progress fixture");
26675        // Every individual field fits Server's progress contract, while the
26676        // obsolete encoded envelope exceeded its 191-character string limit.
26677        assert!(
26678            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
26679                .unwrap()["blob"]
26680                .as_str()
26681                .unwrap()
26682                .len()
26683                > 191
26684        );
26685        let heartbeat = client
26686            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
26687            .await
26688            .expect("cancellation heartbeat");
26689        assert!(heartbeat.cancel_requested);
26690        assert!(heartbeat.should_stop());
26691        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
26692        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
26693        let heartbeat_body =
26694            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
26695        assert_eq!(heartbeat_body["details"], details);
26696        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
26697        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
26698
26699        let error = client
26700            .complete_activity_task(
26701                "activity-cancel",
26702                "attempt-cancel",
26703                "rust-worker",
26704                json!({"late":true}),
26705                DEFAULT_CODEC,
26706            )
26707            .await
26708            .expect_err("late completion must be refused");
26709        assert!(activity_task_rejection_is_final(&error));
26710        let Error::ActivityTaskRejected(rejection) = error else {
26711            panic!("expected typed activity rejection");
26712        };
26713        assert_eq!(rejection.status, 409);
26714        assert_eq!(rejection.reason, "run_cancelled");
26715        assert!(rejection.cancel_requested);
26716        assert_eq!(rejection.can_continue, Some(false));
26717    }
26718
26719    #[tokio::test]
26720    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
26721        let server = MockWorkerServer::cancelled_activity();
26722        let client = Client::builder(server.base_url())
26723            .timeout(Duration::from_secs(2))
26724            .build()
26725            .expect("client");
26726        let cancellation_observed = Arc::new(AtomicBool::new(false));
26727        let observed = Arc::clone(&cancellation_observed);
26728        let mut worker = Worker::new(client.clone(), "rust-workers")
26729            .worker_id("rust-cancel-worker")
26730            .poll_timeout(Duration::from_millis(10));
26731        worker.register_activity("cancel-aware", move |ctx, _args| {
26732            let observed = Arc::clone(&observed);
26733            async move {
26734                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
26735                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
26736                Ok(json!({"late":"completion"}))
26737            }
26738        });
26739
26740        assert_eq!(
26741            worker.run_once().await.expect("cancelled attempt handled"),
26742            1
26743        );
26744        assert!(cancellation_observed.load(Ordering::SeqCst));
26745        assert_eq!(
26746            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
26747            1
26748        );
26749
26750        let mut restarted = Worker::new(client, "rust-workers")
26751            .worker_id("rust-cancel-worker-restarted")
26752            .poll_timeout(Duration::from_millis(10));
26753        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
26754        assert_eq!(
26755            restarted
26756                .run_once()
26757                .await
26758                .expect("replacement worker continues polling"),
26759            0
26760        );
26761    }
26762
26763    #[tokio::test]
26764    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
26765        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"}"#;
26766        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
26767        let client = Client::builder(server.base_url())
26768            .timeout(Duration::from_secs(2))
26769            .build()
26770            .expect("client");
26771
26772        let direct_error = client
26773            .complete_workflow_task(
26774                "workflow-timeout-task",
26775                "timeout-worker",
26776                3,
26777                vec![json!({
26778                    "type": "complete_workflow",
26779                    "result": fixture_envelope(Value::Null)
26780                })],
26781            )
26782            .await
26783            .expect_err("the low-level client preserves the completion rejection");
26784        let Error::Http { status, body } = direct_error else {
26785            panic!("expected the original HTTP completion rejection");
26786        };
26787        assert_eq!(status, reqwest::StatusCode::CONFLICT);
26788        assert_eq!(
26789            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
26790            "run_timed_out"
26791        );
26792
26793        let mut worker = Worker::new(client, "rust-workers")
26794            .worker_id("timeout-worker")
26795            .poll_timeout(Duration::from_millis(10));
26796        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26797            Ok(json!({"late": "result"}))
26798        });
26799
26800        assert_eq!(
26801            worker
26802                .run_once()
26803                .await
26804                .expect("authoritative selected-run timeout settles the tick"),
26805            1
26806        );
26807        assert_eq!(
26808            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
26809            2,
26810            "both the direct client proof and managed worker must see the rejection"
26811        );
26812    }
26813
26814    #[tokio::test]
26815    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
26816        for (name, status, response) in [
26817            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
26818            (
26819                "command was recorded",
26820                "409 Conflict",
26821                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26822            ),
26823            (
26824                "lease conflict",
26825                "409 Conflict",
26826                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
26827            ),
26828            (
26829                "nonterminal run",
26830                "409 Conflict",
26831                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
26832            ),
26833            (
26834                "different selected run",
26835                "409 Conflict",
26836                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"}"#,
26837            ),
26838            (
26839                "different task attempt",
26840                "409 Conflict",
26841                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26842            ),
26843            (
26844                "authentication failure",
26845                "401 Unauthorized",
26846                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26847            ),
26848            (
26849                "authorization failure",
26850                "403 Forbidden",
26851                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26852            ),
26853            (
26854                "protocol failure",
26855                "400 Bad Request",
26856                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
26857            ),
26858            (
26859                "malformed command",
26860                "422 Unprocessable Entity",
26861                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26862            ),
26863            (
26864                "transient server failure",
26865                "503 Service Unavailable",
26866                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26867            ),
26868        ] {
26869            let server = MockWorkerServer::workflow_completion(status, response);
26870            let client = Client::builder(server.base_url())
26871                .timeout(Duration::from_secs(2))
26872                .build()
26873                .expect("client");
26874            let mut worker = Worker::new(client, "rust-workers")
26875                .worker_id("timeout-worker")
26876                .poll_timeout(Duration::from_millis(10));
26877            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26878                Ok(json!({"late": "result"}))
26879            });
26880
26881            let error = worker
26882                .run_once()
26883                .await
26884                .expect_err(&format!("{name} must remain an error"));
26885            assert!(
26886                matches!(error, Error::Http { .. } | Error::Protocol(_)),
26887                "{name} returned an unexpected error variant: {error}"
26888            );
26889        }
26890    }
26891
26892    #[tokio::test]
26893    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
26894        let server = MockWorkerServer::start();
26895        let client = Client::builder(server.base_url())
26896            .worker_token(Some("worker-secret".to_string()))
26897            .namespace("orders")
26898            .timeout(Duration::from_secs(2))
26899            .build()
26900            .expect("client");
26901        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
26902
26903        let result = client
26904            .deregister_worker_registration("worker/α space")
26905            .await
26906            .expect("deregister worker registration");
26907
26908        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
26909        assert_eq!(
26910            server.worker_protocol_for(path).as_deref(),
26911            Some(WORKER_PROTOCOL_VERSION)
26912        );
26913        assert_eq!(server.control_protocol_for(path), None);
26914        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
26915        assert_eq!(
26916            server.authorization_for(path).as_deref(),
26917            Some("Bearer worker-secret")
26918        );
26919        assert_eq!(
26920            result,
26921            WorkerDeregistrationEnvelope {
26922                worker_id: "deregistered-worker".to_string(),
26923                outcome: "deregistered".to_string(),
26924                recovered_workflow_task_count: 2,
26925            }
26926        );
26927    }
26928
26929    #[tokio::test]
26930    async fn low_level_registration_rejects_update_validators_before_transport() {
26931        let server = MockWorkerServer::start();
26932        let client = Client::builder(server.base_url())
26933            .timeout(Duration::from_secs(2))
26934            .build()
26935            .expect("client");
26936
26937        for update_validators in [json!(["approve"]), json!("approve")] {
26938            let error = client
26939                .register_worker_with_command_contracts(
26940                    "validator-claiming-worker",
26941                    "rust-workers",
26942                    vec!["orders".to_string()],
26943                    vec![],
26944                    1,
26945                    1,
26946                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26947                    json!({
26948                        "orders": {
26949                            "queries": ["current"],
26950                            "updates": ["approve"],
26951                            "update_validators": update_validators,
26952                        },
26953                    }),
26954                )
26955                .await
26956                .expect_err("unsupported validator claims must fail before registration");
26957
26958            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
26959                panic!("expected typed unsupported-validator failure");
26960            };
26961            assert_eq!(workflow_type, "orders");
26962        }
26963        assert_eq!(server.request_count("/api/worker/register"), 0);
26964    }
26965
26966    #[tokio::test]
26967    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
26968        let server = MockWorkerServer::start();
26969        let client = Client::builder(server.base_url())
26970            .timeout(Duration::from_secs(2))
26971            .build()
26972            .expect("client");
26973        let mut worker = Worker::new(client, "rust-workers");
26974        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
26975        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
26976        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26977        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
26978        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26979        worker
26980            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
26981            .expect("declare workflow signals");
26982
26983        worker.register().await.expect("register handler contracts");
26984
26985        let declaration =
26986            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
26987        let expected_contracts = json!([
26988            {
26989                "name": "a-avro",
26990                "parameters": [{
26991                    "name": "args", "position": 0, "required": false,
26992                    "variadic": true, "type": null, "allows_null": true,
26993                    "default_available": false, "default": null,
26994                }],
26995            },
26996            {
26997                "name": "z-json",
26998                "parameters": [{
26999                    "name": "args", "position": 0, "required": false,
27000                    "variadic": true, "type": null, "allows_null": true,
27001                    "default_available": false, "default": null,
27002                }],
27003            },
27004        ]);
27005        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
27006        assert_eq!(declaration["query_contracts"], expected_contracts);
27007        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
27008        assert_eq!(declaration["update_contracts"], expected_contracts);
27009        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
27010        assert_eq!(declaration["signal_contracts"], expected_contracts);
27011        assert_eq!(declaration["update_validators"], json!([]));
27012    }
27013
27014    #[tokio::test]
27015    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
27016        let server = MockWorkerServer::start();
27017        let client = Client::new(server.base_url()).expect("client");
27018        let mut worker = Worker::new(client, "rust-workers");
27019        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
27020        assert!(worker
27021            .declare_workflow_signals("missing", &["finish"])
27022            .is_err());
27023        worker
27024            .declare_workflow_signals("orders", &["finish"])
27025            .unwrap();
27026        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
27027            assert!(worker.declare_workflow_signals("orders", names).is_err());
27028        }
27029        worker.register().await.unwrap();
27030        assert_eq!(
27031            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
27032                ["signals"],
27033            json!(["finish"])
27034        );
27035        worker.declare_workflow_signals("orders", &[]).unwrap();
27036        worker.register().await.unwrap();
27037        let registrations = server.request_bodies("/api/worker/register");
27038        assert_eq!(
27039            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
27040            json!([])
27041        );
27042        assert_eq!(
27043            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
27044            json!([])
27045        );
27046    }
27047
27048    #[tokio::test]
27049    async fn low_level_registration_preserves_query_and_update_contracts() {
27050        let server = MockWorkerServer::start();
27051        let client = Client::builder(server.base_url())
27052            .timeout(Duration::from_secs(2))
27053            .build()
27054            .expect("client");
27055        let contracts = json!({
27056            "orders": {
27057                "queries": ["current"],
27058                "updates": ["approve"],
27059                "update_validators": [],
27060            },
27061            "payments": {
27062                "queries": ["status"],
27063                "updates": ["capture"],
27064            },
27065        });
27066
27067        client
27068            .register_worker_with_command_contracts(
27069                "command-worker",
27070                "rust-workers",
27071                vec!["orders".to_string(), "payments".to_string()],
27072                vec![],
27073                1,
27074                1,
27075                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27076                contracts.clone(),
27077            )
27078            .await
27079            .expect("query and update contracts must remain supported");
27080
27081        assert_eq!(
27082            server.request_body("/api/worker/register")["workflow_command_contracts"],
27083            contracts
27084        );
27085        assert!(server
27086            .request_body("/api/worker/register")
27087            .get("workflow_definition_fingerprints")
27088            .is_none());
27089    }
27090
27091    #[tokio::test]
27092    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
27093        let server = MockWorkerServer::start();
27094        let client = Client::builder(server.base_url())
27095            .timeout(Duration::from_secs(2))
27096            .build()
27097            .expect("client");
27098        let mut worker = Worker::new(client.clone(), "rust-workers");
27099        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27100
27101        assert!(worker
27102            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
27103            .is_err());
27104        assert!(worker
27105            .set_workflow_definition_sources("orders", &[])
27106            .is_err());
27107        worker
27108            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
27109            .expect("embed workflow source");
27110        worker.register().await.expect("register worker");
27111        let first = server.request_bodies("/api/worker/register")[0]
27112            ["workflow_definition_fingerprints"]["orders"]
27113            .as_str()
27114            .expect("source-backed fingerprint")
27115            .to_string();
27116        assert!(first.starts_with("sha256:"));
27117
27118        worker
27119            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
27120            .expect("change embedded helper source");
27121        worker.register().await.expect("register changed source");
27122        let changed = server.request_bodies("/api/worker/register")[1]
27123            ["workflow_definition_fingerprints"]["orders"]
27124            .as_str()
27125            .expect("changed fingerprint")
27126            .to_string();
27127        assert_ne!(first, changed);
27128
27129        let mut replacement =
27130            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27131        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27132        replacement
27133            .register()
27134            .await
27135            .expect("register replacement handler");
27136        assert_eq!(
27137            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27138            json!({})
27139        );
27140    }
27141
27142    #[tokio::test]
27143    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27144        let server = MockWorkerServer::start();
27145        let control_only = Client::builder(server.base_url())
27146            .control_token(Some("control-secret".to_string()))
27147            .build()
27148            .expect("control client");
27149
27150        let error = control_only
27151            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27152            .await
27153            .expect_err("control token must not authorize a worker request");
27154        assert!(matches!(
27155            error,
27156            Error::MissingRoleCredentials { role: "worker", .. }
27157        ));
27158        assert_eq!(server.request_count("/api/worker/register"), 0);
27159
27160        let worker_only = Client::builder(server.base_url())
27161            .worker_token(Some("worker-secret".to_string()))
27162            .build()
27163            .expect("worker client");
27164        let error = worker_only
27165            .health()
27166            .await
27167            .expect_err("worker token must not authorize a control request");
27168        assert!(matches!(
27169            error,
27170            Error::MissingRoleCredentials {
27171                role: "control",
27172                ..
27173            }
27174        ));
27175        assert_eq!(server.request_count("/api/health"), 0);
27176    }
27177
27178    #[tokio::test]
27179    async fn shared_token_supports_worker_and_control_planes() {
27180        let server = MockWorkerServer::start();
27181        let client = Client::builder(server.base_url())
27182            .token(Some("shared-secret".to_string()))
27183            .build()
27184            .expect("client");
27185
27186        client.health().await.expect("control request");
27187        client
27188            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27189            .await
27190            .expect("worker request");
27191
27192        assert_eq!(
27193            server.authorization_for("/api/health").as_deref(),
27194            Some("Bearer shared-secret")
27195        );
27196        assert_eq!(
27197            server.control_protocol_for("/api/health").as_deref(),
27198            Some(CONTROL_PLANE_VERSION)
27199        );
27200        assert_eq!(
27201            server.authorization_for("/api/worker/register").as_deref(),
27202            Some("Bearer shared-secret")
27203        );
27204        assert_eq!(
27205            server
27206                .worker_protocol_for("/api/worker/register")
27207                .as_deref(),
27208            Some(WORKER_PROTOCOL_VERSION)
27209        );
27210    }
27211
27212    #[tokio::test]
27213    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27214        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27215        let server = MockWorkerServer::start();
27216        let client = Client::builder(server.base_url())
27217            .timeout(Duration::from_secs(2))
27218            .build()
27219            .expect("client");
27220
27221        client
27222            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27223            .await
27224            .expect("register");
27225        client
27226            .heartbeat_worker("capture-worker", 1, 1)
27227            .await
27228            .expect("heartbeat");
27229        client
27230            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27231            .await
27232            .expect("workflow poll");
27233        client
27234            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27235            .await
27236            .expect("activity poll");
27237
27238        for path in [
27239            "/api/worker/register",
27240            "/api/worker/heartbeat",
27241            "/api/worker/workflow-tasks/poll",
27242            "/api/worker/activity-tasks/poll",
27243        ] {
27244            assert_eq!(
27245                server.worker_protocol_for(path).as_deref(),
27246                Some(WORKER_PROTOCOL_VERSION),
27247                "unexpected protocol for {path}"
27248            );
27249        }
27250
27251        assert_eq!(
27252            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27253            1
27254        );
27255        assert_eq!(
27256            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27257            500
27258        );
27259        assert_eq!(
27260            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27261            1
27262        );
27263        assert!(
27264            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27265                .as_str()
27266                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27267        );
27268        assert!(
27269            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27270                .as_str()
27271                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27272        );
27273        let registration = server.request_body("/api/worker/register");
27274        for optional in [
27275            "cooperative_cancellation",
27276            "local_activities",
27277            "worker_sessions",
27278            "sticky_execution",
27279        ] {
27280            assert!(!registration["capabilities"]
27281                .as_array()
27282                .is_some_and(|capabilities| capabilities
27283                    .iter()
27284                    .any(|capability| capability.as_str() == Some(optional))));
27285        }
27286    }
27287
27288    #[tokio::test]
27289    async fn explicit_previous_worker_protocol_preserves_headers() {
27290        let server = MockWorkerServer::start();
27291        let client = Client::builder(server.base_url())
27292            .worker_protocol_version(WorkerProtocolVersion::V119)
27293            .timeout(Duration::from_secs(2))
27294            .build()
27295            .expect("client");
27296        client
27297            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27298            .await
27299            .expect("register");
27300        client
27301            .heartbeat_worker("legacy-worker", 1, 1)
27302            .await
27303            .expect("heartbeat");
27304        client
27305            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27306            .await
27307            .expect("workflow poll");
27308        client
27309            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27310            .await
27311            .expect("activity poll");
27312        client
27313            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27314            .await
27315            .expect("query poll");
27316        client
27317            .deregister_worker_registration("legacy-worker")
27318            .await
27319            .expect("deregister");
27320        for path in [
27321            "/api/worker/register",
27322            "/api/worker/heartbeat",
27323            "/api/worker/workflow-tasks/poll",
27324            "/api/worker/activity-tasks/poll",
27325            "/api/worker/query-tasks/poll",
27326            "/api/worker/registrations/legacy-worker",
27327        ] {
27328            assert_eq!(
27329                server.worker_protocol_for(path).as_deref(),
27330                Some("1.19"),
27331                "{path}"
27332            );
27333            assert_eq!(server.control_protocol_for(path), None, "{path}");
27334        }
27335    }
27336
27337    #[tokio::test]
27338    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
27339        let server = MockWorkerServer::start();
27340        let client = Client::builder(server.base_url())
27341            .worker_protocol_version(WorkerProtocolVersion::V119)
27342            .timeout(Duration::from_secs(2))
27343            .build()
27344            .expect("client");
27345        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
27346        let error = worker
27347            .register()
27348            .await
27349            .expect_err("legacy cooperation must be refused");
27350        assert!(matches!(
27351            error,
27352            Error::CooperativeCancellationUnavailable(_)
27353        ));
27354        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
27355    }
27356
27357    #[tokio::test]
27358    async fn query_task_endpoints_send_the_selected_worker_protocol() {
27359        let server = MockWorkerServer::start();
27360        let client = Client::builder(server.base_url())
27361            .timeout(Duration::from_secs(2))
27362            .build()
27363            .expect("client");
27364
27365        client
27366            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27367            .await
27368            .expect("query poll");
27369        client
27370            .complete_query_task(
27371                "query-capture",
27372                "capture-worker",
27373                1,
27374                json!(8),
27375                DEFAULT_CODEC,
27376            )
27377            .await
27378            .expect("query complete");
27379        client
27380            .fail_query_task(
27381                "query-capture",
27382                "capture-worker",
27383                1,
27384                "failed",
27385                "query_rejected",
27386                "QueryFailed",
27387            )
27388            .await
27389            .expect("query fail");
27390
27391        for path in [
27392            "/api/worker/query-tasks/poll",
27393            "/api/worker/query-tasks/query-capture/complete",
27394            "/api/worker/query-tasks/query-capture/fail",
27395        ] {
27396            assert_eq!(
27397                server.worker_protocol_for(path).as_deref(),
27398                Some(WORKER_PROTOCOL_VERSION),
27399                "unexpected protocol for {path}"
27400            );
27401        }
27402
27403        assert_eq!(
27404            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
27405            1
27406        );
27407        assert!(
27408            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
27409                .as_str()
27410                .is_some_and(|id| id.starts_with("rust-query-poll-"))
27411        );
27412    }
27413
27414    #[tokio::test]
27415    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
27416        let server = MockWorkerServer::transient_worker_failures();
27417        let client = Client::builder(server.base_url())
27418            .timeout(Duration::from_secs(2))
27419            .build()
27420            .expect("client");
27421
27422        client
27423            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27424            .await
27425            .expect("workflow poll retry");
27426        client
27427            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27428            .await
27429            .expect("activity poll retry");
27430        client
27431            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27432            .await
27433            .expect("query poll retry");
27434
27435        for path in [
27436            "/api/worker/workflow-tasks/poll",
27437            "/api/worker/activity-tasks/poll",
27438            "/api/worker/query-tasks/poll",
27439        ] {
27440            let bodies = server.request_bodies(path);
27441            assert_eq!(bodies.len(), 2, "{path} must be retried once");
27442            assert_eq!(
27443                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
27444                "{path} must preserve the request binding across retry"
27445            );
27446        }
27447    }
27448
27449    #[tokio::test]
27450    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
27451        let server = MockWorkerServer::consecutive_poll_failures(2);
27452        let client = Client::builder(server.base_url())
27453            .timeout(Duration::from_secs(2))
27454            .build()
27455            .expect("client");
27456        let mut worker = Worker::new(client, "capture")
27457            .worker_id("capture-worker")
27458            .poll_timeout(Duration::from_millis(10))
27459            .retry_policy(WorkerRetryPolicy {
27460                max_retries: 2,
27461                initial_backoff: Duration::from_millis(1),
27462                max_backoff: Duration::from_millis(1),
27463            });
27464        worker.register_workflow(
27465            "capture.workflow",
27466            |_ctx, _input| async move { Ok(Value::Null) },
27467        );
27468        worker.register_activity(
27469            "capture.activity",
27470            |_ctx, _input| async move { Ok(Value::Null) },
27471        );
27472        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
27473            Ok(Value::Null)
27474        });
27475
27476        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
27477
27478        for path in [
27479            "/api/worker/workflow-tasks/poll",
27480            "/api/worker/activity-tasks/poll",
27481            "/api/worker/query-tasks/poll",
27482        ] {
27483            let bodies = server.request_bodies(path);
27484            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
27485            assert!(
27486                bodies
27487                    .iter()
27488                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
27489                "{path} must preserve one request binding across every retry"
27490            );
27491        }
27492    }
27493
27494    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
27495        let reason = if unavailable {
27496            "storage_admission_unavailable"
27497        } else {
27498            "storage_pressure"
27499        };
27500        let mut body = json!({
27501            "reason": reason,
27502            "storage_state": if unavailable { "fenced" } else { "draining" },
27503            "retryable": true,
27504            "retry_after_seconds": 1,
27505        });
27506        if !mid_poll {
27507            body["request_admitted"] = json!(false);
27508        }
27509        if let Some(id) = poll_id {
27510            body["task"] = Value::Null;
27511            body["poll_status"] = json!(reason);
27512            body["poll_request_id"] = json!(id);
27513            body["retry_same_poll_request_id"] = json!(true);
27514            body["claim_admitted"] = json!(false);
27515        }
27516        body
27517    }
27518
27519    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
27520        let operation = match path {
27521            "/api/worker/register" => "register_worker",
27522            "/api/worker/heartbeat" => "heartbeat_worker",
27523            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
27524            "/api/worker/activity-tasks/poll" => "poll_activity_task",
27525            "/api/worker/query-tasks/poll" => "poll_query_task",
27526            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
27527            _ => return None,
27528        };
27529        let request: Value = serde_json::from_str(request).ok()?;
27530        let mut response = json!({
27531            "reason": "backend_unavailable",
27532            "operation": operation,
27533            "outcome": "unknown",
27534            "retryable": true,
27535            "retry_after_seconds": 1,
27536            "worker_id": request["worker_id"],
27537            "task_queue": request.get("task_queue"),
27538        });
27539        if path.ends_with("/poll") {
27540            response["task"] = Value::Null;
27541            response["poll_status"] = json!("backend_unavailable");
27542            response["poll_request_id"] = request["poll_request_id"].clone();
27543            response["retry_same_poll_request_id"] = json!(true);
27544        }
27545        Some(response)
27546    }
27547
27548    fn backend_retry_override(
27549        path: &str,
27550        request: &str,
27551        number: usize,
27552    ) -> Option<(&'static str, String)> {
27553        if number > 8 {
27554            return None;
27555        }
27556        Some((
27557            "503 Service Unavailable",
27558            backend_refusal(path, request)?.to_string(),
27559        ))
27560    }
27561
27562    fn backend_unavailable_override(
27563        path: &str,
27564        request: &str,
27565        _number: usize,
27566    ) -> Option<(&'static str, String)> {
27567        Some((
27568            "503 Service Unavailable",
27569            backend_refusal(path, request)?.to_string(),
27570        ))
27571    }
27572
27573    fn storage_worker(server: &MockWorkerServer) -> Worker {
27574        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
27575            .worker_id("storage-worker")
27576            .retry_policy(WorkerRetryPolicy {
27577                max_retries: 1,
27578                initial_backoff: Duration::from_millis(1),
27579                max_backoff: Duration::from_millis(1),
27580            })
27581    }
27582
27583    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
27584        let requests = server.requests.lock().expect("requests");
27585        let bodies: Vec<_> = requests
27586            .iter()
27587            .filter(|request| request.path == path)
27588            .map(|request| &request.body)
27589            .collect();
27590        assert_eq!(bodies.len(), count, "{path}");
27591        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
27592    }
27593
27594    #[test]
27595    fn backend_recovery_requires_the_explicit_worker_contract() {
27596        for (path, operation) in [
27597            ("/worker/register", "register_worker"),
27598            ("/worker/heartbeat", "heartbeat_worker"),
27599            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
27600            ("/worker/activity-tasks/poll", "poll_activity_task"),
27601            ("/worker/query-tasks/poll", "poll_query_task"),
27602            (
27603                "/worker/update-validation-tasks/poll",
27604                "poll_update_validation_task",
27605            ),
27606        ] {
27607            let poll_id = path.ends_with("/poll").then_some("same-poll");
27608            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
27609            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
27610                .expect("worker operation");
27611            assert_eq!(body["operation"], operation);
27612            let error = Error::Http {
27613                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27614                body: body.to_string(),
27615            };
27616            assert_eq!(
27617                worker_backend_unavailable_retry_after(&error, path, poll_id),
27618                Some(Duration::from_secs(1))
27619            );
27620            assert!(!worker_operation_is_retryable(&error));
27621            for (field, value) in [
27622                ("operation", json!("wrong_operation")),
27623                ("outcome", json!("completed")),
27624                ("retryable", json!(false)),
27625                ("retry_after_seconds", json!(0)),
27626                ("worker_id", json!("")),
27627            ] {
27628                let mut invalid = body.clone();
27629                invalid[field] = value;
27630                let error = Error::Http {
27631                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27632                    body: invalid.to_string(),
27633                };
27634                assert!(
27635                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
27636                    "{path}: {field}"
27637                );
27638                assert!(!worker_operation_is_retryable(&error));
27639            }
27640            if let Some(poll_id) = poll_id {
27641                for (field, value) in [
27642                    ("poll_request_id", json!("wrong-poll")),
27643                    ("poll_status", json!("empty")),
27644                    ("task", json!({"task_id":"claimed"})),
27645                    ("retry_same_poll_request_id", json!(false)),
27646                ] {
27647                    let mut invalid = body.clone();
27648                    invalid[field] = value;
27649                    let error = Error::Http {
27650                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27651                        body: invalid.to_string(),
27652                    };
27653                    assert!(
27654                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
27655                            .is_none(),
27656                        "{path}: {field}"
27657                    );
27658                }
27659            }
27660            let error = Error::Http {
27661                status: reqwest::StatusCode::UNAUTHORIZED,
27662                body: body.to_string(),
27663            };
27664            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
27665            assert!(!worker_operation_is_retryable(&error));
27666        }
27667    }
27668
27669    #[tokio::test]
27670    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
27671        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27672            request_override: Some(backend_retry_override),
27673            ..MockWorkerBehavior::default()
27674        });
27675        let mut worker =
27676            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27677        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27678        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
27679        worker.register_query("backend.workflow", "state", |_, _| async {
27680            Ok(Value::Null)
27681        });
27682        worker.register().await.expect("registration recovery");
27683        worker
27684            .client
27685            .heartbeat_worker("storage-worker", 1, 1)
27686            .await
27687            .expect("heartbeat recovery");
27688        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
27689        for path in [
27690            "/api/worker/register",
27691            "/api/worker/heartbeat",
27692            "/api/worker/workflow-tasks/poll",
27693            "/api/worker/activity-tasks/poll",
27694            "/api/worker/query-tasks/poll",
27695        ] {
27696            assert_identical_requests(&server, path, 9);
27697        }
27698    }
27699
27700    #[tokio::test]
27701    async fn backend_recovery_wait_stops_with_worker() {
27702        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27703            request_override: Some(backend_unavailable_override),
27704            ..MockWorkerBehavior::default()
27705        });
27706        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
27707            max_retries: 1,
27708            initial_backoff: Duration::from_secs(2),
27709            max_backoff: Duration::from_secs(2),
27710        });
27711        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27712        let started = tokio::time::Instant::now();
27713        let _ = tokio::time::timeout(
27714            Duration::from_secs(1),
27715            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
27716        )
27717        .await
27718        .expect("shutdown interrupts backend wait");
27719        assert!(started.elapsed() < Duration::from_secs(1));
27720        assert!(server.request_count("/api/worker/register") >= 1);
27721    }
27722
27723    #[test]
27724    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
27725        for unavailable in [false, true] {
27726            for mid_poll in [false, true] {
27727                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
27728                let error = Error::Http {
27729                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27730                    body: body.to_string(),
27731                };
27732                assert_eq!(
27733                    worker_storage_admission_retry_after(&error, Some("same-poll")),
27734                    Some(Duration::from_secs(1))
27735                );
27736                assert!(
27737                    !worker_operation_is_retryable(&error),
27738                    "storage is not a bounded generic retry"
27739                );
27740                for (field, value) in [
27741                    ("poll_request_id", json!("wrong-poll")),
27742                    ("task", json!({"task_id":"claimed"})),
27743                    ("retryable", json!(false)),
27744                    ("retry_after_seconds", json!(0)),
27745                    ("retry_after_seconds", json!(true)),
27746                    ("retry_after_seconds", json!(1.0)),
27747                    ("storage_state", json!("normal")),
27748                    ("poll_status", json!("empty")),
27749                    ("claim_admitted", json!(true)),
27750                    ("retry_same_poll_request_id", json!(false)),
27751                    ("request_admitted", json!(true)),
27752                ] {
27753                    let mut invalid = body.clone();
27754                    invalid[field] = value;
27755                    let error = Error::Http {
27756                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27757                        body: invalid.to_string(),
27758                    };
27759                    assert!(
27760                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
27761                        "{field}"
27762                    );
27763                }
27764            }
27765        }
27766        let body = storage_refusal(None, false, false);
27767        let error = Error::Http {
27768            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27769            body: body.to_string(),
27770        };
27771        assert!(worker_storage_admission_retry_after(&error, None).is_some());
27772        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
27773        let error = Error::Http {
27774            status: reqwest::StatusCode::FORBIDDEN,
27775            body: body.to_string(),
27776        };
27777        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27778        let body = storage_refusal(None, false, true);
27779        let error = Error::Http {
27780            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27781            body: body.to_string(),
27782        };
27783        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27784    }
27785
27786    #[tokio::test]
27787    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
27788        for unavailable in [false, true] {
27789            for mid_poll in [false, true] {
27790                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27791                    poll_failures_per_path: 1,
27792                    storage_refusals: 7,
27793                    storage_path: Some("/poll"),
27794                    storage_unavailable: unavailable,
27795                    storage_mid_poll: mid_poll,
27796                    ..MockWorkerBehavior::default()
27797                });
27798                let mut worker = storage_worker(&server);
27799                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
27800                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
27801                for path in [
27802                    "/api/worker/workflow-tasks/poll",
27803                    "/api/worker/activity-tasks/poll",
27804                    "/api/worker/query-tasks/poll",
27805                ] {
27806                    assert_identical_requests(&server, path, 9);
27807                }
27808            }
27809        }
27810    }
27811
27812    #[tokio::test]
27813    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
27814        struct CountedBody(Arc<AtomicUsize>);
27815        impl Serialize for CountedBody {
27816            fn serialize<S: Serializer>(
27817                &self,
27818                serializer: S,
27819            ) -> std::result::Result<S::Ok, S::Error> {
27820                let count = self.0.fetch_add(1, Ordering::SeqCst);
27821                json!({"serialization":count,"lease_owner":"worker","attempt":7})
27822                    .serialize(serializer)
27823            }
27824        }
27825        for path in [
27826            "/api/worker/register",
27827            "/api/worker/heartbeat",
27828            "/api/worker/workflow-tasks/storage-task/complete",
27829            "/api/worker/workflow-tasks/storage-task/fail",
27830            "/api/worker/activity-tasks/storage-task/complete",
27831            "/api/worker/activity-tasks/storage-task/fail",
27832            "/api/worker/activity-tasks/storage-task/heartbeat",
27833            "/api/worker/query-tasks/storage-task/complete",
27834            "/api/worker/query-tasks/storage-task/fail",
27835        ] {
27836            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27837                storage_refusals: 7,
27838                storage_path: Some(path),
27839                ..MockWorkerBehavior::default()
27840            });
27841            let worker =
27842                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27843            let calls = Arc::new(AtomicUsize::new(0));
27844            let _: Value = worker
27845                .client
27846                .request_json(
27847                    reqwest::Method::POST,
27848                    &path[4..],
27849                    RequestProtocol::DefaultWorker,
27850                    Some(&CountedBody(Arc::clone(&calls))),
27851                )
27852                .await
27853                .expect("prepared request recovery");
27854            assert_eq!(calls.load(Ordering::SeqCst), 1);
27855            assert_identical_requests(&server, path, 8);
27856        }
27857        for worker_scope in [false, true] {
27858            let path = if worker_scope {
27859                "/api/health"
27860            } else {
27861                "/api/worker/register"
27862            };
27863            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27864                storage_refusals: usize::MAX,
27865                storage_path: Some(path),
27866                ..MockWorkerBehavior::default()
27867            });
27868            let worker = storage_worker(&server);
27869            let client = worker.client.clone();
27870            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
27871            let error = if worker_scope {
27872                worker
27873                    .client
27874                    .health()
27875                    .await
27876                    .expect_err("control plane is not retried")
27877            } else {
27878                client
27879                    .request_json::<Value, Value>(
27880                        reqwest::Method::POST,
27881                        "/worker/register",
27882                        RequestProtocol::DefaultWorker,
27883                        Some(&json!({})),
27884                    )
27885                    .await
27886                    .expect_err("direct client is not retried")
27887            };
27888            assert!(worker_storage_admission_body(&error).is_some());
27889            assert_eq!(server.request_count(path), 1);
27890        }
27891    }
27892
27893    #[tokio::test]
27894    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
27895        for fail in [false, true] {
27896            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27897                storage_activity: true,
27898                storage_refusals: 7,
27899                storage_path: Some("/storage-activity/"),
27900                ..MockWorkerBehavior::default()
27901            });
27902            let mut worker = storage_worker(&server);
27903            let calls = Arc::new(AtomicUsize::new(0));
27904            let observed = Arc::clone(&calls);
27905            worker.register_activity("storage.activity", move |ctx, _| {
27906                let calls = Arc::clone(&observed);
27907                async move {
27908                    calls.fetch_add(1, Ordering::SeqCst);
27909                    ctx.heartbeat(json!({"step":2})).await?;
27910                    if fail {
27911                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
27912                    } else {
27913                        Ok(json!({"receipt":true}))
27914                    }
27915                }
27916            });
27917            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
27918            assert_eq!(calls.load(Ordering::SeqCst), 1);
27919            assert_identical_requests(
27920                &server,
27921                "/api/worker/activity-tasks/storage-activity/heartbeat",
27922                8,
27923            );
27924            let suffix = if fail { "fail" } else { "complete" };
27925            assert_identical_requests(
27926                &server,
27927                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
27928                8,
27929            );
27930            let other = if fail { "complete" } else { "fail" };
27931            assert_eq!(
27932                server.request_count(&format!(
27933                    "/api/worker/activity-tasks/storage-activity/{other}"
27934                )),
27935                0
27936            );
27937        }
27938    }
27939
27940    #[tokio::test]
27941    async fn storage_waits_are_interruptible_without_false_activity_failure() {
27942        for path in [
27943            "/api/worker/register",
27944            "/api/worker/heartbeat",
27945            "/api/worker/activity-tasks/poll",
27946            "/api/worker/activity-tasks/storage-activity/heartbeat",
27947            "/api/worker/activity-tasks/storage-activity/complete",
27948        ] {
27949            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27950                storage_activity: true,
27951                storage_refusals: usize::MAX,
27952                storage_path: Some(path),
27953                ..MockWorkerBehavior::default()
27954            });
27955            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27956            worker.register_activity("storage.activity", |ctx, _| async move {
27957                ctx.heartbeat(json!({"step":2})).await?;
27958                Ok(json!({"receipt":true}))
27959            });
27960            let shutdown = async {
27961                while server.request_count(path) == 0 {
27962                    tokio::time::sleep(Duration::from_millis(1)).await;
27963                }
27964            };
27965            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
27966                .await
27967                .expect("shutdown interrupts admission");
27968            assert!(
27969                result.is_err(),
27970                "a refused operation must not appear acknowledged: {path}, {result:?}"
27971            );
27972            assert_eq!(server.request_count(path), 1);
27973            assert_eq!(
27974                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
27975                0
27976            );
27977            assert_eq!(
27978                server.request_count("/api/worker/registrations/mock-worker"),
27979                usize::from(!path.ends_with("/register"))
27980            );
27981        }
27982    }
27983
27984    #[tokio::test]
27985    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
27986        for fail in [false, true] {
27987            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27988                storage_query: true,
27989                storage_refusals: 7,
27990                storage_path: Some("/storage-query/"),
27991                ..MockWorkerBehavior::default()
27992            });
27993            let mut worker = storage_worker(&server);
27994            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
27995            let calls = Arc::new(AtomicUsize::new(0));
27996            let observed = Arc::clone(&calls);
27997            worker.register_query("storage.workflow", "state", move |_, _| {
27998                let calls = Arc::clone(&observed);
27999                async move {
28000                    calls.fetch_add(1, Ordering::SeqCst);
28001                    if fail {
28002                        Err(Error::WorkerLoop("intentional query failure".to_string()))
28003                    } else {
28004                        Ok(json!({"state":"waiting"}))
28005                    }
28006                }
28007            });
28008            assert_eq!(worker.run_once().await.expect("query settled"), 1);
28009            assert_eq!(calls.load(Ordering::SeqCst), 1);
28010            let suffix = if fail { "fail" } else { "complete" };
28011            assert_identical_requests(
28012                &server,
28013                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
28014                8,
28015            );
28016            let other = if fail { "complete" } else { "fail" };
28017            assert_eq!(
28018                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
28019                0
28020            );
28021        }
28022    }
28023
28024    #[tokio::test]
28025    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
28026        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28027            storage_refusals: 7,
28028            storage_path: Some("/poll"),
28029            unauthorized_polls: true,
28030            ..MockWorkerBehavior::default()
28031        });
28032        let error = storage_worker(&server)
28033            .run_once()
28034            .await
28035            .expect_err("auth remains terminal");
28036        assert!(matches!(
28037            error,
28038            Error::Http {
28039                status: reqwest::StatusCode::UNAUTHORIZED,
28040                ..
28041            }
28042        ));
28043        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
28044
28045        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28046            storage_refusals: 7,
28047            storage_path: Some("/activity-cancel/complete"),
28048            ..MockWorkerBehavior::default()
28049        });
28050        let worker =
28051            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28052        let error = worker
28053            .client
28054            .complete_activity_task(
28055                "activity-cancel",
28056                "attempt-cancel",
28057                "worker",
28058                json!({}),
28059                DEFAULT_CODEC,
28060            )
28061            .await
28062            .expect_err("cancellation remains terminal");
28063        assert!(activity_task_rejection_is_final(&error));
28064        assert_identical_requests(
28065            &server,
28066            "/api/worker/activity-tasks/activity-cancel/complete",
28067            8,
28068        );
28069
28070        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28071            storage_refusals: usize::MAX,
28072            storage_path: Some("/poll"),
28073            storage_wrong_poll_id: true,
28074            ..MockWorkerBehavior::default()
28075        });
28076        assert!(storage_worker(&server).run_once().await.is_err());
28077        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28078    }
28079
28080    #[tokio::test]
28081    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
28082        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28083            storage_refusals: usize::MAX,
28084            storage_path: Some("/poll"),
28085            ..MockWorkerBehavior::default()
28086        });
28087        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28088        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
28089        let run = tokio::spawn(async move { worker.run().await });
28090        tokio::time::timeout(Duration::from_secs(2), async {
28091            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
28092                tokio::time::sleep(Duration::from_millis(1)).await;
28093            }
28094        })
28095        .await
28096        .expect("poll started");
28097        run.abort();
28098        assert!(run.await.expect_err("cancelled run").is_cancelled());
28099        tokio::time::sleep(Duration::from_millis(250)).await;
28100        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
28101    }
28102
28103    #[tokio::test]
28104    async fn query_protocol_rejection_from_older_server_is_typed() {
28105        let server = MockWorkerServer::reject_query_protocol();
28106        let client = Client::builder(server.base_url())
28107            .timeout(Duration::from_secs(2))
28108            .build()
28109            .expect("client");
28110
28111        let error = client
28112            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28113            .await
28114            .expect_err("server below query protocol floor must reject");
28115        let Error::Protocol(failure) = error else {
28116            panic!("expected typed protocol failure");
28117        };
28118
28119        assert_eq!(failure.status, 400);
28120        assert_eq!(failure.reason, "unsupported_protocol_version");
28121        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
28122        assert_eq!(
28123            failure.requested_version.as_deref(),
28124            Some(WORKER_PROTOCOL_VERSION)
28125        );
28126        assert_eq!(
28127            server
28128                .worker_protocol_for("/api/worker/query-tasks/poll")
28129                .as_deref(),
28130            Some(WORKER_PROTOCOL_VERSION)
28131        );
28132    }
28133
28134    #[tokio::test]
28135    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28136        let server = MockWorkerServer::reject_query_protocol();
28137        let client = Client::builder(server.base_url())
28138            .timeout(Duration::from_secs(2))
28139            .build()
28140            .expect("client");
28141        let mut worker = Worker::new(client, "rust-workers")
28142            .worker_id("baseline-worker")
28143            .poll_timeout(Duration::from_millis(10));
28144
28145        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28146            Ok(Value::Null)
28147        });
28148
28149        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28150        assert_eq!(
28151            server
28152                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28153                .as_deref(),
28154            Some(WORKER_PROTOCOL_VERSION)
28155        );
28156        assert_eq!(
28157            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28158            None,
28159            "a worker without query handlers must not use the query-task endpoint"
28160        );
28161    }
28162
28163    #[tokio::test]
28164    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28165        let server = MockWorkerServer::reject_query_completion();
28166        let client = Client::builder(server.base_url())
28167            .timeout(Duration::from_secs(2))
28168            .build()
28169            .expect("client");
28170
28171        let error = client
28172            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28173            .await
28174            .expect_err("expired completion must be rejected");
28175        let Error::QueryFailed(failure) = error else {
28176            panic!("expected typed query failure");
28177        };
28178        assert_eq!(failure.status, 409);
28179        assert_eq!(failure.reason, "query_task_timed_out");
28180
28181        let mut worker = Worker::new(client, "rust-workers")
28182            .worker_id("late-worker")
28183            .poll_timeout(Duration::from_millis(10));
28184        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28185        worker.register_query(
28186            "counter",
28187            "current",
28188            |_ctx, _args| async move { Ok(json!(8)) },
28189        );
28190
28191        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28192        assert_eq!(
28193            worker
28194                .run_once()
28195                .await
28196                .expect("worker continues after late completion"),
28197            0
28198        );
28199        assert_eq!(
28200            server.request_count("/api/worker/query-tasks/query-late/complete"),
28201            2
28202        );
28203        assert_eq!(
28204            server.request_count("/api/worker/query-tasks/query-late/fail"),
28205            0,
28206            "a server completion rejection must not be reported as an encoding failure"
28207        );
28208    }
28209
28210    #[tokio::test]
28211    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28212        let server = MockWorkerServer::start();
28213        let client = Client::builder(server.base_url())
28214            .timeout(Duration::from_secs(2))
28215            .build()
28216            .expect("client");
28217        let mut worker = Worker::new(client, "rust-workers")
28218            .worker_id("joined-worker")
28219            .poll_timeout(Duration::from_millis(10));
28220        worker.register_workflow(
28221            "joined.workflow",
28222            |_ctx, _input| async move { Ok(Value::Null) },
28223        );
28224        worker.register_activity(
28225            "joined.activity",
28226            |_ctx, _input| async move { Ok(Value::Null) },
28227        );
28228        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28229            Ok(Value::Null)
28230        });
28231
28232        worker
28233            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28234            .await
28235            .expect("normal shutdown");
28236
28237        let deregistration_path = "/api/worker/registrations/mock-worker";
28238        assert_eq!(server.request_count(deregistration_path), 1);
28239        for poll_path in [
28240            "/api/worker/workflow-tasks/poll",
28241            "/api/worker/activity-tasks/poll",
28242            "/api/worker/query-tasks/poll",
28243        ] {
28244            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28245        }
28246        assert_eq!(
28247            server.captured_paths().last().map(String::as_str),
28248            Some(deregistration_path),
28249            "deregistration must start only after every poller has joined"
28250        );
28251    }
28252
28253    #[tokio::test]
28254    async fn registration_failure_does_not_deregister() {
28255        let server = MockWorkerServer::rejected_registration();
28256        let client = Client::builder(server.base_url())
28257            .timeout(Duration::from_secs(2))
28258            .build()
28259            .expect("client");
28260        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28261
28262        let error = worker
28263            .run_until(async {})
28264            .await
28265            .expect_err("registration must fail");
28266        assert!(matches!(
28267            error,
28268            Error::Http {
28269                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28270                ..
28271            }
28272        ));
28273        assert!(server
28274            .captured_paths()
28275            .iter()
28276            .all(|path| !path.starts_with("/api/worker/registrations/")));
28277    }
28278
28279    #[tokio::test]
28280    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28281        let server = MockWorkerServer::rejected_registration_protocol();
28282        let client = Client::builder(server.base_url())
28283            .timeout(Duration::from_secs(2))
28284            .build()
28285            .expect("client");
28286        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28287
28288        let error = worker
28289            .run_until(async {})
28290            .await
28291            .expect_err("a protocol 1.16 server must reject this worker");
28292        let Error::Protocol(failure) = error else {
28293            panic!("expected typed protocol rejection");
28294        };
28295        assert_eq!(failure.reason, "unsupported_protocol_version");
28296        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28297        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28298        assert_eq!(
28299            server
28300                .worker_protocol_for("/api/worker/register")
28301                .as_deref(),
28302            Some(WORKER_PROTOCOL_VERSION)
28303        );
28304    }
28305
28306    #[tokio::test]
28307    async fn declined_registration_does_not_deregister() {
28308        let server = MockWorkerServer::declined_registration();
28309        let client = Client::builder(server.base_url())
28310            .timeout(Duration::from_secs(2))
28311            .build()
28312            .expect("client");
28313        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28314
28315        let error = worker
28316            .run_until(async {})
28317            .await
28318            .expect_err("declined registration must fail");
28319        assert!(matches!(error, Error::WorkerLoop(_)));
28320        assert!(error.to_string().contains("was not accepted"));
28321        assert!(server
28322            .captured_paths()
28323            .iter()
28324            .all(|path| !path.starts_with("/api/worker/registrations/")));
28325    }
28326
28327    #[tokio::test]
28328    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
28329        let server = MockWorkerServer::rejected_deregistration();
28330        let client = Client::builder(server.base_url())
28331            .timeout(Duration::from_secs(2))
28332            .build()
28333            .expect("client");
28334        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
28335
28336        let error = worker
28337            .run_until(async {})
28338            .await
28339            .expect_err("deregistration must fail");
28340        assert!(matches!(
28341            error,
28342            Error::Http {
28343                status: reqwest::StatusCode::FORBIDDEN,
28344                ..
28345            }
28346        ));
28347        assert_eq!(
28348            server.request_count("/api/worker/registrations/mock-worker"),
28349            1
28350        );
28351    }
28352
28353    #[tokio::test]
28354    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
28355        let server = MockWorkerServer::rejected_deregistration_protocol();
28356        let client = Client::builder(server.base_url())
28357            .timeout(Duration::from_secs(2))
28358            .build()
28359            .expect("client");
28360        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
28361
28362        let error = worker
28363            .run_until(async {})
28364            .await
28365            .expect_err("protocol rejection must fail shutdown");
28366        let Error::Protocol(failure) = error else {
28367            panic!("expected typed protocol failure");
28368        };
28369        assert_eq!(failure.reason, "unsupported_protocol_version");
28370        assert_eq!(
28371            failure.requested_version.as_deref(),
28372            Some(WORKER_PROTOCOL_VERSION)
28373        );
28374        assert_eq!(
28375            server.request_count("/api/worker/registrations/mock-worker"),
28376            1
28377        );
28378    }
28379
28380    #[tokio::test]
28381    async fn primary_poller_error_retains_deregistration_failure_context() {
28382        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
28383        let client = Client::builder(server.base_url())
28384            .timeout(Duration::from_secs(2))
28385            .build()
28386            .expect("client");
28387        let mut worker = Worker::new(client, "rust-workers")
28388            .worker_id("combined-failure")
28389            .poll_timeout(Duration::from_millis(10));
28390        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
28391            Ok(Value::Null)
28392        });
28393
28394        let error = worker
28395            .run()
28396            .await
28397            .expect_err("worker and cleanup must fail");
28398        let summary = error.to_string();
28399        assert!(summary.contains("authentication_failed"));
28400        assert!(summary.contains("worker cannot deregister"));
28401        let Error::WorkerShutdown {
28402            primary,
28403            deregistration,
28404        } = error
28405        else {
28406            panic!("expected combined worker shutdown error");
28407        };
28408        assert!(matches!(
28409            *primary,
28410            Error::Http {
28411                status: reqwest::StatusCode::UNAUTHORIZED,
28412                ..
28413            }
28414        ));
28415        assert!(matches!(
28416            *deregistration,
28417            Error::Http {
28418                status: reqwest::StatusCode::FORBIDDEN,
28419                ..
28420            }
28421        ));
28422        assert_eq!(
28423            server.request_count("/api/worker/registrations/mock-worker"),
28424            1
28425        );
28426    }
28427
28428    #[tokio::test]
28429    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
28430        let server = MockWorkerServer::start();
28431        let client = Client::builder(server.base_url())
28432            .timeout(Duration::from_secs(2))
28433            .build()
28434            .expect("client");
28435        let mut worker = Worker::new(client, "rust-workers")
28436            .worker_id("activity-only-worker")
28437            .poll_timeout(Duration::from_millis(10));
28438
28439        worker.register_activity(
28440            "activity.only",
28441            |_ctx, _args| async move { Ok(Value::Null) },
28442        );
28443
28444        worker.run_until(async {}).await.expect("run worker");
28445    }
28446
28447    #[tokio::test]
28448    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
28449        let server = MockWorkerServer::start();
28450        let client = Client::builder(server.base_url())
28451            .timeout(Duration::from_secs(2))
28452            .build()
28453            .expect("client");
28454        let mut worker = Worker::new(client, "rust-workers")
28455            .worker_id("workflow-only-worker")
28456            .poll_timeout(Duration::from_millis(10));
28457
28458        worker.register_workflow(
28459            "workflow.only",
28460            |_ctx, _input| async move { Ok(Value::Null) },
28461        );
28462
28463        worker.run_until(async {}).await.expect("run worker");
28464    }
28465
28466    #[tokio::test]
28467    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
28468        let server = MockWorkerServer::start();
28469        let client = Client::builder(server.base_url())
28470            .timeout(Duration::from_secs(2))
28471            .build()
28472            .expect("client");
28473        let observations = Arc::new(Mutex::new(Vec::new()));
28474        let observed = Arc::clone(&observations);
28475        let mut worker = Worker::new(client, "rust-workers")
28476            .worker_id("observed-heartbeat-worker")
28477            .poll_timeout(Duration::from_millis(10))
28478            .on_worker_heartbeat(move |observation| {
28479                observed
28480                    .lock()
28481                    .expect("heartbeat observations")
28482                    .push(observation.clone());
28483            });
28484
28485        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
28486            Ok(Value::Null)
28487        });
28488        let acknowledged = Arc::clone(&observations);
28489        worker
28490            .run_until(async move {
28491                tokio::time::timeout(Duration::from_secs(2), async move {
28492                    loop {
28493                        if !acknowledged
28494                            .lock()
28495                            .expect("heartbeat observations")
28496                            .is_empty()
28497                        {
28498                            break;
28499                        }
28500                        tokio::time::sleep(Duration::from_millis(1)).await;
28501                    }
28502                })
28503                .await
28504                .expect("heartbeat acknowledgement within timeout");
28505            })
28506            .await
28507            .expect("run worker");
28508
28509        let observations = observations.lock().expect("heartbeat observations");
28510        let first = observations.first().expect("heartbeat acknowledgement");
28511        assert_eq!(first.worker_id, "observed-heartbeat-worker");
28512        assert_eq!(first.task_queue, "rust-workers");
28513        assert!(first.acknowledged_at_unix_millis > 0);
28514        assert_eq!(first.acknowledgement, json!({}));
28515    }
28516
28517    #[tokio::test]
28518    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
28519        let server = MockWorkerServer::delayed_heartbeat_worker();
28520        let client = Client::builder(server.base_url())
28521            .timeout(Duration::from_secs(3))
28522            .build()
28523            .expect("client");
28524        let observations = Arc::new(Mutex::new(Vec::new()));
28525        let observed = Arc::clone(&observations);
28526        let mut worker = Worker::new(client, "rust-snapshot-workers")
28527            .worker_id("rust-snapshot-worker")
28528            .poll_timeout(Duration::from_millis(10))
28529            .on_worker_heartbeat(move |observation| {
28530                observed
28531                    .lock()
28532                    .expect("heartbeat observations")
28533                    .push(observation.clone());
28534            });
28535
28536        worker.register_workflow("snapshot", |ctx, _input| async move {
28537            ctx.wait_signal("finish").await?;
28538            Ok(json!({"status": "finished"}))
28539        });
28540        worker.register_query("snapshot", "current", |ctx, _args| async move {
28541            Ok(json!(ctx
28542                .signals("increment")
28543                .iter()
28544                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28545                .sum::<i64>()))
28546        });
28547        worker.register_activity("cancel-aware", |_ctx, _args| async move {
28548            Ok(json!({"late": "completion"}))
28549        });
28550
28551        worker
28552            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
28553            .await
28554            .expect("delayed heartbeat must allow a clean worker shutdown");
28555
28556        let observations = observations.lock().expect("heartbeat observations");
28557        assert!(
28558            observations.len() >= 3,
28559            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
28560        );
28561        assert!(
28562            observations.windows(2).all(|pair| {
28563                pair[1].acknowledged_at_unix_millis
28564                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28565                    >= 850
28566            }),
28567            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
28568        );
28569        drop(observations);
28570
28571        let heartbeat_times = server.request_times("/api/worker/heartbeat");
28572        let delayed_request_at = *heartbeat_times
28573            .get(1)
28574            .expect("intentionally delayed heartbeat request");
28575        let delay_window_start = delayed_request_at + Duration::from_millis(100);
28576        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
28577        for path in [
28578            "/api/worker/workflow-tasks/poll",
28579            "/api/worker/activity-tasks/poll",
28580            "/api/worker/query-tasks/poll",
28581        ] {
28582            assert!(
28583                server
28584                    .request_times(path)
28585                    .iter()
28586                    .any(|received_at| *received_at >= delay_window_start
28587                        && *received_at <= delay_window_end),
28588                "{path} must keep polling while a heartbeat acknowledgement is delayed"
28589            );
28590        }
28591        assert!(
28592            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
28593            "workflow work must be settled"
28594        );
28595        assert!(
28596            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
28597            "activity work must be settled"
28598        );
28599        assert!(
28600            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
28601            "query work must be settled"
28602        );
28603    }
28604
28605    #[tokio::test]
28606    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
28607        let server = MockWorkerServer::heartbeat_retry_worker();
28608        let client = Client::builder(server.base_url())
28609            .timeout(Duration::from_secs(2))
28610            .build()
28611            .expect("client");
28612        let observations = Arc::new(Mutex::new(Vec::new()));
28613        let observed = Arc::clone(&observations);
28614        let worker = Worker::new(client, "rust-workers")
28615            .worker_id("heartbeat-retry-worker")
28616            .retry_policy(WorkerRetryPolicy {
28617                max_retries: 1,
28618                initial_backoff: Duration::from_millis(300),
28619                max_backoff: Duration::from_millis(300),
28620            })
28621            .on_worker_heartbeat(move |observation| {
28622                observed
28623                    .lock()
28624                    .expect("heartbeat observations")
28625                    .push(observation.clone());
28626            });
28627
28628        worker
28629            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
28630            .await
28631            .expect("retryable heartbeat failure must remain bounded and recover");
28632
28633        let observations = observations.lock().expect("heartbeat observations");
28634        assert!(observations.len() >= 3, "heartbeat retry must recover");
28635        assert!(
28636            observations.windows(2).all(|pair| {
28637                pair[1]
28638                    .acknowledged_at_unix_millis
28639                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28640                    >= 850
28641            }),
28642            "a successful retry must start a fresh advertised cadence: {observations:?}"
28643        );
28644        assert_eq!(
28645            server.request_count("/api/worker/heartbeat"),
28646            observations.len() + 1,
28647            "one retryable failure must add exactly one bounded request"
28648        );
28649    }
28650
28651    #[tokio::test]
28652    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
28653        let server = MockWorkerServer::waiting_query_worker();
28654        let client = Client::builder(server.base_url())
28655            .timeout(Duration::from_secs(2))
28656            .build()
28657            .expect("client");
28658        let observations = Arc::new(Mutex::new(Vec::new()));
28659        let observed = Arc::clone(&observations);
28660        let mut worker = Worker::new(client, "rust-snapshot-workers")
28661            .worker_id("rust-snapshot-worker")
28662            .poll_timeout(Duration::from_millis(10))
28663            .on_worker_heartbeat(move |observation| {
28664                observed
28665                    .lock()
28666                    .expect("heartbeat observations")
28667                    .push(observation.clone());
28668            });
28669
28670        worker.register_workflow("snapshot", |ctx, _input| async move {
28671            ctx.wait_signal("finish").await?;
28672            Ok(json!({"status": "finished"}))
28673        });
28674        worker.register_query("snapshot", "current", |ctx, _args| async move {
28675            let current = ctx
28676                .signals("increment")
28677                .iter()
28678                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28679                .sum::<i64>();
28680            Ok(json!(current))
28681        });
28682        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
28683        worker
28684            .declare_workflow_signals("snapshot", &["finish"])
28685            .expect("declare finish signal");
28686
28687        worker
28688            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
28689            .await
28690            .expect("pending workflow and query poller must remain live until shutdown");
28691
28692        assert!(
28693            observations.lock().expect("heartbeat observations").len() >= 4,
28694            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
28695        );
28696        assert!(
28697            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
28698            "workflow polling must continue after empty replay acknowledgements"
28699        );
28700        assert!(
28701            server.request_count("/api/worker/query-tasks/poll") >= 2,
28702            "query polling must continue after serving the current query"
28703        );
28704        assert_eq!(
28705            server.request_body("/api/worker/register")["capabilities"],
28706            json!([
28707                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
28708                DURABLE_SELECTION_CAPABILITY,
28709                MEMO_UPSERTS_CAPABILITY,
28710                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
28711                QUERY_TASKS_CAPABILITY,
28712                WORKFLOW_UPDATES_CAPABILITY,
28713                MESSAGE_STREAMS_CAPABILITY
28714            ])
28715        );
28716        assert_eq!(
28717            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
28718            json!({
28719                "queries": ["current"],
28720                "query_contracts": [{
28721                    "name": "current",
28722                    "parameters": [{
28723                        "name": "args", "position": 0, "required": false,
28724                        "variadic": true, "type": null, "allows_null": true,
28725                        "default_available": false, "default": null,
28726                    }],
28727                }],
28728                "signals": ["finish"],
28729                "signal_contracts": [{
28730                    "name": "finish",
28731                    "parameters": [{
28732                        "name": "args", "position": 0, "required": false,
28733                        "variadic": true, "type": null, "allows_null": true,
28734                        "default_available": false, "default": null,
28735                    }],
28736                }],
28737                "updates": ["replace"],
28738                "update_contracts": [{
28739                    "name": "replace",
28740                    "parameters": [{
28741                        "name": "args", "position": 0, "required": false,
28742                        "variadic": true, "type": null, "allows_null": true,
28743                        "default_available": false, "default": null,
28744                    }],
28745                }],
28746                "update_validators": [],
28747            })
28748        );
28749
28750        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
28751        assert_eq!(
28752            opened["commands"],
28753            json!([{
28754                "type": "open_signal_wait",
28755                "signal_name": "finish",
28756            }])
28757        );
28758
28759        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
28760            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
28761            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
28762            let failure = server.request_body(&fail_path);
28763            assert_eq!(
28764                failure["failure"]["type"],
28765                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
28766            );
28767            assert_eq!(server.request_count(&completion_path), 0);
28768        }
28769
28770        let query_completion =
28771            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
28772        assert_eq!(query_completion["result"], json!(8));
28773
28774        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
28775        assert_eq!(
28776            server.request_count(terminal_path),
28777            1,
28778            "the matching signal must settle the workflow exactly once"
28779        );
28780        let terminal = server.request_body(terminal_path);
28781        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
28782        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
28783        assert_eq!(
28784            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
28785                .expect("terminal workflow result"),
28786            json!({"status": "finished"})
28787        );
28788    }
28789
28790    #[tokio::test]
28791    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
28792        let server = MockWorkerServer::transient_worker_failures();
28793        let client = Client::builder(server.base_url())
28794            .timeout(Duration::from_secs(2))
28795            .build()
28796            .expect("client");
28797        let mut worker = Worker::new(client, "rust-workers")
28798            .worker_id("retry-worker")
28799            .poll_timeout(Duration::from_millis(10))
28800            .retry_policy(WorkerRetryPolicy {
28801                max_retries: 2,
28802                initial_backoff: Duration::from_millis(1),
28803                max_backoff: Duration::from_millis(1),
28804            });
28805        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28806        worker.register_activity(
28807            "counter.activity",
28808            |_ctx, _input| async move { Ok(Value::Null) },
28809        );
28810        worker.register_query(
28811            "counter",
28812            "current",
28813            |_ctx, _args| async move { Ok(json!(8)) },
28814        );
28815
28816        worker
28817            .run_until(tokio::time::sleep(Duration::from_millis(75)))
28818            .await
28819            .expect("transient failures must not stop the worker");
28820
28821        for path in [
28822            "/api/worker/heartbeat",
28823            "/api/worker/workflow-tasks/poll",
28824            "/api/worker/activity-tasks/poll",
28825            "/api/worker/query-tasks/poll",
28826        ] {
28827            assert!(
28828                server.request_count(path) >= 2,
28829                "{path} must continue after its transient failure"
28830            );
28831        }
28832    }
28833
28834    #[tokio::test]
28835    async fn worker_continues_after_long_poll_capacity_backpressure() {
28836        let server = MockWorkerServer::capacity_limited_activity_poll();
28837        let client = Client::builder(server.base_url())
28838            .timeout(Duration::from_secs(2))
28839            .build()
28840            .expect("client");
28841        let mut worker = Worker::new(client, "rust-workers")
28842            .worker_id("capacity-worker")
28843            .poll_timeout(Duration::from_millis(10))
28844            .retry_policy(WorkerRetryPolicy {
28845                max_retries: 0,
28846                initial_backoff: Duration::from_millis(1),
28847                max_backoff: Duration::from_millis(1),
28848            });
28849        worker.register_activity("capacity.activity", |_ctx, _input| async move {
28850            Ok(json!({"handled": true}))
28851        });
28852
28853        worker
28854            .run_until(tokio::time::sleep(Duration::from_millis(50)))
28855            .await
28856            .expect("capacity backpressure must not stop the worker");
28857
28858        assert!(
28859            server.request_count("/api/worker/activity-tasks/poll") >= 2,
28860            "the activity poller must continue after capacity backpressure"
28861        );
28862        assert_eq!(
28863            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
28864            1,
28865            "the worker must complete work returned after capacity recovers"
28866        );
28867    }
28868
28869    #[test]
28870    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
28871        let capacity = Error::Http {
28872            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28873            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
28874        };
28875        assert_eq!(
28876            worker_poll_capacity_retry_after(&capacity),
28877            Some(Duration::from_secs(3))
28878        );
28879
28880        let rejected_capacity = Error::Http {
28881            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28882            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
28883        };
28884        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
28885        assert!(!worker_operation_is_retryable(&rejected_capacity));
28886
28887        let ordinary_rate_limit = Error::Http {
28888            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28889            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
28890                .to_string(),
28891        };
28892        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
28893        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
28894    }
28895
28896    #[tokio::test]
28897    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
28898        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28899            poll_failures_per_path: 8,
28900            heartbeat_failures: 8,
28901            ..MockWorkerBehavior::default()
28902        });
28903        let client = Client::builder(server.base_url())
28904            .timeout(Duration::from_secs(2))
28905            .build()
28906            .expect("client");
28907        let acknowledgements = Arc::new(AtomicUsize::new(0));
28908        let observed = Arc::clone(&acknowledgements);
28909        let mut worker = Worker::new(client, "rust-workers")
28910            .recover_transient_outages(true)
28911            .poll_timeout(Duration::from_millis(10))
28912            .retry_policy(WorkerRetryPolicy {
28913                max_retries: 2,
28914                initial_backoff: Duration::from_millis(2),
28915                max_backoff: Duration::from_millis(5),
28916            })
28917            .on_worker_heartbeat(move |_| {
28918                observed.fetch_add(1, Ordering::SeqCst);
28919            });
28920        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28921        worker.register_activity(
28922            "counter.activity",
28923            |_ctx, _input| async move { Ok(Value::Null) },
28924        );
28925        worker.register_query("counter", "current", |_ctx, _args| async move {
28926            Ok(Value::Null)
28927        });
28928
28929        worker
28930            .run_until(tokio::time::sleep(Duration::from_millis(500)))
28931            .await
28932            .expect("a recoverable outage must not stop the service worker");
28933
28934        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
28935        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
28936        for path in [
28937            "/api/worker/workflow-tasks/poll",
28938            "/api/worker/activity-tasks/poll",
28939            "/api/worker/query-tasks/poll",
28940        ] {
28941            let bodies = server.request_bodies(path);
28942            assert!(bodies.len() >= 10, "{path} must resume after recovery");
28943            let first = &bodies[0]["poll_request_id"];
28944            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
28945            for body in &bodies[..9] {
28946                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
28947            }
28948            assert_ne!(&bodies[9]["poll_request_id"], first);
28949            let times = server.request_times(path);
28950            for pair in times[..9].windows(2) {
28951                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
28952            }
28953        }
28954    }
28955
28956    #[tokio::test]
28957    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
28958        for heartbeat_outage in [false, true] {
28959            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28960                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
28961                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
28962                ..MockWorkerBehavior::default()
28963            });
28964            let client = Client::builder(server.base_url()).build().expect("client");
28965            let mut worker = Worker::new(client, "rust-workers")
28966                .recover_transient_outages(true)
28967                .retry_policy(WorkerRetryPolicy {
28968                    max_retries: 1,
28969                    initial_backoff: Duration::from_secs(5),
28970                    max_backoff: Duration::from_secs(5),
28971                });
28972            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28973            let started = Instant::now();
28974            worker
28975                .run_until(tokio::time::sleep(Duration::from_millis(200)))
28976                .await
28977                .expect("shutdown during an outage is a normal stop");
28978            assert!(started.elapsed() < Duration::from_secs(1));
28979            let path = if heartbeat_outage {
28980                "/api/worker/heartbeat"
28981            } else {
28982                "/api/worker/workflow-tasks/poll"
28983            };
28984            assert_eq!(server.request_count(path), 1);
28985            assert_eq!(
28986                server.request_count("/api/worker/registrations/mock-worker"),
28987                1
28988            );
28989        }
28990    }
28991
28992    #[tokio::test]
28993    async fn worker_outage_recovery_keeps_run_once_bounded() {
28994        let server = MockWorkerServer::unavailable_polls();
28995        let client = Client::builder(server.base_url()).build().expect("client");
28996        let mut worker = Worker::new(client, "rust-workers")
28997            .recover_transient_outages(true)
28998            .retry_policy(WorkerRetryPolicy {
28999                max_retries: 2,
29000                initial_backoff: Duration::from_millis(1),
29001                max_backoff: Duration::from_millis(1),
29002            });
29003        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29004        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
29005        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
29006    }
29007
29008    #[tokio::test]
29009    async fn worker_outage_recovery_respects_disabled_retries() {
29010        let server = MockWorkerServer::unavailable_polls();
29011        let client = Client::builder(server.base_url()).build().expect("client");
29012        let mut worker = Worker::new(client, "rust-workers")
29013            .recover_transient_outages(true)
29014            .retry_policy(WorkerRetryPolicy {
29015                max_retries: 0,
29016                ..WorkerRetryPolicy::default()
29017            });
29018        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29019        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
29020        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29021    }
29022
29023    #[tokio::test]
29024    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
29025        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29026            heartbeat_failures: usize::MAX,
29027            unauthorized_polls: true,
29028            ..MockWorkerBehavior::default()
29029        });
29030        let client = Client::builder(server.base_url()).build().expect("client");
29031        let mut worker = Worker::new(client, "rust-workers")
29032            .recover_transient_outages(true)
29033            .retry_policy(WorkerRetryPolicy {
29034                max_retries: 1,
29035                initial_backoff: Duration::from_secs(5),
29036                max_backoff: Duration::from_secs(5),
29037            });
29038        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29039        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
29040            .await
29041            .expect("fatal poll errors must interrupt heartbeat recovery")
29042            .expect_err("authentication failure is terminal");
29043        assert!(
29044            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
29045        );
29046        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29047    }
29048
29049    #[tokio::test]
29050    async fn worker_bounds_transport_retries() {
29051        let server = MockWorkerServer::unavailable_polls();
29052        let client = Client::builder(server.base_url())
29053            .timeout(Duration::from_secs(2))
29054            .build()
29055            .expect("client");
29056        let mut worker = Worker::new(client, "rust-workers")
29057            .worker_id("bounded-retry-worker")
29058            .poll_timeout(Duration::from_millis(10))
29059            .retry_policy(WorkerRetryPolicy {
29060                max_retries: 2,
29061                initial_backoff: Duration::from_millis(1),
29062                max_backoff: Duration::from_millis(1),
29063            });
29064        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29065
29066        let error = worker.run().await.expect_err("retry bound must terminate");
29067        assert!(matches!(error, Error::Transport(_)));
29068        assert_eq!(
29069            server.request_count("/api/worker/workflow-tasks/poll"),
29070            3,
29071            "one initial request plus exactly two retries"
29072        );
29073    }
29074
29075    #[tokio::test]
29076    async fn worker_retry_policy_can_disable_poll_retries() {
29077        let server = MockWorkerServer::unavailable_polls();
29078        let client = Client::builder(server.base_url())
29079            .timeout(Duration::from_secs(2))
29080            .build()
29081            .expect("client");
29082        let mut worker = Worker::new(client, "rust-workers")
29083            .worker_id("no-retry-worker")
29084            .poll_timeout(Duration::from_millis(10))
29085            .retry_policy(WorkerRetryPolicy {
29086                max_retries: 0,
29087                initial_backoff: Duration::from_millis(1),
29088                max_backoff: Duration::from_millis(1),
29089            });
29090        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29091
29092        let error = worker
29093            .run_once()
29094            .await
29095            .expect_err("disabled retries must return the first transport failure");
29096        assert!(matches!(error, Error::Transport(_)));
29097        assert_eq!(
29098            server.request_count("/api/worker/workflow-tasks/poll"),
29099            1,
29100            "max_retries=0 must send only the initial request"
29101        );
29102    }
29103
29104    #[tokio::test]
29105    async fn worker_does_not_retry_authentication_failures() {
29106        let server = MockWorkerServer::unauthorized_polls();
29107        let client = Client::builder(server.base_url())
29108            .timeout(Duration::from_secs(2))
29109            .build()
29110            .expect("client");
29111        let mut worker = Worker::new(client, "rust-workers")
29112            .worker_id("unauthorized-worker")
29113            .recover_transient_outages(true)
29114            .poll_timeout(Duration::from_millis(10));
29115        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29116
29117        let error = worker
29118            .run()
29119            .await
29120            .expect_err("authentication must terminate");
29121        let Error::Http { status, body } = error else {
29122            panic!("expected stable HTTP authentication error");
29123        };
29124        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29125        assert!(body.contains("authentication_failed"));
29126        assert_eq!(
29127            server.request_count("/api/worker/workflow-tasks/poll"),
29128            1,
29129            "authentication failures must not be retried"
29130        );
29131    }
29132
29133    #[test]
29134    fn duplicate_registration_keeps_the_original_workflow() {
29135        let client = Client::new("http://127.0.0.1:9").expect("client");
29136        let mut worker = Worker::new(client, "registration-tests");
29137        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29138        let original = Arc::clone(&worker.workflows["same"].execute);
29139        worker
29140            .set_workflow_definition_sources("same", &["first workflow source"])
29141            .expect("source identity");
29142        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29143        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29144        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29145        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29146    }
29147
29148    #[test]
29149    fn duplicate_registration_keeps_the_original_activity() {
29150        let client = Client::new("http://127.0.0.1:9").expect("client");
29151        let mut worker = Worker::new(client, "registration-tests");
29152        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29153        let original = Arc::clone(&worker.activities["same"]);
29154        worker.register_activity_avro_value("same", |_ctx, _input| async {
29155            Ok(AvroValue::String("second".into()))
29156        });
29157        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29158    }
29159
29160    #[test]
29161    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29162        let client = Client::new("http://127.0.0.1:9").expect("client");
29163        let mut worker = Worker::new(client, "registration-tests");
29164        worker.register_query("orders", "same", |_ctx, _input| async {
29165            Ok(json!("first"))
29166        });
29167        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29168            panic!("snapshot query");
29169        };
29170        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29171            Ok(json!("second"))
29172        });
29173        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29174            panic!("duplicate replaced the query adapter");
29175        };
29176        assert!(Arc::ptr_eq(&original, retained));
29177        worker.register_update("orders", "same", |_ctx, _input| async {
29178            Ok(json!("first"))
29179        });
29180        let original = Arc::clone(&worker.updates["orders"]["same"]);
29181        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29182            Ok(AvroValue::Null)
29183        });
29184        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29185    }
29186
29187    #[tokio::test]
29188    async fn duplicate_registration_fails_before_server_contact() {
29189        let server = MockWorkerServer::start();
29190        let client = Client::builder(server.base_url()).build().expect("client");
29191        let mut worker =
29192            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29193        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29194        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29195        let error = worker
29196            .run_once()
29197            .await
29198            .expect_err("ambiguous worker must not poll");
29199        assert!(
29200            error.to_string().contains("duplicate_registration"),
29201            "{error}"
29202        );
29203        assert!(server.requests.lock().expect("requests").is_empty());
29204    }
29205
29206    #[derive(Clone, Debug)]
29207    struct CapturedRequest {
29208        headers: String,
29209        method: String,
29210        path: String,
29211        authorization: Option<String>,
29212        namespace: Option<String>,
29213        worker_protocol: Option<String>,
29214        control_protocol: Option<String>,
29215        body: String,
29216        received_at: Instant,
29217    }
29218
29219    struct MockWorkerServer {
29220        addr: SocketAddr,
29221        stop: Arc<AtomicBool>,
29222        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29223        thread: Option<thread::JoinHandle<()>>,
29224    }
29225
29226    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29227
29228    #[derive(Clone, Copy, Default)]
29229    struct MockWorkerBehavior {
29230        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29231        request_override: Option<RequestOverride>,
29232        storage_refusals: usize,
29233        storage_path: Option<&'static str>,
29234        storage_unavailable: bool,
29235        storage_mid_poll: bool,
29236        storage_activity: bool,
29237        storage_query: bool,
29238        storage_wrong_poll_id: bool,
29239        reject_query_protocol: bool,
29240        reject_query_completion: bool,
29241        waiting_query_worker: bool,
29242        decline_registration: bool,
29243        complete_named_signal: bool,
29244        poll_failures_per_path: usize,
29245        long_poll_capacity_responses_per_path: usize,
29246        heartbeat_failures: usize,
29247        heartbeat_failure_request: Option<usize>,
29248        delayed_heartbeat_request: Option<usize>,
29249        heartbeat_response_delay: Duration,
29250        concurrent_requests: bool,
29251        unauthorized_polls: bool,
29252        reject_registration: bool,
29253        reject_registration_protocol: bool,
29254        reject_deregistration: bool,
29255        reject_deregistration_protocol: bool,
29256        cancelled_activity: bool,
29257        draining_polls: bool,
29258        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29259        workflow_completion_status: Option<&'static str>,
29260        workflow_completion_body: Option<&'static str>,
29261    }
29262
29263    impl MockWorkerServer {
29264        fn start() -> Self {
29265            Self::start_with_behavior(MockWorkerBehavior::default())
29266        }
29267
29268        fn reject_query_protocol() -> Self {
29269            Self::start_with_behavior(MockWorkerBehavior {
29270                reject_query_protocol: true,
29271                ..MockWorkerBehavior::default()
29272            })
29273        }
29274
29275        fn reject_query_completion() -> Self {
29276            Self::start_with_behavior(MockWorkerBehavior {
29277                reject_query_completion: true,
29278                ..MockWorkerBehavior::default()
29279            })
29280        }
29281
29282        fn waiting_query_worker() -> Self {
29283            Self::start_with_behavior(MockWorkerBehavior {
29284                waiting_query_worker: true,
29285                complete_named_signal: true,
29286                ..MockWorkerBehavior::default()
29287            })
29288        }
29289
29290        fn transient_worker_failures() -> Self {
29291            Self::start_with_behavior(MockWorkerBehavior {
29292                poll_failures_per_path: 1,
29293                heartbeat_failures: 1,
29294                ..MockWorkerBehavior::default()
29295            })
29296        }
29297
29298        fn consecutive_poll_failures(count: usize) -> Self {
29299            Self::start_with_behavior(MockWorkerBehavior {
29300                poll_failures_per_path: count,
29301                ..MockWorkerBehavior::default()
29302            })
29303        }
29304
29305        fn capacity_limited_activity_poll() -> Self {
29306            Self::start_with_behavior(MockWorkerBehavior {
29307                long_poll_capacity_responses_per_path: 1,
29308                ..MockWorkerBehavior::default()
29309            })
29310        }
29311
29312        fn delayed_heartbeat_worker() -> Self {
29313            Self::start_with_behavior(MockWorkerBehavior {
29314                waiting_query_worker: true,
29315                delayed_heartbeat_request: Some(2),
29316                heartbeat_response_delay: Duration::from_millis(1_500),
29317                concurrent_requests: true,
29318                cancelled_activity: true,
29319                ..MockWorkerBehavior::default()
29320            })
29321        }
29322
29323        fn heartbeat_retry_worker() -> Self {
29324            Self::start_with_behavior(MockWorkerBehavior {
29325                waiting_query_worker: true,
29326                heartbeat_failure_request: Some(2),
29327                concurrent_requests: true,
29328                ..MockWorkerBehavior::default()
29329            })
29330        }
29331
29332        fn unavailable_polls() -> Self {
29333            Self::start_with_behavior(MockWorkerBehavior {
29334                poll_failures_per_path: usize::MAX,
29335                ..MockWorkerBehavior::default()
29336            })
29337        }
29338
29339        fn unauthorized_polls() -> Self {
29340            Self::start_with_behavior(MockWorkerBehavior {
29341                unauthorized_polls: true,
29342                ..MockWorkerBehavior::default()
29343            })
29344        }
29345
29346        fn rejected_registration() -> Self {
29347            Self::start_with_behavior(MockWorkerBehavior {
29348                reject_registration: true,
29349                ..MockWorkerBehavior::default()
29350            })
29351        }
29352
29353        fn rejected_registration_protocol() -> Self {
29354            Self::start_with_behavior(MockWorkerBehavior {
29355                reject_registration_protocol: true,
29356                ..MockWorkerBehavior::default()
29357            })
29358        }
29359
29360        fn declined_registration() -> Self {
29361            Self::start_with_behavior(MockWorkerBehavior {
29362                decline_registration: true,
29363                ..MockWorkerBehavior::default()
29364            })
29365        }
29366
29367        fn rejected_deregistration() -> Self {
29368            Self::start_with_behavior(MockWorkerBehavior {
29369                reject_deregistration: true,
29370                ..MockWorkerBehavior::default()
29371            })
29372        }
29373
29374        fn rejected_deregistration_protocol() -> Self {
29375            Self::start_with_behavior(MockWorkerBehavior {
29376                reject_deregistration_protocol: true,
29377                ..MockWorkerBehavior::default()
29378            })
29379        }
29380
29381        fn unauthorized_polls_and_rejected_deregistration() -> Self {
29382            Self::start_with_behavior(MockWorkerBehavior {
29383                unauthorized_polls: true,
29384                reject_deregistration: true,
29385                ..MockWorkerBehavior::default()
29386            })
29387        }
29388
29389        fn cancelled_activity() -> Self {
29390            Self::start_with_behavior(MockWorkerBehavior {
29391                cancelled_activity: true,
29392                ..MockWorkerBehavior::default()
29393            })
29394        }
29395
29396        fn draining_polls() -> Self {
29397            Self::start_with_behavior(MockWorkerBehavior {
29398                draining_polls: true,
29399                ..MockWorkerBehavior::default()
29400            })
29401        }
29402
29403        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
29404            Self::start_with_behavior(MockWorkerBehavior {
29405                invalid_task_payload_codec: Some(codec),
29406                ..MockWorkerBehavior::default()
29407            })
29408        }
29409
29410        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
29411            Self::start_with_behavior(MockWorkerBehavior {
29412                workflow_completion_status: Some(status),
29413                workflow_completion_body: Some(body),
29414                ..MockWorkerBehavior::default()
29415            })
29416        }
29417
29418        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
29419            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
29420            listener
29421                .set_nonblocking(true)
29422                .expect("configure mock listener");
29423            let addr = listener.local_addr().expect("mock server address");
29424            let stop = Arc::new(AtomicBool::new(false));
29425            let server_stop = Arc::clone(&stop);
29426            let requests = Arc::new(Mutex::new(Vec::new()));
29427            let server_requests = Arc::clone(&requests);
29428            let thread = thread::spawn(move || {
29429                let mut request_threads = Vec::new();
29430                while !server_stop.load(Ordering::SeqCst) {
29431                    match listener.accept() {
29432                        Ok((mut stream, _)) => {
29433                            if behavior.concurrent_requests {
29434                                let requests = Arc::clone(&server_requests);
29435                                request_threads.push(thread::spawn(move || {
29436                                    handle_mock_worker_request(&mut stream, &requests, behavior)
29437                                }));
29438                            } else {
29439                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
29440                            }
29441                        }
29442                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
29443                            let mut index = 0;
29444                            while index < request_threads.len() {
29445                                if request_threads[index].is_finished() {
29446                                    request_threads
29447                                        .swap_remove(index)
29448                                        .join()
29449                                        .expect("join mock request");
29450                                } else {
29451                                    index += 1;
29452                                }
29453                            }
29454                            thread::sleep(Duration::from_millis(5));
29455                        }
29456                        Err(_) => break,
29457                    }
29458                }
29459                for request_thread in request_threads {
29460                    request_thread.join().expect("join mock request");
29461                }
29462            });
29463
29464            Self {
29465                addr,
29466                stop,
29467                requests,
29468                thread: Some(thread),
29469            }
29470        }
29471
29472        fn base_url(&self) -> String {
29473            format!("http://{}", self.addr)
29474        }
29475
29476        fn worker_protocol_for(&self, path: &str) -> Option<String> {
29477            self.requests
29478                .lock()
29479                .expect("captured requests")
29480                .iter()
29481                .find(|request| request.path == path)
29482                .and_then(|request| request.worker_protocol.clone())
29483        }
29484
29485        fn control_protocol_for(&self, path: &str) -> Option<String> {
29486            self.requests
29487                .lock()
29488                .expect("captured requests")
29489                .iter()
29490                .find(|request| request.path == path)
29491                .and_then(|request| request.control_protocol.clone())
29492        }
29493
29494        fn method_for(&self, path: &str) -> Option<String> {
29495            self.requests
29496                .lock()
29497                .expect("captured requests")
29498                .iter()
29499                .find(|request| request.path == path)
29500                .map(|request| request.method.clone())
29501        }
29502
29503        fn authorization_for(&self, path: &str) -> Option<String> {
29504            self.requests
29505                .lock()
29506                .expect("captured requests")
29507                .iter()
29508                .find(|request| request.path == path)
29509                .and_then(|request| request.authorization.clone())
29510        }
29511
29512        fn namespace_for(&self, path: &str) -> Option<String> {
29513            self.requests
29514                .lock()
29515                .expect("captured requests")
29516                .iter()
29517                .find(|request| request.path == path)
29518                .and_then(|request| request.namespace.clone())
29519        }
29520
29521        fn request_count(&self, path: &str) -> usize {
29522            self.requests
29523                .lock()
29524                .expect("captured requests")
29525                .iter()
29526                .filter(|request| request.path == path)
29527                .count()
29528        }
29529
29530        fn captured_paths(&self) -> Vec<String> {
29531            self.requests
29532                .lock()
29533                .expect("captured requests")
29534                .iter()
29535                .map(|request| request.path.clone())
29536                .collect()
29537        }
29538
29539        fn request_times(&self, path: &str) -> Vec<Instant> {
29540            self.requests
29541                .lock()
29542                .expect("captured requests")
29543                .iter()
29544                .filter(|request| request.path == path)
29545                .map(|request| request.received_at)
29546                .collect()
29547        }
29548
29549        fn request_body(&self, path: &str) -> Value {
29550            let requests = self.requests.lock().expect("captured requests");
29551            let body = &requests
29552                .iter()
29553                .find(|request| request.path == path)
29554                .unwrap_or_else(|| panic!("missing request for {path}"))
29555                .body;
29556            serde_json::from_str(body).unwrap_or_else(|error| {
29557                panic!("invalid JSON request body for {path}: {error}: {body:?}")
29558            })
29559        }
29560
29561        fn request_bodies(&self, path: &str) -> Vec<Value> {
29562            self.requests
29563                .lock()
29564                .expect("captured requests")
29565                .iter()
29566                .filter(|request| request.path == path)
29567                .map(|request| {
29568                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
29569                        panic!(
29570                            "invalid JSON request body for {path}: {error}: {:?}",
29571                            request.body
29572                        )
29573                    })
29574                })
29575                .collect()
29576        }
29577    }
29578
29579    impl Drop for MockWorkerServer {
29580        fn drop(&mut self) {
29581            self.stop.store(true, Ordering::SeqCst);
29582            let _ = TcpStream::connect(self.addr);
29583
29584            if let Some(thread) = self.thread.take() {
29585                thread.join().expect("join mock server");
29586            }
29587        }
29588    }
29589
29590    fn handle_mock_worker_request(
29591        stream: &mut TcpStream,
29592        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
29593        behavior: MockWorkerBehavior,
29594    ) {
29595        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
29596        let mut buffer = [0_u8; 8192];
29597        let mut request = Vec::new();
29598
29599        loop {
29600            match stream.read(&mut buffer) {
29601                Ok(0) => break,
29602                Ok(read) => {
29603                    request.extend_from_slice(&buffer[..read]);
29604                    if mock_request_is_complete(&request) {
29605                        break;
29606                    }
29607                }
29608                Err(error)
29609                    if matches!(
29610                        error.kind(),
29611                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
29612                    ) =>
29613                {
29614                    break;
29615                }
29616                Err(_) => return,
29617            }
29618        }
29619
29620        let request = String::from_utf8_lossy(&request);
29621        let body = request
29622            .split_once("\r\n\r\n")
29623            .map(|(_, body)| body)
29624            .unwrap_or_default();
29625        let path = request
29626            .lines()
29627            .next()
29628            .and_then(|line| line.split_whitespace().nth(1))
29629            .unwrap_or_default();
29630        let method = request
29631            .lines()
29632            .next()
29633            .and_then(|line| line.split_whitespace().next())
29634            .unwrap_or_default();
29635        let authorization = request.lines().find_map(|line| {
29636            let (name, value) = line.split_once(':')?;
29637            name.eq_ignore_ascii_case("Authorization")
29638                .then(|| value.trim().to_string())
29639        });
29640        let namespace = request.lines().find_map(|line| {
29641            let (name, value) = line.split_once(':')?;
29642            name.eq_ignore_ascii_case("X-Namespace")
29643                .then(|| value.trim().to_string())
29644        });
29645        let worker_protocol = request.lines().find_map(|line| {
29646            let (name, value) = line.split_once(':')?;
29647            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
29648                .then(|| value.trim().to_string())
29649        });
29650        let control_protocol = request.lines().find_map(|line| {
29651            let (name, value) = line.split_once(':')?;
29652            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
29653                .then(|| value.trim().to_string())
29654        });
29655        let request_number = {
29656            let mut requests = requests.lock().expect("captured requests");
29657            requests.push(CapturedRequest {
29658                headers: request
29659                    .split_once("\r\n\r\n")
29660                    .map_or("", |(headers, _)| headers)
29661                    .to_owned(),
29662                method: method.to_string(),
29663                path: path.to_string(),
29664                authorization,
29665                namespace,
29666                worker_protocol: worker_protocol.clone(),
29667                control_protocol,
29668                body: body.to_string(),
29669                received_at: Instant::now(),
29670            });
29671            requests
29672                .iter()
29673                .filter(|request| request.path == path)
29674                .count()
29675        };
29676
29677        if let Some(response) = behavior
29678            .request_override
29679            .and_then(|handler| handler(path, body, request_number))
29680        {
29681            write_mock_response(stream, response.0, &response.1);
29682            return;
29683        }
29684        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
29685            write_mock_response(stream, response.0, &response.1);
29686            return;
29687        }
29688        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
29689            return;
29690        }
29691        let pressure_path = behavior
29692            .storage_path
29693            .is_some_and(|part| path.contains(part));
29694        let prior_failures = if path.ends_with("/poll") {
29695            behavior.poll_failures_per_path
29696        } else {
29697            0
29698        };
29699        if pressure_path
29700            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
29701        {
29702            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
29703            let poll_id = path
29704                .ends_with("/poll")
29705                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
29706            let mut refusal = storage_refusal(
29707                poll_id,
29708                behavior.storage_unavailable,
29709                behavior.storage_mid_poll,
29710            );
29711            if behavior.storage_wrong_poll_id {
29712                refusal["poll_request_id"] = json!("wrong-poll");
29713            }
29714            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
29715            return;
29716        }
29717        if path.contains("/storage-task/")
29718            || path.contains("/storage-activity/")
29719            || path.contains("/storage-query/")
29720        {
29721            write_mock_response(stream, "200 OK", "{}");
29722            return;
29723        }
29724        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
29725            write_mock_response(stream, "200 OK", &json!({"task":{
29726                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
29727                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
29728                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29729                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29730                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
29731            }}).to_string());
29732            return;
29733        }
29734        if behavior.storage_activity
29735            && path == "/api/worker/activity-tasks/poll"
29736            && request_number == 1
29737        {
29738            write_mock_response(stream, "200 OK", &json!({"task":{
29739                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
29740                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29741                "attempt_number":7, "lease_owner":"storage-worker"
29742            }}).to_string());
29743            return;
29744        }
29745
29746        if path == "/api/worker/register" {
29747            if behavior.reject_registration_protocol {
29748                write_mock_response(
29749                    stream,
29750                    "400 Bad Request",
29751                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
29752                );
29753                return;
29754            }
29755            if behavior.reject_registration {
29756                write_mock_response(
29757                    stream,
29758                    "503 Service Unavailable",
29759                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
29760                );
29761                return;
29762            }
29763        }
29764
29765        if path.starts_with("/api/worker/registrations/") {
29766            if behavior.reject_deregistration_protocol {
29767                write_mock_response(
29768                    stream,
29769                    "400 Bad Request",
29770                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
29771                );
29772            } else if behavior.reject_deregistration {
29773                write_mock_response(
29774                    stream,
29775                    "403 Forbidden",
29776                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
29777                );
29778            } else {
29779                write_mock_response(
29780                    stream,
29781                    "200 OK",
29782                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
29783                );
29784            }
29785            return;
29786        }
29787
29788        let is_poll = matches!(
29789            path,
29790            "/api/worker/workflow-tasks/poll"
29791                | "/api/worker/activity-tasks/poll"
29792                | "/api/worker/query-tasks/poll"
29793        );
29794        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
29795            write_mock_response(
29796                stream,
29797                "429 Too Many Requests",
29798                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
29799            );
29800            return;
29801        }
29802        if is_poll && request_number <= behavior.poll_failures_per_path {
29803            return;
29804        }
29805        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
29806            return;
29807        }
29808        if path == "/api/worker/heartbeat"
29809            && behavior.heartbeat_failure_request == Some(request_number)
29810        {
29811            return;
29812        }
29813        if path == "/api/worker/heartbeat"
29814            && behavior.delayed_heartbeat_request == Some(request_number)
29815        {
29816            thread::sleep(behavior.heartbeat_response_delay);
29817        }
29818        if behavior.unauthorized_polls && is_poll {
29819            write_mock_response(
29820                stream,
29821                "401 Unauthorized",
29822                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
29823            );
29824            return;
29825        }
29826        if behavior.draining_polls && is_poll {
29827            write_mock_response(
29828                stream,
29829                "409 Conflict",
29830                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
29831            );
29832            return;
29833        }
29834
29835        if let Some(codec_case) = behavior.invalid_task_payload_codec {
29836            if is_poll && request_number == 1 {
29837                let mut task = match path {
29838                    "/api/worker/workflow-tasks/poll" => json!({
29839                        "task_id": "codec-workflow",
29840                        "workflow_type": "codec.workflow",
29841                        "payload_codec": DEFAULT_CODEC,
29842                        "workflow_task_attempt": 1,
29843                        "lease_owner": "codec-worker"
29844                    }),
29845                    "/api/worker/activity-tasks/poll" => json!({
29846                        "task_id": "codec-activity",
29847                        "activity_attempt_id": "codec-activity-attempt",
29848                        "activity_type": "codec.activity",
29849                        "payload_codec": DEFAULT_CODEC,
29850                        "attempt_number": 1,
29851                        "lease_owner": "codec-worker"
29852                    }),
29853                    "/api/worker/query-tasks/poll" => json!({
29854                        "query_task_id": "codec-query",
29855                        "query_task_attempt": 1,
29856                        "workflow_type": "codec.workflow",
29857                        "query_name": "known",
29858                        "payload_codec": DEFAULT_CODEC,
29859                        "lease_owner": "codec-worker"
29860                    }),
29861                    _ => unreachable!("is_poll limits task codec probe paths"),
29862                };
29863                codec_case.apply(&mut task);
29864                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
29865                return;
29866            }
29867
29868            if matches!(
29869                path,
29870                "/api/worker/workflow-tasks/codec-workflow/fail"
29871                    | "/api/worker/activity-tasks/codec-activity/fail"
29872                    | "/api/worker/query-tasks/codec-query/fail"
29873            ) {
29874                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
29875                return;
29876            }
29877        }
29878
29879        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
29880            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
29881            let body = format!(
29882                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
29883            );
29884            write_mock_response(stream, "400 Bad Request", &body);
29885            return;
29886        }
29887
29888        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
29889        {
29890            write_mock_response(
29891                stream,
29892                "409 Conflict",
29893                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
29894            );
29895            return;
29896        }
29897
29898        if behavior.workflow_completion_status.is_some()
29899            && path == "/api/worker/workflow-tasks/poll"
29900            && request_number == 1
29901        {
29902            write_mock_response(
29903                stream,
29904                "200 OK",
29905                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"}}"#,
29906            );
29907            return;
29908        }
29909
29910        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
29911            if let (Some(status), Some(body)) = (
29912                behavior.workflow_completion_status,
29913                behavior.workflow_completion_body,
29914            ) {
29915                write_mock_response(stream, status, body);
29916                return;
29917            }
29918        }
29919
29920        if behavior.waiting_query_worker {
29921            if behavior.complete_named_signal
29922                && path == "/api/worker/workflow-tasks/poll"
29923                && request_number == 1
29924            {
29925                let body = json!({
29926                    "task": {
29927                        "task_id": "snapshot-open",
29928                        "workflow_id": "snapshot-1",
29929                        "run_id": "snapshot-run-1",
29930                        "workflow_type": "snapshot",
29931                        "payload_codec": DEFAULT_CODEC,
29932                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29933                            .expect("Avro workflow arguments"),
29934                        "history_events": [],
29935                        "workflow_task_attempt": 1,
29936                        "lease_owner": "rust-snapshot-worker"
29937                    }
29938                })
29939                .to_string();
29940                write_mock_response(stream, "200 OK", &body);
29941                return;
29942            }
29943
29944            let signal_request = request_number - usize::from(behavior.complete_named_signal);
29945            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
29946            if path == "/api/worker/workflow-tasks/poll"
29947                && signal_request >= 1
29948                && signal_request <= signal_request_limit
29949            {
29950                let finish = behavior.complete_named_signal && signal_request == 3;
29951                let amounts = if signal_request == 1 {
29952                    vec![3]
29953                } else {
29954                    vec![3, 5]
29955                };
29956                let task_id = if signal_request == 1 {
29957                    "snapshot-wait-3"
29958                } else if finish {
29959                    "snapshot-finish"
29960                } else {
29961                    "snapshot-wait-5"
29962                };
29963                let mut history_events = std::iter::once(json!({
29964                    "event_type": "SignalWaitOpened",
29965                    "payload": {"sequence": 1, "signal_name": "finish"}
29966                }))
29967                .chain(amounts.iter().enumerate().map(|(index, amount)| {
29968                    json!({
29969                        "event_type": "SignalReceived",
29970                        "payload": {
29971                            "signal_id": format!("increment-{amount}"),
29972                            "signal_name": "increment",
29973                            "workflow_sequence": index + 2,
29974                            "payload_codec": DEFAULT_CODEC,
29975                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29976                                .expect("Avro signal envelope")
29977                        }
29978                    })
29979                }))
29980                .collect::<Vec<_>>();
29981                let (resume_id, resume_name, resume_arguments) = if finish {
29982                    history_events.push(json!({
29983                        "event_type": "SignalReceived",
29984                        "payload": {
29985                            "signal_id": "finish",
29986                            "signal_name": "finish",
29987                            "workflow_sequence": 4,
29988                            "payload_codec": DEFAULT_CODEC,
29989                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29990                                .expect("Avro finish signal envelope")
29991                        }
29992                    }));
29993                    (
29994                        "finish".to_string(),
29995                        "finish".to_string(),
29996                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
29997                            .expect("Avro finish resume signal"),
29998                    )
29999                } else {
30000                    let amount = amounts.last().expect("amount");
30001                    (
30002                        format!("increment-{amount}"),
30003                        "increment".to_string(),
30004                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30005                            .expect("Avro increment resume signal"),
30006                    )
30007                };
30008                let body = json!({
30009                    "task": {
30010                        "task_id": task_id,
30011                        "workflow_id": "snapshot-1",
30012                        "run_id": "snapshot-run-1",
30013                        "workflow_type": "snapshot",
30014                        "payload_codec": DEFAULT_CODEC,
30015                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30016                            .expect("Avro workflow arguments"),
30017                        "history_events": history_events,
30018                        "workflow_task_attempt": 1,
30019                        "workflow_signal_id": resume_id,
30020                        "signal_name": resume_name,
30021                        "signal_arguments": resume_arguments,
30022                        "lease_owner": "rust-snapshot-worker"
30023                    }
30024                })
30025                .to_string();
30026                write_mock_response(stream, "200 OK", &body);
30027                return;
30028            }
30029
30030            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
30031                let history_events = [3, 5]
30032                    .into_iter()
30033                    .enumerate()
30034                    .map(|(index, amount)| {
30035                        json!({
30036                            "event_type": "SignalReceived",
30037                            "payload": {
30038                                "signal_id": format!("increment-{amount}"),
30039                                "signal_name": "increment",
30040                                "workflow_sequence": index + 2,
30041                                "payload_codec": DEFAULT_CODEC,
30042                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30043                                    .expect("Avro query signal envelope")
30044                            }
30045                        })
30046                    })
30047                    .collect::<Vec<_>>();
30048                let body = json!({
30049                    "task": {
30050                        "query_task_id": "snapshot-current",
30051                        "query_task_attempt": 1,
30052                        "lease_owner": "rust-snapshot-worker",
30053                        "workflow_id": "snapshot-1",
30054                        "run_id": "snapshot-run-1",
30055                        "workflow_type": "snapshot",
30056                        "query_name": "current",
30057                        "payload_codec": DEFAULT_CODEC,
30058                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30059                            .expect("Avro workflow arguments"),
30060                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30061                            .expect("Avro query arguments"),
30062                        "history_events": history_events,
30063                        "run_status": "waiting"
30064                    }
30065                })
30066                .to_string();
30067                write_mock_response(stream, "200 OK", &body);
30068                return;
30069            }
30070
30071            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
30072                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
30073            {
30074                write_mock_response(
30075                    stream,
30076                    "200 OK",
30077                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
30078                );
30079                return;
30080            }
30081
30082            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
30083                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
30084                return;
30085            }
30086
30087            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
30088                write_mock_response(
30089                    stream,
30090                    "200 OK",
30091                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
30092                );
30093                return;
30094            }
30095
30096            if path == "/api/worker/query-tasks/snapshot-current/complete" {
30097                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
30098                return;
30099            }
30100        }
30101
30102        if matches!(
30103            path,
30104            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
30105        ) {
30106            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30107                .expect("typed mock result");
30108            let body = json!({
30109                "result": typed_fidelity_probe().into_json().expect("result projection"),
30110                "result_envelope": result,
30111            })
30112            .to_string();
30113            write_mock_response(stream, "200 OK", &body);
30114            return;
30115        }
30116
30117        if path == "/api/workflows/typed-1" {
30118            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30119                .expect("typed mock result");
30120            let body = json!({
30121                "workflow_id": "typed-1",
30122                "run_id": "run-typed-1",
30123                "workflow_type": "typed.echo",
30124                "status": "completed",
30125                "output": typed_fidelity_probe().into_json().expect("output projection"),
30126                "output_envelope": result,
30127            })
30128            .to_string();
30129            write_mock_response(stream, "200 OK", &body);
30130            return;
30131        }
30132
30133        let (status, body) = match path {
30134            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30135            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30136            "/api/workflows" => (
30137                "201 Created",
30138                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30139            ),
30140            "/api/worker/register" if behavior.decline_registration => (
30141                "200 OK",
30142                r#"{"worker_id":"declined-worker","registered":false}"#,
30143            ),
30144            "/api/worker/register" if behavior.waiting_query_worker => (
30145                "200 OK",
30146                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30147            ),
30148            "/api/worker/register" => (
30149                "200 OK",
30150                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30151            ),
30152            "/api/worker/heartbeat" => ("200 OK", "{}"),
30153            "/api/worker/activity-tasks/poll"
30154                if behavior.cancelled_activity && request_number == 1 =>
30155            {
30156                (
30157                    "200 OK",
30158                    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"}}"#,
30159                )
30160            }
30161            "/api/worker/activity-tasks/poll"
30162                if behavior.long_poll_capacity_responses_per_path > 0
30163                    && request_number
30164                        == behavior
30165                            .long_poll_capacity_responses_per_path
30166                            .saturating_add(1) =>
30167            {
30168                (
30169                    "200 OK",
30170                    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"}}"#,
30171                )
30172            }
30173            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30174                ("200 OK", r#"{"task":null}"#)
30175            }
30176            "/api/worker/query-tasks/poll"
30177                if behavior.reject_query_completion && request_number == 1 =>
30178            {
30179                (
30180                    "200 OK",
30181                    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"}}"#,
30182                )
30183            }
30184            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30185            "/api/worker/query-tasks/query-capture/complete"
30186            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30187            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30188                "200 OK",
30189                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30190            ),
30191            "/api/worker/activity-tasks/activity-cancel/complete" => (
30192                "409 Conflict",
30193                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30194            ),
30195            "/api/worker/activity-tasks/activity-typed/complete"
30196            | "/api/worker/activity-tasks/activity-typed/fail"
30197            | "/api/worker/activity-tasks/capacity-activity/complete"
30198            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30199            "/api/workflows/counter-1/query/current" => (
30200                "200 OK",
30201                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30202            ),
30203            "/api/workflows/counter-1/query/missing" => (
30204                "404 Not Found",
30205                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30206            ),
30207            "/api/workflows/wf-lifecycle/cancel" => (
30208                "200 OK",
30209                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30210            ),
30211            "/api/workflows/wf-lifecycle/terminate" => (
30212                "200 OK",
30213                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30214            ),
30215            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30216                "200 OK",
30217                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30218            ),
30219            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30220                "200 OK",
30221                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30222            ),
30223            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30224                "202 Accepted",
30225                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30226            ),
30227            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30228                "200 OK",
30229                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}"#,
30230            ),
30231            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30232                "409 Conflict",
30233                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30234            ),
30235            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30236            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30237                "409 Conflict",
30238                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30239            ),
30240            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30241                "200 OK",
30242                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"}]}}"#,
30243            ),
30244            "/api/workflows/wf-cancelled" => (
30245                "200 OK",
30246                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30247            ),
30248            "/api/workflows/wf-terminated" => (
30249                "200 OK",
30250                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30251            ),
30252            "/api/workflows/wf-timed-out" => (
30253                "200 OK",
30254                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30255            ),
30256            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30257                "200 OK",
30258                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30259            ),
30260            "/api/workflows/wf-selected" => (
30261                "200 OK",
30262                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30263            ),
30264            "/api/workflows/wf-selected/runs/run-selected" => (
30265                "200 OK",
30266                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30267            ),
30268            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30269        };
30270        write_mock_response(stream, status, body);
30271    }
30272
30273    fn mock_request_is_complete(request: &[u8]) -> bool {
30274        let Some(header_end) = request
30275            .windows(4)
30276            .position(|window| window == b"\r\n\r\n")
30277            .map(|position| position + 4)
30278        else {
30279            return false;
30280        };
30281        let headers = String::from_utf8_lossy(&request[..header_end]);
30282        let content_length = headers.lines().find_map(|line| {
30283            let (name, value) = line.split_once(':')?;
30284            name.eq_ignore_ascii_case("content-length")
30285                .then(|| value.trim().parse::<usize>().ok())
30286                .flatten()
30287        });
30288
30289        request.len() >= header_end + content_length.unwrap_or(0)
30290    }
30291
30292    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30293        let response = format!(
30294            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30295            body.len()
30296        );
30297
30298        let _ = stream.write_all(response.as_bytes());
30299        let _ = stream.flush();
30300    }
30301
30302    fn activity_completion_backend_recovery(
30303        path: &str,
30304        _body: &str,
30305        request_number: usize,
30306    ) -> Option<(&'static str, String)> {
30307        match path {
30308            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30309                "200 OK",
30310                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(),
30311            )),
30312            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30313                "503 Service Unavailable",
30314                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(),
30315            )),
30316            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30317                "200 OK",
30318                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30319            )),
30320            _ => None,
30321        }
30322    }
30323
30324    fn workflow_completion_backend_recovery(
30325        path: &str,
30326        _body: &str,
30327        request_number: usize,
30328    ) -> Option<(&'static str, String)> {
30329        match path {
30330            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
30331                "200 OK",
30332                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
30333            )),
30334            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
30335                "503 Service Unavailable",
30336                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(),
30337            )),
30338            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
30339                "200 OK",
30340                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30341            )),
30342            _ => None,
30343        }
30344    }
30345
30346    fn activity_completion_stale_after_backend_recovery(
30347        path: &str,
30348        body: &str,
30349        request_number: usize,
30350    ) -> Option<(&'static str, String)> {
30351        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
30352            return Some((
30353                "409 Conflict",
30354                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(),
30355            ));
30356        }
30357        activity_completion_backend_recovery(path, body, request_number)
30358    }
30359
30360    fn activity_completion_remains_unavailable(
30361        path: &str,
30362        body: &str,
30363        request_number: usize,
30364    ) -> Option<(&'static str, String)> {
30365        if path == "/api/worker/activity-tasks/recover-activity/complete" {
30366            return activity_completion_backend_recovery(path, body, 1);
30367        }
30368        activity_completion_backend_recovery(path, body, request_number)
30369    }
30370
30371    #[tokio::test]
30372    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
30373        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30374            request_override: Some(activity_completion_backend_recovery),
30375            ..MockWorkerBehavior::default()
30376        });
30377        let client = Client::builder(server.base_url())
30378            .timeout(Duration::from_secs(2))
30379            .build()
30380            .expect("client");
30381        let handler_calls = Arc::new(AtomicUsize::new(0));
30382        let mut worker = Worker::new(client, "recover-queue")
30383            .worker_id("recover-worker")
30384            .poll_timeout(Duration::from_millis(10));
30385        worker.register_activity("recover.activity", {
30386            let handler_calls = Arc::clone(&handler_calls);
30387            move |_ctx, _args| {
30388                let handler_calls = Arc::clone(&handler_calls);
30389                async move {
30390                    handler_calls.fetch_add(1, Ordering::SeqCst);
30391                    Ok(json!("done"))
30392                }
30393            }
30394        });
30395
30396        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30397        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30398        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30399        assert_eq!(bodies.len(), 2);
30400        assert_eq!(bodies[0], bodies[1]);
30401    }
30402
30403    #[tokio::test]
30404    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
30405        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30406            request_override: Some(workflow_completion_backend_recovery),
30407            ..MockWorkerBehavior::default()
30408        });
30409        let client = Client::builder(server.base_url())
30410            .timeout(Duration::from_secs(2))
30411            .build()
30412            .expect("client");
30413        let handler_calls = Arc::new(AtomicUsize::new(0));
30414        let mut worker = Worker::new(client, "recover-queue")
30415            .worker_id("recover-worker")
30416            .poll_timeout(Duration::from_millis(10));
30417        worker.register_workflow("recover.workflow", {
30418            let handler_calls = Arc::clone(&handler_calls);
30419            move |_ctx, _args| {
30420                let handler_calls = Arc::clone(&handler_calls);
30421                async move {
30422                    handler_calls.fetch_add(1, Ordering::SeqCst);
30423                    Ok(json!("done"))
30424                }
30425            }
30426        });
30427
30428        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
30429        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30430        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30431        assert_eq!(bodies.len(), 2);
30432        assert_eq!(bodies[0], bodies[1]);
30433    }
30434
30435    #[tokio::test]
30436    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
30437        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30438            request_override: Some(activity_completion_stale_after_backend_recovery),
30439            ..MockWorkerBehavior::default()
30440        });
30441        let client = Client::builder(server.base_url())
30442            .timeout(Duration::from_secs(2))
30443            .build()
30444            .expect("client");
30445        let handler_calls = Arc::new(AtomicUsize::new(0));
30446        let mut worker = Worker::new(client, "recover-queue")
30447            .worker_id("recover-worker")
30448            .poll_timeout(Duration::from_millis(10));
30449        worker.register_activity("recover.activity", {
30450            let handler_calls = Arc::clone(&handler_calls);
30451            move |_ctx, _args| {
30452                let handler_calls = Arc::clone(&handler_calls);
30453                async move {
30454                    handler_calls.fetch_add(1, Ordering::SeqCst);
30455                    Ok(json!("done"))
30456                }
30457            }
30458        });
30459
30460        assert_eq!(
30461            worker
30462                .run_once()
30463                .await
30464                .expect("authoritative stale outcome"),
30465            1
30466        );
30467        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30468        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30469        assert_eq!(bodies.len(), 2);
30470        assert_eq!(bodies[0], bodies[1]);
30471    }
30472
30473    #[test]
30474    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
30475        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
30476        let response = json!({
30477            "reason":"backend_unavailable", "operation":"complete_activity_task",
30478            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30479            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
30480            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
30481        });
30482        let path = "/worker/activity-tasks/recover-activity/complete";
30483        let error = |body: Value| Error::Http {
30484            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30485            body: body.to_string(),
30486        };
30487        assert_eq!(
30488            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
30489            Some(Duration::from_secs(1))
30490        );
30491
30492        for (field, invalid) in [
30493            ("operation", json!("poll_activity_task")),
30494            ("outcome", json!("rejected")),
30495            ("worker_id", json!("another-worker")),
30496            ("task_queue", json!("recover-queue")),
30497            ("retryable", json!(false)),
30498            ("retry_after_seconds", json!(0)),
30499            ("task_id", json!("another-task")),
30500            ("lease_owner", json!("another-worker")),
30501            ("activity_attempt_id", json!("another-attempt")),
30502        ] {
30503            let mut invalid_response = response.clone();
30504            invalid_response[field] = invalid;
30505            assert_eq!(
30506                worker_fenced_completion_retry_after(
30507                    &error(invalid_response),
30508                    path,
30509                    Some(&request)
30510                ),
30511                None,
30512                "must not retry mismatched {field}"
30513            );
30514        }
30515        assert_eq!(
30516            worker_fenced_completion_retry_after(&error(response), path, None),
30517            None
30518        );
30519    }
30520
30521    #[tokio::test]
30522    async fn shutdown_interrupts_fenced_completion_backend_wait() {
30523        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30524            request_override: Some(activity_completion_remains_unavailable),
30525            ..MockWorkerBehavior::default()
30526        });
30527        let client = Client::builder(server.base_url())
30528            .timeout(Duration::from_secs(2))
30529            .build()
30530            .expect("client");
30531        let stop = Arc::new(AtomicBool::new(false));
30532        let worker = Worker::new(client, "recover-queue")
30533            .worker_id("recover-worker")
30534            .with_storage_admission(Arc::clone(&stop));
30535        let completion = tokio::spawn(async move {
30536            worker
30537                .client
30538                .complete_activity_task(
30539                    "recover-activity",
30540                    "recover-attempt",
30541                    "recover-worker",
30542                    json!("done"),
30543                    DEFAULT_CODEC,
30544                )
30545                .await
30546        });
30547        let path = "/api/worker/activity-tasks/recover-activity/complete";
30548        tokio::time::timeout(Duration::from_secs(2), async {
30549            while server.request_count(path) == 0 {
30550                tokio::time::sleep(Duration::from_millis(10)).await;
30551            }
30552        })
30553        .await
30554        .expect("first completion request");
30555        stop.store(true, Ordering::SeqCst);
30556        let error = tokio::time::timeout(Duration::from_secs(1), completion)
30557            .await
30558            .expect("shutdown must interrupt retry wait")
30559            .expect("completion task")
30560            .expect_err("backend is still unavailable");
30561        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
30562        assert_eq!(server.request_count(path), 1);
30563    }
30564}