Skip to main content

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod activity_error;
4mod activity_hydration;
5mod activity_lease;
6mod cancellation_context;
7mod cancellation_replay_clock;
8mod cancellation_scope;
9mod cancellation_scope_history;
10mod cancellation_scope_replay;
11mod cooperative_cancellation;
12mod local_activity;
13mod nexus;
14mod query_authority;
15mod runtime_payloads;
16mod runtime_uploads;
17mod sticky_worker;
18mod sticky_workflow_cache;
19#[cfg(feature = "telemetry")]
20pub mod telemetry;
21pub mod testing;
22mod tls;
23mod worker_capacity;
24mod worker_session;
25mod workflow_hydration;
26
27pub use activity_error::ActivityError;
28pub use cancellation_context::{
29    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
30};
31pub use cancellation_scope::CancellationScopeOpenReceipt;
32#[doc(hidden)]
33pub use cancellation_scope_history::{
34    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
35};
36#[doc(hidden)]
37pub use cancellation_scope_replay::CancellationScopeRequested;
38
39pub use cooperative_cancellation::{
40    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
41    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
42    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
43    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
44};
45
46use std::{
47    any::{type_name, Any, TypeId},
48    collections::{BTreeMap, BTreeSet, HashMap},
49    future::Future,
50    io::{self, Read},
51    pin::Pin,
52    sync::{
53        atomic::{AtomicBool, Ordering},
54        Arc, Mutex, OnceLock,
55    },
56    task::{Context as TaskContext, Poll},
57    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
58};
59
60use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
61use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
62use chrono::DateTime;
63use futures_util::{future::OptionFuture, task::noop_waker_ref};
64pub use local_activity::LocalActivityOptions;
65use serde::{
66    de::DeserializeOwned,
67    ser::{SerializeMap, SerializeSeq},
68    Deserialize, Deserializer, Serialize, Serializer,
69};
70pub use serde_json::{json, Value};
71use sha2::{Digest, Sha256};
72pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
73use thiserror::Error;
74pub use uuid::Uuid;
75pub use worker_session::{WorkerSession, WorkerSessionOptions};
76
77pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
78pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
79
80/// Select the worker request protocol without enabling optional capabilities.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum WorkerProtocolVersion {
84    /// Compatibility with Servers that implement only worker protocol 1.19.
85    V119,
86    /// The default worker protocol.
87    #[default]
88    V120,
89}
90
91impl WorkerProtocolVersion {
92    fn as_str(self) -> &'static str {
93        match self {
94            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
95            Self::V120 => WORKER_PROTOCOL_VERSION,
96        }
97    }
98}
99const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
100/// First additive worker protocol that defines portable worker-affinity features.
101pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
102pub const CONTROL_PLANE_VERSION: &str = "2";
103pub const DEFAULT_CODEC: &str = "avro";
104pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
105/// Worker-registration capability for authored condition-wait occurrence identity.
106pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
107    "condition_wait_occurrence_identity";
108/// Worker-registration capability for portable memo upserts.
109pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
110/// Worker-registration capability for server-routed read-only queries.
111pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
112/// Worker-registration capability for canonical typed search attributes.
113pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
114/// Worker-registration capability for synchronous workflow updates.
115pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
116/// Worker-registration capability for durable named input streams.
117pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
118/// Worker-registration capability for persisted first-completion selection.
119pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
120pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
121pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
122pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
123pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
124pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
125/// First additive worker protocol that defines query-task transport.
126pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
127/// First additive worker protocol that defines typed search-attribute upserts.
128pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
129/// First additive worker protocol that defines portable memo upserts.
130pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
131/// First additive worker protocol that preserves declared search-attribute types.
132pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
133/// First additive worker protocol that defines external durable condition waits.
134pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
135/// First additive worker protocol that preserves authored condition-wait occurrences.
136pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
137/// First additive worker protocol that defines durable selection groups.
138pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
139
140pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
141    let Some((major, minor)) = version.split_once('.') else {
142        return false;
143    };
144    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
145}
146
147fn validate_user_signal_name(signal_name: &str) -> Result<()> {
148    if signal_name == MESSAGE_STREAM_SIGNAL {
149        return Err(Error::Codec(format!(
150            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
151        )));
152    }
153    Ok(())
154}
155
156const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
157const MAX_REQUEST_ID_CHARACTERS: usize = 255;
158
159/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
160fn validate_request_id(request_id: &str) -> Result<()> {
161    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
162        return Err(Error::Codec(format!(
163            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
164        )));
165    }
166    Ok(())
167}
168
169fn generated_request_id(command: &str) -> String {
170    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
171}
172
173/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
174fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
175    if receipt.is_null() {
176        return json!({ "request_id": request_id });
177    }
178    if let Some(receipt) = receipt.as_object_mut() {
179        receipt
180            .entry("request_id")
181            .or_insert_with(|| Value::String(request_id.to_string()));
182    }
183    receipt
184}
185
186const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
187const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
188    "Workflow task waiting for scheduled history.";
189const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
190const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
191const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
192const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
193const MAX_MEMO_ENTRIES: usize = 100;
194const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
195const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
196
197const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
198    "lease_expired",
199    "query_task_not_found",
200    "query_task_not_leased",
201    "query_task_timed_out",
202    "query_deadline_unavailable",
203    "lease_owner_mismatch",
204    "query_task_attempt_mismatch",
205];
206
207/// Manifest for the default service-worker profile.
208///
209/// Inline local execution is enabled separately by [`Worker::local_activities`].
210/// Local execution, sessions and caching require explicit Worker configuration.
211pub fn portable_worker_affinity_capability_manifest() -> Value {
212    json!({
213        "local_activities": {
214            "supported": false,
215            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
216            "reason": "rust_worker_does_not_execute_record_local_activity",
217        },
218        "worker_sessions": {
219            "supported": false,
220            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
221            "reason": "rust_worker_has_no_typed_session_lifecycle",
222        },
223        "sticky_execution": {
224            "supported": false,
225            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
226            "reason": "rust_worker_uses_complete_durable_history_replay",
227        },
228    })
229}
230
231/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
232pub const AVRO_VALUE_SCHEMA_JSON: &str =
233    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
234pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
235pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
236const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
237
238static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
239static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
240    OnceLock::new();
241
242#[derive(Clone, Copy)]
243enum RequestProtocol {
244    ControlPlane,
245    DefaultWorker,
246    Worker(&'static str),
247}
248
249pub type Result<T> = std::result::Result<T, Error>;
250
251pub use nexus::{
252    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
253    NexusServiceOptions, NexusWaitFor,
254};
255
256#[derive(Debug, Error)]
257#[non_exhaustive]
258pub enum Error {
259    #[error("transport error: {0}")]
260    Transport(#[from] reqwest::Error),
261    #[error(
262        "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"
263    )]
264    InvalidBaseUrl,
265    #[error("invalid additional root certificates: {0}")]
266    InvalidRootCertificates(String),
267    #[error(transparent)]
268    Testing(#[from] testing::TestingError),
269    #[error("json error: {0}")]
270    Json(#[from] serde_json::Error),
271    #[error("http {status}: {body}")]
272    Http {
273        status: reqwest::StatusCode,
274        body: String,
275    },
276    #[error("codec error: {0}")]
277    Codec(String),
278    #[error(transparent)]
279    QueryFailed(QueryFailure),
280    #[error(transparent)]
281    Protocol(ProtocolFailure),
282    #[error(transparent)]
283    NonDeterministicReplay(ReplayFailure),
284    #[error(transparent)]
285    ChildWorkflowFailed(ChildWorkflowFailure),
286    #[error(transparent)]
287    ActivityFailed(ActivityFailure),
288    #[error(transparent)]
289    ActivityError(#[from] ActivityError),
290    #[error(transparent)]
291    NexusOperationFailed(Box<NexusOperationFailure>),
292    #[error(transparent)]
293    ParallelFailed(ParallelFailure),
294    #[error(transparent)]
295    SagaCompensationFailed(SagaCompensationFailure),
296    #[error(transparent)]
297    InvalidParallelGroup(ParallelGroupError),
298    #[error(transparent)]
299    DurableOperationCancelled(DurableOperationCancelled),
300    #[error(transparent)]
301    WorkflowCancellationRequested(WorkflowCancellationRequested),
302    #[error(transparent)]
303    CooperativeCancellationRequested(CooperativeCancellationRequested),
304    #[error(transparent)]
305    CancellationScopeRequested(CancellationScopeRequested),
306    #[error(transparent)]
307    WorkflowCommandRejected(WorkflowCommandRejection),
308    #[error(transparent)]
309    WorkflowFailed(WorkflowTerminalOutcome),
310    #[error(transparent)]
311    WorkflowCancelled(WorkflowTerminalOutcome),
312    #[error(transparent)]
313    WorkflowTerminated(WorkflowTerminalOutcome),
314    #[error(transparent)]
315    WorkflowTimedOut(WorkflowTerminalOutcome),
316    #[error(transparent)]
317    ActivityTaskRejected(ActivityTaskRejection),
318    #[error("activity lease renewal unavailable: {0}")]
319    ActivityLeaseRenewalUnavailable(String),
320    #[error("workflow handler {0:?} is not registered")]
321    WorkflowNotRegistered(String),
322    #[error("activity handler {0:?} is not registered")]
323    ActivityNotRegistered(String),
324    #[error(
325        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
326    )]
327    HandlerType {
328        handler_kind: HandlerKind,
329        handler_name: String,
330        value_kind: HandlerValueKind,
331        rust_type: &'static str,
332        message: String,
333    },
334    #[error("workflow future yielded without emitting a durable command")]
335    WorkflowYieldedWithoutCommand,
336    #[error(
337        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
338    )]
339    MissingWorkflowCommandIdentity,
340    #[error("workflow state lock is poisoned")]
341    WorkflowStatePoisoned,
342    #[error("timer duration is too large for the worker protocol")]
343    TimerDurationOverflow,
344    #[error(transparent)]
345    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
346    #[error(transparent)]
347    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
348    #[error("operation timed out")]
349    Timeout,
350    #[error(
351        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
352    )]
353    MissingRoleCredentials {
354        role: &'static str,
355        opposite_role: &'static str,
356    },
357    #[error("worker loop error: {0}")]
358    WorkerLoop(String),
359    #[error(
360        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
361    )]
362    UnsupportedUpdateValidators { workflow_type: String },
363    #[error("{primary}; worker deregistration also failed: {deregistration}")]
364    WorkerShutdown {
365        primary: Box<Error>,
366        deregistration: Box<Error>,
367    },
368    #[error("invalid child workflow options: {0}")]
369    InvalidChildWorkflowOptions(String),
370    #[error("invalid workflow memo update: {0}")]
371    InvalidMemoUpdate(String),
372    #[error(
373        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
374    )]
375    WorkflowMemoUpdatesUnavailable,
376    #[error("cooperative cancellation is unavailable: {0}")]
377    CooperativeCancellationUnavailable(String),
378    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
379    CancellationScopeExecutionUnavailable,
380    #[error("invalid cooperative cancellation: {0}")]
381    InvalidCooperativeCancellation(String),
382    #[error("activity execution no longer owns its claim: {0}")]
383    ActivityExecutionAbandoned(String),
384    #[error(transparent)]
385    InvalidActivityOptions(ActivityOptionsError),
386    #[error(transparent)]
387    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
388    #[doc(hidden)]
389    #[error("workflow requested continue as new")]
390    ContinueAsNew(ContinueAsNewRequest),
391}
392
393impl Error {
394    /// The caller command key echoed by the Server in a refusal body.
395    ///
396    /// Signals and updates send their key as the `request_id` body field, and a
397    /// Server refusal such as `request_id_conflict` echoes it. Transport failures
398    /// and refusals without an echoed key return `None`: keep the key you passed
399    /// to a `*_with_request_id` method, or obtained from
400    /// [`Client::generate_signal_request_id`] or
401    /// [`Client::generate_update_request_id`], to retry the same logical command
402    /// after an uncertain outcome.
403    pub fn request_id(&self) -> Option<String> {
404        self.refusal_body()?
405            .get("request_id")
406            .and_then(Value::as_str)
407            .filter(|request_id| !request_id.is_empty())
408            .map(str::to_string)
409    }
410
411    /// Whether the Server refused a signal or update because its caller command
412    /// key is retained for a command with a different intent
413    /// (HTTP 409, `reason: "request_id_conflict"`).
414    pub fn is_request_id_conflict(&self) -> bool {
415        self.request_id_conflict().is_some()
416    }
417
418    /// The retained-command details of a `request_id_conflict` refusal.
419    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
420        let status = match self {
421            Self::Http { status, .. } => status.as_u16(),
422            Self::WorkflowCommandRejected(rejection) => rejection.status,
423            _ => return None,
424        };
425        request_id_conflict(status, self.refusal_body()?)
426    }
427
428    fn refusal_body(&self) -> Option<Value> {
429        match self {
430            Self::Http { body, .. } => serde_json::from_str(body).ok(),
431            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
432            _ => None,
433        }
434    }
435}
436
437/// A refused signal or update whose caller command key is already retained for
438/// a command with a different intent.
439///
440/// Nothing was admitted or recorded, and the key stays bound to the retained
441/// command. Send a new key for a different command, or repeat the retained
442/// command's exact intent to receive its receipt. `conflict` lists the
443/// mismatched intent parts among `name`, `arguments` and `target`.
444#[derive(Clone, Debug, PartialEq)]
445#[non_exhaustive]
446pub struct RequestIdConflict {
447    pub status: u16,
448    pub request_id: String,
449    pub message: String,
450    pub retained_command_id: Option<String>,
451    pub retained_command_type: Option<String>,
452    pub retained_outcome: Option<String>,
453    pub conflict: Vec<String>,
454    pub body: Value,
455}
456
457fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
458    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
459        return None;
460    }
461    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
462    Some(RequestIdConflict {
463        status,
464        request_id: string("request_id").unwrap_or_default(),
465        message: string("message")
466            .or_else(|| string("error"))
467            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
468        retained_command_id: string("retained_command_id"),
469        retained_command_type: string("retained_command_type"),
470        retained_outcome: string("retained_outcome"),
471        conflict: body
472            .get("conflict")
473            .and_then(Value::as_array)
474            .map(|parts| {
475                parts
476                    .iter()
477                    .filter_map(Value::as_str)
478                    .map(str::to_string)
479                    .collect()
480            })
481            .unwrap_or_default(),
482        body,
483    })
484}
485
486/// Handler namespaces checked independently within a Worker.
487#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
488pub enum RegistrationKind {
489    Workflow,
490    Activity,
491    Query,
492    Update,
493}
494
495impl std::fmt::Display for RegistrationKind {
496    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497        formatter.write_str(match self {
498            Self::Workflow => "workflow",
499            Self::Activity => "activity",
500            Self::Query => "query",
501            Self::Update => "update",
502        })
503    }
504}
505
506/// The authoring adapter and source location of a handler registration.
507#[derive(Clone, Debug, PartialEq, Eq)]
508pub struct HandlerRegistration {
509    pub method: &'static str,
510    pub handler_type: &'static str,
511    pub file: &'static str,
512    pub line: u32,
513    pub column: u32,
514}
515
516impl std::fmt::Display for HandlerRegistration {
517    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518        write!(
519            formatter,
520            "{} at {}:{}:{} ({})",
521            self.method, self.file, self.line, self.column, self.handler_type
522        )
523    }
524}
525
526/// Ambiguous local configuration, rejected before contacting Server.
527#[derive(Clone, Debug, Error, PartialEq, Eq)]
528#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
529pub struct DuplicateRegistrationError {
530    pub handler_kind: RegistrationKind,
531    pub handler_name: String,
532    /// Query/update registrations are scoped to their owning workflow type.
533    pub workflow_type: Option<String>,
534    pub first_definition: HandlerRegistration,
535    pub second_definition: HandlerRegistration,
536}
537
538impl From<DuplicateRegistrationError> for Error {
539    fn from(error: DuplicateRegistrationError) -> Self {
540        Self::WorkerLoop(error.to_string())
541    }
542}
543
544/// Validation failure for a durable condition-wait definition.
545#[derive(Clone, Debug, Error, PartialEq, Eq)]
546pub enum ConditionWaitOptionsError {
547    #[error("condition_key must be non-empty")]
548    EmptyKey,
549    #[error("condition_definition_fingerprint must be non-empty")]
550    EmptyPredicateIdentity,
551    #[error("condition timeout is too large for the worker protocol")]
552    TimeoutOverflow,
553}
554
555/// Stable identity and optional durable timeout for a condition wait.
556///
557/// `predicate_identity` is recorded as the worker protocol's
558/// `condition_definition_fingerprint` and must change whenever predicate
559/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
560/// is written inline; it derives this identity from the predicate tokens.
561#[derive(Clone, Debug, PartialEq, Eq)]
562pub struct ConditionWaitOptions {
563    condition_key: String,
564    predicate_identity: String,
565    timeout: Option<Duration>,
566}
567
568impl ConditionWaitOptions {
569    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
570        Self {
571            condition_key: condition_key.into(),
572            predicate_identity: predicate_identity.into(),
573            timeout: None,
574        }
575    }
576
577    pub fn timeout(mut self, timeout: Duration) -> Self {
578        self.timeout = Some(timeout);
579        self
580    }
581
582    fn validate(
583        &self,
584    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
585        let condition_key = self.condition_key.trim();
586        if condition_key.is_empty() {
587            return Err(ConditionWaitOptionsError::EmptyKey);
588        }
589        let predicate_identity = self.predicate_identity.trim();
590        if predicate_identity.is_empty() {
591            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
592        }
593        let timeout_seconds = self
594            .timeout
595            .map(|timeout| {
596                timeout
597                    .as_secs()
598                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
599                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
600            })
601            .transpose()?;
602
603        Ok(ValidatedConditionWaitOptions {
604            condition_key: condition_key.to_string(),
605            predicate_identity: predicate_identity.to_string(),
606            timeout_seconds,
607        })
608    }
609}
610
611#[derive(Clone, Debug, PartialEq, Eq)]
612struct ValidatedConditionWaitOptions {
613    condition_key: String,
614    predicate_identity: String,
615    timeout_seconds: Option<u64>,
616}
617
618const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
619
620/// Unambiguous terminal result of a durable condition wait.
621#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
622#[serde(rename_all = "snake_case")]
623pub enum ConditionWaitResult {
624    Satisfied,
625    TimedOut,
626}
627
628impl ConditionWaitResult {
629    pub fn is_satisfied(self) -> bool {
630        self == Self::Satisfied
631    }
632
633    pub fn is_timed_out(self) -> bool {
634        self == Self::TimedOut
635    }
636}
637
638/// Build the stable condition definition identity used by [`wait_condition!`].
639#[doc(hidden)]
640pub fn __condition_definition_fingerprint(source: &str) -> String {
641    let mut digest = Sha256::new();
642    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
643    digest.update(source.as_bytes());
644    format!("sha256:{:x}", digest.finalize())
645}
646
647/// Create a durable condition wait whose predicate definition is fingerprinted
648/// from its inline Rust tokens.
649///
650/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
651/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
652#[macro_export]
653macro_rules! wait_condition {
654    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
655        $ctx.wait_condition(
656            $crate::ConditionWaitOptions::new(
657                $key,
658                $crate::__condition_definition_fingerprint(concat!(
659                    module_path!(),
660                    "\0",
661                    stringify!($predicate)
662                )),
663            )
664            .timeout($timeout),
665            $predicate,
666        )
667    }};
668    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
669        $ctx.wait_condition(
670            $crate::ConditionWaitOptions::new(
671                $key,
672                $crate::__condition_definition_fingerprint(concat!(
673                    module_path!(),
674                    "\0",
675                    stringify!($predicate)
676                )),
677            ),
678            $predicate,
679        )
680    }};
681}
682
683const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
684const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
685const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
686const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
687const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
688
689/// Validation failure for a typed workflow search-attribute update.
690#[derive(Clone, Debug, Error, PartialEq, Eq)]
691pub enum SearchAttributeUpdateError {
692    #[error("search-attribute update requires at least one attribute")]
693    Empty,
694    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
695    InvalidKey(String),
696    #[error("search-attribute update exceeds the limit of 100 attributes")]
697    TooManyAttributes,
698    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
699    ValueTooLong {
700        key: String,
701        kind: &'static str,
702        limit: usize,
703    },
704    #[error(
705        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
706    )]
707    EmptyString(String),
708    #[error("search attribute {0:?} has a non-finite float value")]
709    NonFiniteFloat(String),
710    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
711    InvalidDateTime(String),
712    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
713    PayloadTooLarge,
714}
715
716/// One public typed search-attribute value.
717#[derive(Clone, Debug, PartialEq)]
718pub enum SearchAttributeValue {
719    String(String),
720    Keyword(String),
721    KeywordList(Vec<String>),
722    Int(i64),
723    Float(f64),
724    Bool(bool),
725    DateTime(String),
726    Delete,
727}
728
729impl SearchAttributeValue {
730    fn type_name(&self) -> Option<&'static str> {
731        match self {
732            Self::String(_) => Some("string"),
733            Self::Keyword(_) => Some("keyword"),
734            Self::KeywordList(_) => Some("keyword_list"),
735            Self::Int(_) => Some("int"),
736            Self::Float(_) => Some("float"),
737            Self::Bool(_) => Some("bool"),
738            Self::DateTime(_) => Some("datetime"),
739            Self::Delete => None,
740        }
741    }
742
743    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
744        let normalize_string = |value: String, kind: &'static str, limit: usize| {
745            let value = value.trim().to_string();
746            if value.is_empty() {
747                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
748            }
749            if value.len() > limit {
750                return Err(SearchAttributeUpdateError::ValueTooLong {
751                    key: key.to_string(),
752                    kind,
753                    limit,
754                });
755            }
756            Ok(value)
757        };
758
759        match self {
760            Self::String(value) => Ok(Self::String(normalize_string(
761                value,
762                "string",
763                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
764            )?)),
765            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
766                value,
767                "keyword",
768                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
769            )?)),
770            Self::KeywordList(values) => {
771                let values = values
772                    .into_iter()
773                    .map(|value| {
774                        let value = value.trim().to_string();
775                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
776                            return Err(SearchAttributeUpdateError::ValueTooLong {
777                                key: key.to_string(),
778                                kind: "keyword-list entry",
779                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
780                            });
781                        }
782                        Ok(value)
783                    })
784                    .collect::<std::result::Result<Vec<_>, _>>()?;
785                Ok(Self::KeywordList(values))
786            }
787            Self::Float(value) if !value.is_finite() => {
788                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
789            }
790            Self::DateTime(value) => {
791                let value =
792                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
793                if DateTime::parse_from_rfc3339(&value).is_err() {
794                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
795                }
796                Ok(Self::DateTime(value))
797            }
798            value => Ok(value),
799        }
800    }
801
802    fn into_json(self) -> Value {
803        match self {
804            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
805                Value::String(value)
806            }
807            Self::KeywordList(values) => {
808                Value::Array(values.into_iter().map(Value::String).collect())
809            }
810            Self::Int(value) => json!(value),
811            Self::Float(value) => json!(value),
812            Self::Bool(value) => json!(value),
813            Self::Delete => Value::Null,
814        }
815    }
816}
817
818/// Validated typed workflow-side search-attribute mutation.
819#[derive(Clone, Debug, Default, PartialEq)]
820pub struct SearchAttributeUpdate {
821    attributes: BTreeMap<String, SearchAttributeValue>,
822}
823
824impl SearchAttributeUpdate {
825    pub fn new() -> Self {
826        Self::default()
827    }
828
829    pub fn set(
830        mut self,
831        key: impl Into<String>,
832        value: SearchAttributeValue,
833    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
834        let key = key.into();
835        validate_search_attribute_key(&key)?;
836        if !self.attributes.contains_key(&key)
837            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
838        {
839            return Err(SearchAttributeUpdateError::TooManyAttributes);
840        }
841        self.attributes.insert(key.clone(), value.normalized(&key)?);
842        self.validate_size()?;
843        Ok(self)
844    }
845
846    pub fn string(
847        self,
848        key: impl Into<String>,
849        value: impl Into<String>,
850    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
851        self.set(key, SearchAttributeValue::String(value.into()))
852    }
853
854    pub fn keyword(
855        self,
856        key: impl Into<String>,
857        value: impl Into<String>,
858    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
859        self.set(key, SearchAttributeValue::Keyword(value.into()))
860    }
861
862    pub fn keyword_list<I, V>(
863        self,
864        key: impl Into<String>,
865        values: I,
866    ) -> std::result::Result<Self, SearchAttributeUpdateError>
867    where
868        I: IntoIterator<Item = V>,
869        V: Into<String>,
870    {
871        self.set(
872            key,
873            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
874        )
875    }
876
877    pub fn int(
878        self,
879        key: impl Into<String>,
880        value: i64,
881    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
882        self.set(key, SearchAttributeValue::Int(value))
883    }
884
885    pub fn float(
886        self,
887        key: impl Into<String>,
888        value: f64,
889    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
890        self.set(key, SearchAttributeValue::Float(value))
891    }
892
893    pub fn bool(
894        self,
895        key: impl Into<String>,
896        value: bool,
897    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
898        self.set(key, SearchAttributeValue::Bool(value))
899    }
900
901    pub fn datetime(
902        self,
903        key: impl Into<String>,
904        value: impl Into<String>,
905    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
906        self.set(key, SearchAttributeValue::DateTime(value.into()))
907    }
908
909    pub fn delete(
910        self,
911        key: impl Into<String>,
912    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
913        self.set(key, SearchAttributeValue::Delete)
914    }
915
916    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
917        let (attributes, _) = self.clone().into_wire_parts();
918        if serde_json::to_vec(&attributes)
919            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
920            .unwrap_or(true)
921        {
922            return Err(SearchAttributeUpdateError::PayloadTooLarge);
923        }
924        Ok(())
925    }
926
927    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
928        let mut attributes = serde_json::Map::new();
929        let mut attribute_types = BTreeMap::new();
930        for (key, value) in self.attributes {
931            if let Some(type_name) = value.type_name() {
932                attribute_types.insert(key.clone(), type_name.to_string());
933            }
934            attributes.insert(key, value.into_json());
935        }
936        (Value::Object(attributes), attribute_types)
937    }
938
939    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
940        if self.attributes.is_empty() {
941            return Err(SearchAttributeUpdateError::Empty);
942        }
943        self.validate_size()
944    }
945}
946
947fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
948    let valid = !key.is_empty()
949        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
950        && key
951            .bytes()
952            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
953    if valid {
954        Ok(())
955    } else {
956        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
957    }
958}
959
960/// The registered handler family reported by [`Error::HandlerType`].
961#[derive(Clone, Copy, Debug, PartialEq, Eq)]
962pub enum HandlerKind {
963    Workflow,
964    Activity,
965}
966
967impl std::fmt::Display for HandlerKind {
968    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969        formatter.write_str(match self {
970            Self::Workflow => "workflow",
971            Self::Activity => "activity",
972        })
973    }
974}
975
976/// Whether a typed handler failed to adapt its input or result.
977#[derive(Clone, Copy, Debug, PartialEq, Eq)]
978pub enum HandlerValueKind {
979    Input,
980    Result,
981}
982
983impl std::fmt::Display for HandlerValueKind {
984    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
985        formatter.write_str(match self {
986            Self::Input => "input",
987            Self::Result => "result",
988        })
989    }
990}
991
992/// The lifecycle command sent to a workflow execution.
993#[derive(Clone, Copy, Debug, PartialEq, Eq)]
994pub enum WorkflowCommandKind {
995    Cancel,
996    Terminate,
997}
998
999impl WorkflowCommandKind {
1000    fn as_str(self) -> &'static str {
1001        match self {
1002            Self::Cancel => "cancel",
1003            Self::Terminate => "terminate",
1004        }
1005    }
1006}
1007
1008/// Optional structured fields for a cancellation or termination request.
1009#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1010pub struct WorkflowCommandOptions {
1011    #[serde(skip_serializing_if = "Option::is_none")]
1012    pub reason: Option<String>,
1013    #[serde(skip_serializing_if = "Option::is_none")]
1014    pub request_id: Option<String>,
1015}
1016
1017/// Server-enforced timeout policy for a workflow start.
1018///
1019/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1020/// only bounds how long the caller waits. A server deadline produces a terminal
1021/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1022/// `run_timeout`.
1023#[derive(Clone, Debug, PartialEq, Eq)]
1024pub struct WorkflowStartOptions {
1025    pub execution_timeout_seconds: u64,
1026    pub run_timeout_seconds: u64,
1027}
1028
1029impl Default for WorkflowStartOptions {
1030    fn default() -> Self {
1031        Self {
1032            execution_timeout_seconds: 3600,
1033            run_timeout_seconds: 600,
1034        }
1035    }
1036}
1037
1038impl WorkflowStartOptions {
1039    pub fn new() -> Self {
1040        Self::default()
1041    }
1042
1043    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1044        self.execution_timeout_seconds = seconds;
1045        self
1046    }
1047
1048    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1049        self.run_timeout_seconds = seconds;
1050        self
1051    }
1052
1053    fn validate(&self) -> Result<()> {
1054        if self.execution_timeout_seconds == 0 {
1055            return Err(Error::Codec(
1056                "execution_timeout_seconds must be at least 1".to_string(),
1057            ));
1058        }
1059        if self.run_timeout_seconds == 0 {
1060            return Err(Error::Codec(
1061                "run_timeout_seconds must be at least 1".to_string(),
1062            ));
1063        }
1064        if self.run_timeout_seconds > self.execution_timeout_seconds {
1065            return Err(Error::Codec(
1066                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1067            ));
1068        }
1069
1070        Ok(())
1071    }
1072}
1073
1074/// Optional routing overrides for a continue-as-new transition.
1075///
1076/// Omitted values retain the current workflow type and task queue. Server-owned
1077/// instance metadata is not accepted here and is carried by the server.
1078#[derive(Clone, Debug, Default, PartialEq, Eq)]
1079pub struct ContinueAsNewOptions {
1080    pub workflow_type: Option<String>,
1081    pub task_queue: Option<String>,
1082}
1083
1084impl ContinueAsNewOptions {
1085    pub fn new() -> Self {
1086        Self::default()
1087    }
1088
1089    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1090        self.workflow_type = Some(workflow_type.into());
1091        self
1092    }
1093
1094    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1095        self.task_queue = Some(task_queue.into());
1096        self
1097    }
1098
1099    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1100        for (field, value) in [
1101            ("workflow_type", self.workflow_type.as_deref()),
1102            ("task_queue", self.task_queue.as_deref()),
1103        ] {
1104            if value.is_some_and(|value| value.trim().is_empty()) {
1105                return Err(ContinueAsNewOptionsError {
1106                    field,
1107                    message: format!("{field} must not be empty"),
1108                });
1109            }
1110        }
1111        Ok(())
1112    }
1113}
1114
1115/// A stable validation error raised before a continue-as-new command is emitted.
1116#[derive(Clone, Debug, Error, PartialEq, Eq)]
1117#[error("invalid continue-as-new option {field}: {message}")]
1118pub struct ContinueAsNewOptionsError {
1119    pub field: &'static str,
1120    pub message: String,
1121}
1122
1123/// Public history-budget information attached to the current workflow task.
1124#[derive(Clone, Debug, Default, PartialEq, Eq)]
1125pub struct WorkflowHistoryBudget {
1126    pub event_count: u64,
1127    pub size_bytes: Option<u64>,
1128    pub continue_as_new_recommended: bool,
1129    pub pressure: Option<String>,
1130}
1131
1132#[doc(hidden)]
1133#[derive(Clone, Debug)]
1134pub struct ContinueAsNewRequest {
1135    arguments: AvroValue,
1136    options: ContinueAsNewOptions,
1137}
1138
1139impl WorkflowCommandOptions {
1140    pub fn new() -> Self {
1141        Self::default()
1142    }
1143
1144    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1145        self.reason = Some(reason.into());
1146        self
1147    }
1148
1149    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1150        self.request_id = Some(request_id.into());
1151        self
1152    }
1153}
1154
1155/// The accepted, machine-readable result of a lifecycle command.
1156#[derive(Clone, Debug, PartialEq)]
1157pub struct WorkflowCommandResult {
1158    pub command: WorkflowCommandKind,
1159    pub workflow_id: String,
1160    pub run_id: Option<String>,
1161    pub outcome: Option<String>,
1162    pub reason: Option<String>,
1163    pub command_status: Option<String>,
1164    pub raw: Value,
1165}
1166
1167/// A new run continuing a failed run from its recorded activity boundary.
1168#[derive(Clone, Debug, PartialEq)]
1169pub struct WorkflowRedriveResult {
1170    pub workflow_id: String,
1171    pub source_run_id: String,
1172    pub run_id: String,
1173    pub resume_step_sequence: u64,
1174    pub raw: Value,
1175}
1176
1177/// A stable rejection returned by instance- or selected-run lifecycle commands.
1178#[derive(Clone, Debug, Error)]
1179#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1180pub struct WorkflowCommandRejection {
1181    pub command: WorkflowCommandKind,
1182    pub status: u16,
1183    pub reason: String,
1184    pub message: String,
1185    pub workflow_id: String,
1186    pub run_id: Option<String>,
1187    pub target_scope: Option<String>,
1188    pub body: Value,
1189}
1190
1191/// Stable terminal categories returned by [`WorkflowHandle::result`].
1192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1193pub enum WorkflowTerminalKind {
1194    Failed,
1195    Cancelled,
1196    Terminated,
1197    TimedOut,
1198}
1199
1200/// A typed terminal workflow outcome with durable identity and failure metadata.
1201///
1202/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1203/// of parsing its display representation. Fields remain `None` when an older
1204/// server did not publish that metadata.
1205#[derive(Clone, Debug, Error)]
1206#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1207pub struct WorkflowTerminalOutcome {
1208    pub kind: WorkflowTerminalKind,
1209    pub workflow_id: String,
1210    pub run_id: Option<String>,
1211    pub reason: String,
1212    pub failure_category: Option<String>,
1213    pub failure_id: Option<String>,
1214    pub exception_type: Option<String>,
1215    pub exception_class: Option<String>,
1216    pub non_retryable: Option<bool>,
1217    pub message: Option<String>,
1218    pub exception: Option<Value>,
1219    pub raw: Value,
1220}
1221
1222/// A worker-side activity settlement or heartbeat rejected by durable state.
1223#[derive(Clone, Debug, Error)]
1224#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1225pub struct ActivityTaskRejection {
1226    pub operation: String,
1227    pub status: u16,
1228    pub reason: String,
1229    pub task_id: String,
1230    pub activity_attempt_id: String,
1231    pub cancel_requested: bool,
1232    pub can_continue: Option<bool>,
1233    pub run_closed_reason: Option<String>,
1234    pub body: Value,
1235}
1236
1237/// Stable validation categories for [`ActivityOptions`].
1238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1239pub enum ActivityOptionsErrorKind {
1240    EmptyTaskQueue,
1241    EmptyRetryPolicy,
1242    InvalidMaxAttempts,
1243    BackoffWithoutRetryBudget,
1244    TooManyBackoffIntervals,
1245    InvalidBackoffCoefficient,
1246    BackoffGenerationTooLarge,
1247    BackoffOverflow,
1248    EmptyNonRetryableErrorType,
1249    TimeoutNotPositive,
1250    MissingTotalTimeout,
1251    TimeoutOverflow,
1252    TimeoutOrder,
1253}
1254
1255/// A machine-readable activity-options validation failure.
1256#[derive(Clone, Debug, Error, PartialEq, Eq)]
1257#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1258pub struct ActivityOptionsError {
1259    pub kind: ActivityOptionsErrorKind,
1260    pub field: Option<&'static str>,
1261    pub message: String,
1262}
1263
1264impl ActivityOptionsError {
1265    fn new(
1266        kind: ActivityOptionsErrorKind,
1267        field: Option<&'static str>,
1268        message: impl Into<String>,
1269    ) -> Self {
1270        Self {
1271            kind,
1272            field,
1273            message: message.into(),
1274        }
1275    }
1276}
1277
1278/// Stable terminal categories returned when an awaited activity does not succeed.
1279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1280pub enum ActivityFailureKind {
1281    Failed,
1282    Cancelled,
1283    TimedOut,
1284}
1285
1286/// A stable, machine-readable terminal activity failure.
1287///
1288/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1289/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1290#[derive(Clone, Debug, Error, PartialEq)]
1291#[error("activity failed ({reason}): {message}")]
1292pub struct ActivityFailure {
1293    pub kind: ActivityFailureKind,
1294    pub reason: String,
1295    pub message: String,
1296    pub activity_execution_id: Option<String>,
1297    pub activity_attempt_id: Option<String>,
1298    pub activity_type: Option<String>,
1299    pub activity_class: Option<String>,
1300    pub attempt_number: Option<u64>,
1301    pub failure_id: Option<String>,
1302    pub failure_category: Option<String>,
1303    pub timeout_kind: Option<String>,
1304    pub non_retryable: bool,
1305    pub exception_type: Option<String>,
1306    pub exception_class: Option<String>,
1307    pub code: Option<Value>,
1308    pub exception: Option<Value>,
1309}
1310
1311/// Stable terminal categories returned when an awaited child does not succeed.
1312#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1313pub enum ChildWorkflowFailureKind {
1314    Failed,
1315    Cancelled,
1316    Terminated,
1317}
1318
1319/// A stable, machine-readable child workflow failure delivered to its parent.
1320///
1321/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1322/// of parsing the display message. Child and parent identifiers retain the
1323/// relationship recorded in durable history across worker restarts.
1324#[derive(Clone, Debug, Error)]
1325#[error("child workflow failed ({reason}): {message}")]
1326pub struct ChildWorkflowFailure {
1327    pub kind: ChildWorkflowFailureKind,
1328    pub reason: String,
1329    pub message: String,
1330    pub parent_workflow_id: Option<String>,
1331    pub parent_workflow_run_id: Option<String>,
1332    pub child_workflow_id: Option<String>,
1333    pub child_workflow_run_id: Option<String>,
1334    pub child_workflow_type: Option<String>,
1335    pub failure_id: Option<String>,
1336    pub failure_category: Option<String>,
1337    pub exception_type: Option<String>,
1338    pub exception_class: Option<String>,
1339    pub non_retryable: bool,
1340    pub code: Option<Value>,
1341    pub exception: Option<Value>,
1342}
1343
1344/// The identity of one durable workflow execution.
1345#[derive(Clone, Debug, PartialEq, Eq)]
1346pub struct WorkflowIdentity {
1347    pub workflow_id: Option<String>,
1348    pub run_id: Option<String>,
1349}
1350
1351/// A successful child result together with its durable parent-child identity.
1352#[derive(Clone, Debug, PartialEq)]
1353pub struct ChildWorkflowResult {
1354    pub parent: WorkflowIdentity,
1355    pub child: WorkflowIdentity,
1356    pub child_workflow_type: Option<String>,
1357    pub result: Value,
1358}
1359
1360/// Lossless successful child result for fixed Avro Value workflows.
1361#[derive(Clone, Debug, PartialEq)]
1362pub struct ChildWorkflowAvroResult {
1363    pub parent: WorkflowIdentity,
1364    pub child: WorkflowIdentity,
1365    pub child_workflow_type: Option<String>,
1366    pub result: AvroValue,
1367}
1368
1369/// Stable user-facing identity for one member of a durable selection group.
1370#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1371#[serde(untagged)]
1372pub enum SelectionKey {
1373    Index(usize),
1374    Name(String),
1375}
1376
1377impl From<usize> for SelectionKey {
1378    fn from(value: usize) -> Self {
1379        Self::Index(value)
1380    }
1381}
1382
1383impl From<String> for SelectionKey {
1384    fn from(value: String) -> Self {
1385        Self::Name(value)
1386    }
1387}
1388
1389impl From<&str> for SelectionKey {
1390    fn from(value: &str) -> Self {
1391        Self::Name(value.to_string())
1392    }
1393}
1394
1395/// Typed result of explicitly awaiting a cancelled non-winning operation.
1396#[derive(Clone, Debug, Error, PartialEq, Eq)]
1397#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1398pub struct DurableOperationCancelled {
1399    pub selection_group_id: String,
1400    pub member_key: SelectionKey,
1401    pub member_index: usize,
1402    pub operation_kind: String,
1403    pub operation_identity: String,
1404}
1405
1406/// Stable identity for one enclosing deterministic parallel group.
1407///
1408/// The same fields are attached to every ordinary activity, timer, or child
1409/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1410/// no Rust-specific wire command is introduced.
1411#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1412pub struct ParallelGroupMetadata {
1413    pub parallel_group_id: String,
1414    pub parallel_group_kind: String,
1415    pub parallel_group_base_sequence: u64,
1416    pub parallel_group_size: usize,
1417    pub parallel_group_index: usize,
1418    #[serde(default, skip_serializing_if = "Option::is_none")]
1419    pub parallel_group_mode: Option<String>,
1420    #[serde(default, skip_serializing_if = "Option::is_none")]
1421    pub selection_member_key: Option<SelectionKey>,
1422    #[serde(default, skip_serializing_if = "Option::is_none")]
1423    pub selection_member_index: Option<usize>,
1424    #[serde(default, skip_serializing_if = "Option::is_none")]
1425    pub selection_member_base_sequence: Option<u64>,
1426    #[serde(default, skip_serializing_if = "Option::is_none")]
1427    pub selection_member_size: Option<usize>,
1428    #[serde(default, skip_serializing_if = "Option::is_none")]
1429    pub selection_member_kind: Option<String>,
1430}
1431
1432/// One input-ordered result returned by [`WorkflowContext::parallel`].
1433#[derive(Clone, Debug, PartialEq)]
1434pub enum ParallelResult {
1435    Activity(Value),
1436    ChildWorkflow(ChildWorkflowResult),
1437    Timer,
1438    Signal(Vec<Value>),
1439    Condition(ConditionWaitResult),
1440    Group(Vec<ParallelResult>),
1441}
1442
1443/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1444#[derive(Clone, Debug, PartialEq)]
1445pub enum ParallelAvroResult {
1446    Activity(AvroValue),
1447    ChildWorkflow(ChildWorkflowAvroResult),
1448    Timer,
1449    Signal(Vec<AvroValue>),
1450    Condition(ConditionWaitResult),
1451    Group(Vec<ParallelAvroResult>),
1452}
1453
1454impl ParallelAvroResult {
1455    fn into_json_result(self) -> Result<ParallelResult> {
1456        match self {
1457            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1458            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1459                parent: result.parent,
1460                child: result.child,
1461                child_workflow_type: result.child_workflow_type,
1462                result: result.result.into_json()?,
1463            })),
1464            Self::Timer => Ok(ParallelResult::Timer),
1465            Self::Signal(values) => Ok(ParallelResult::Signal(
1466                values
1467                    .into_iter()
1468                    .map(AvroValue::into_json)
1469                    .collect::<Result<Vec<_>>>()?,
1470            )),
1471            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1472            Self::Group(results) => Ok(ParallelResult::Group(
1473                results
1474                    .into_iter()
1475                    .map(Self::into_json_result)
1476                    .collect::<Result<Vec<_>>>()?,
1477            )),
1478        }
1479    }
1480}
1481
1482/// One successful leaf retained when another parallel member failed.
1483#[derive(Clone, Debug, PartialEq)]
1484pub struct ParallelCompletion {
1485    pub member_path: Vec<usize>,
1486    pub result: ParallelResult,
1487}
1488
1489/// A deterministic join failed after some siblings had already completed.
1490///
1491/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1492/// error. `completed` is declaration ordered and contains only durable
1493/// successes observed in the same replay. Late sibling completions can add
1494/// entries on a later replay without changing `member_path` or the selected
1495/// positional failure.
1496#[derive(Debug, Error)]
1497#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1498pub struct ParallelFailure {
1499    pub group_id: String,
1500    pub member_path: Vec<usize>,
1501    pub group_path: Vec<ParallelGroupMetadata>,
1502    pub completed: Vec<ParallelCompletion>,
1503    #[source]
1504    pub cause: Box<Error>,
1505}
1506
1507/// Stable validation error returned before an invalid group emits commands.
1508#[derive(Clone, Debug, Error, PartialEq, Eq)]
1509#[error("invalid deterministic parallel group ({reason}): {message}")]
1510pub struct ParallelGroupError {
1511    pub reason: &'static str,
1512    pub member_path: Vec<usize>,
1513    pub message: String,
1514}
1515
1516/// Cooperative workflow cancellation observed at an author-controlled point.
1517#[derive(Clone, Debug, Error, PartialEq, Eq)]
1518#[error("workflow cancellation was requested")]
1519pub struct WorkflowCancellationRequested;
1520
1521/// A forward saga failure followed by a terminal compensation failure.
1522#[derive(Debug, Error)]
1523#[error(
1524    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1525)]
1526pub struct SagaCompensationFailure {
1527    pub initiating_failure: Box<Error>,
1528    pub compensation_failure: Box<Error>,
1529    pub compensation_activity_type: String,
1530    pub compensation_registration_order: usize,
1531}
1532
1533/// Server behavior when a parent closes while its child is still open.
1534#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1535pub enum ParentClosePolicy {
1536    #[default]
1537    Abandon,
1538    /// Legacy terminal cancellation without cooperative cleanup.
1539    RequestCancel,
1540    /// Request cooperative cleanup with the original lineage and deadline.
1541    RequestCancellation,
1542    Terminate,
1543}
1544
1545impl ParentClosePolicy {
1546    fn as_str(self) -> &'static str {
1547        match self {
1548            Self::Abandon => "abandon",
1549            Self::RequestCancel => "request_cancel",
1550            Self::RequestCancellation => "request_cancellation",
1551            Self::Terminate => "terminate",
1552        }
1553    }
1554}
1555
1556/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1557#[non_exhaustive]
1558#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1559pub enum CancellationPolicy {
1560    /// Request cancellation and continue without waiting. Historical Activity default.
1561    TryCancel,
1562    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1563    WaitCancellationCompleted,
1564    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1565    #[default]
1566    Abandon,
1567}
1568
1569impl CancellationPolicy {
1570    fn as_str(self) -> &'static str {
1571        match self {
1572            Self::TryCancel => "try_cancel",
1573            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1574            Self::Abandon => "abandon",
1575        }
1576    }
1577}
1578
1579/// Durable retry policy for one child workflow invocation.
1580#[derive(Clone, Debug, Default, PartialEq, Eq)]
1581pub struct ChildWorkflowRetryPolicy {
1582    pub max_attempts: Option<u32>,
1583    pub backoff_seconds: Vec<u64>,
1584    pub non_retryable_error_types: Vec<String>,
1585}
1586
1587/// Options recorded with a child-workflow command.
1588///
1589/// The task queue is mandatory so routing is explicit and replay-stable.
1590#[derive(Clone, Debug, PartialEq, Eq)]
1591pub struct ChildWorkflowOptions {
1592    pub task_queue: String,
1593    pub parent_close_policy: ParentClosePolicy,
1594    pub cancellation_policy: CancellationPolicy,
1595    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1596    pub execution_timeout_seconds: Option<u64>,
1597    pub run_timeout_seconds: Option<u64>,
1598}
1599
1600impl ChildWorkflowOptions {
1601    pub fn new(task_queue: impl Into<String>) -> Self {
1602        Self {
1603            task_queue: task_queue.into(),
1604            parent_close_policy: ParentClosePolicy::Abandon,
1605            cancellation_policy: CancellationPolicy::Abandon,
1606            retry_policy: None,
1607            execution_timeout_seconds: None,
1608            run_timeout_seconds: None,
1609        }
1610    }
1611
1612    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1613        self.parent_close_policy = policy;
1614        self
1615    }
1616
1617    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1618        self.cancellation_policy = policy;
1619        self
1620    }
1621
1622    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1623        self.retry_policy = Some(policy);
1624        self
1625    }
1626
1627    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1628        self.execution_timeout_seconds = Some(seconds);
1629        self
1630    }
1631
1632    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1633        self.run_timeout_seconds = Some(seconds);
1634        self
1635    }
1636}
1637
1638/// Backoff intervals for one durable activity retry policy.
1639#[derive(Clone, Debug, PartialEq, Eq)]
1640pub enum ActivityBackoff {
1641    /// Use these intervals between attempts. The server repeats the final
1642    /// interval if the retry budget contains more attempts than entries.
1643    /// All entries are retained, including those beyond the retry budget.
1644    Explicit(Vec<Duration>),
1645    /// Generate one interval for every retry using integer exponential growth.
1646    Exponential {
1647        initial_interval: Duration,
1648        coefficient: u32,
1649        maximum_interval: Option<Duration>,
1650    },
1651}
1652
1653/// Durable server-side retry policy for one activity execution.
1654#[derive(Clone, Debug, Default, PartialEq, Eq)]
1655pub struct ActivityRetryPolicy {
1656    pub max_attempts: Option<u32>,
1657    pub backoff: Option<ActivityBackoff>,
1658    pub non_retryable_error_types: Vec<String>,
1659}
1660
1661impl ActivityRetryPolicy {
1662    /// Start a policy with a finite attempt budget, including the first attempt.
1663    pub fn new(max_attempts: u32) -> Self {
1664        Self {
1665            max_attempts: Some(max_attempts),
1666            ..Self::default()
1667        }
1668    }
1669
1670    /// Preserve the complete explicit list independently of the attempt budget.
1671    /// Unused entries remain part of the policy compared during replay.
1672    /// Set explicit durable retry intervals. Each positive fractional second
1673    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
1674    /// second. Zero stays zero. Queue latency can delay the next attempt further.
1675    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1676        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1677        self
1678    }
1679
1680    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
1681    /// Each interval is capped by `maximum_interval`, when present, then rounded
1682    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
1683    /// Zero stays zero. This policy is separate from HTTP transport retries.
1684    pub fn exponential_backoff(
1685        mut self,
1686        initial_interval: Duration,
1687        coefficient: u32,
1688        maximum_interval: Option<Duration>,
1689    ) -> Self {
1690        self.backoff = Some(ActivityBackoff::Exponential {
1691            initial_interval,
1692            coefficient,
1693            maximum_interval,
1694        });
1695        self
1696    }
1697
1698    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1699        self.non_retryable_error_types.push(error_type.into());
1700        self
1701    }
1702
1703    pub fn non_retryable_error_types(
1704        mut self,
1705        error_types: impl IntoIterator<Item = impl Into<String>>,
1706    ) -> Self {
1707        self.non_retryable_error_types
1708            .extend(error_types.into_iter().map(Into::into));
1709        self
1710    }
1711}
1712
1713/// Options recorded atomically on one deterministic `schedule_activity` command.
1714///
1715/// Durations are rounded up to whole seconds when encoded, so the server never
1716/// receives a shorter timeout or backoff than the caller requested.
1717#[derive(Clone, Debug, Default, PartialEq, Eq)]
1718pub struct ActivityOptions {
1719    pub task_queue: Option<String>,
1720    pub retry_policy: Option<ActivityRetryPolicy>,
1721    pub start_to_close_timeout: Option<Duration>,
1722    pub schedule_to_start_timeout: Option<Duration>,
1723    pub schedule_to_close_timeout: Option<Duration>,
1724    pub heartbeat_timeout: Option<Duration>,
1725    pub cancellation_policy: Option<CancellationPolicy>,
1726}
1727
1728impl ActivityOptions {
1729    pub fn new() -> Self {
1730        Self::default()
1731    }
1732
1733    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1734        self.task_queue = Some(task_queue.into());
1735        self
1736    }
1737
1738    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1739        self.retry_policy = Some(policy);
1740        self
1741    }
1742
1743    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1744        self.start_to_close_timeout = Some(timeout);
1745        self
1746    }
1747
1748    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1749        self.schedule_to_start_timeout = Some(timeout);
1750        self
1751    }
1752
1753    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1754        self.schedule_to_close_timeout = Some(timeout);
1755        self
1756    }
1757
1758    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1759        self.heartbeat_timeout = Some(timeout);
1760        self
1761    }
1762
1763    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1764        self.cancellation_policy = Some(policy);
1765        self
1766    }
1767
1768    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1769        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1770            && self.schedule_to_close_timeout.is_none()
1771        {
1772            return Err(ActivityOptionsError::new(
1773                ActivityOptionsErrorKind::MissingTotalTimeout,
1774                Some("schedule_to_close_timeout"),
1775                "remote Activity Abandon requires a finite positive total timeout",
1776            ));
1777        }
1778        if self
1779            .task_queue
1780            .as_deref()
1781            .is_some_and(|queue| queue.trim().is_empty())
1782        {
1783            return Err(ActivityOptionsError::new(
1784                ActivityOptionsErrorKind::EmptyTaskQueue,
1785                Some("task_queue"),
1786                "task_queue must not be empty",
1787            ));
1788        }
1789
1790        for (field, value) in [
1791            ("start_to_close_timeout", self.start_to_close_timeout),
1792            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1793            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1794            ("heartbeat_timeout", self.heartbeat_timeout),
1795        ] {
1796            if value.is_some_and(|value| value.is_zero()) {
1797                return Err(ActivityOptionsError::new(
1798                    ActivityOptionsErrorKind::TimeoutNotPositive,
1799                    Some(field),
1800                    format!("{field} must be positive"),
1801                ));
1802            }
1803        }
1804
1805        validate_timeout_order(
1806            "heartbeat_timeout",
1807            self.heartbeat_timeout,
1808            "start_to_close_timeout",
1809            self.start_to_close_timeout,
1810        )?;
1811        validate_timeout_order(
1812            "start_to_close_timeout",
1813            self.start_to_close_timeout,
1814            "schedule_to_close_timeout",
1815            self.schedule_to_close_timeout,
1816        )?;
1817        validate_timeout_order(
1818            "schedule_to_start_timeout",
1819            self.schedule_to_start_timeout,
1820            "schedule_to_close_timeout",
1821            self.schedule_to_close_timeout,
1822        )?;
1823
1824        Ok(ValidatedActivityOptions {
1825            task_queue: self.task_queue.clone(),
1826            retry_policy: self
1827                .retry_policy
1828                .as_ref()
1829                .map(validate_activity_retry_policy)
1830                .transpose()?,
1831            start_to_close_timeout: timeout_seconds(
1832                "start_to_close_timeout",
1833                self.start_to_close_timeout,
1834            )?,
1835            schedule_to_start_timeout: timeout_seconds(
1836                "schedule_to_start_timeout",
1837                self.schedule_to_start_timeout,
1838            )?,
1839            schedule_to_close_timeout: timeout_seconds(
1840                "schedule_to_close_timeout",
1841                self.schedule_to_close_timeout,
1842            )?,
1843            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1844            cancellation_policy: self.cancellation_policy,
1845        })
1846    }
1847}
1848
1849/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1850///
1851/// Constructors capture arguments but perform no I/O. The join validates the
1852/// complete tree, attaches the existing parallel-group metadata to every
1853/// ordinary command, schedules all leaves, and then suspends.
1854pub enum ParallelOperation {
1855    Activity {
1856        activity_type: String,
1857        options: ActivityOptions,
1858        arguments: Result<AvroValue>,
1859    },
1860    ChildWorkflow {
1861        workflow_type: String,
1862        options: ChildWorkflowOptions,
1863        arguments: Result<AvroValue>,
1864    },
1865    Timer(Duration),
1866    Signal(String),
1867    Condition {
1868        options: ConditionWaitOptions,
1869        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1870    },
1871    Group(Vec<ParallelOperation>),
1872}
1873
1874impl ParallelOperation {
1875    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1876        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1877    }
1878
1879    pub fn activity_with_options<T: Serialize>(
1880        activity_type: impl Into<String>,
1881        options: ActivityOptions,
1882        args: T,
1883    ) -> Self {
1884        Self::Activity {
1885            activity_type: activity_type.into(),
1886            options,
1887            arguments: AvroValue::from_serialize(&args),
1888        }
1889    }
1890
1891    pub fn child_workflow<T: Serialize>(
1892        workflow_type: impl Into<String>,
1893        options: ChildWorkflowOptions,
1894        args: T,
1895    ) -> Self {
1896        Self::ChildWorkflow {
1897            workflow_type: workflow_type.into(),
1898            options,
1899            arguments: AvroValue::from_serialize(&args),
1900        }
1901    }
1902
1903    pub fn timer(duration: Duration) -> Self {
1904        Self::Timer(duration)
1905    }
1906
1907    pub fn signal(signal_name: impl Into<String>) -> Self {
1908        Self::Signal(signal_name.into())
1909    }
1910
1911    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1912    where
1913        F: Fn() -> Result<bool> + Send + 'static,
1914    {
1915        Self::Condition {
1916            options,
1917            predicate: Box::new(predicate),
1918        }
1919    }
1920
1921    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1922        Self::Group(operations)
1923    }
1924}
1925
1926#[derive(Clone, Debug)]
1927struct ValidatedActivityOptions {
1928    task_queue: Option<String>,
1929    retry_policy: Option<Value>,
1930    start_to_close_timeout: Option<u64>,
1931    schedule_to_start_timeout: Option<u64>,
1932    schedule_to_close_timeout: Option<u64>,
1933    heartbeat_timeout: Option<u64>,
1934    cancellation_policy: Option<CancellationPolicy>,
1935}
1936
1937fn validate_timeout_order(
1938    smaller_name: &'static str,
1939    smaller: Option<Duration>,
1940    larger_name: &'static str,
1941    larger: Option<Duration>,
1942) -> std::result::Result<(), ActivityOptionsError> {
1943    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1944        return Err(ActivityOptionsError::new(
1945            ActivityOptionsErrorKind::TimeoutOrder,
1946            Some(smaller_name),
1947            format!("{smaller_name} must be <= {larger_name}"),
1948        ));
1949    }
1950    Ok(())
1951}
1952
1953fn timeout_seconds(
1954    field: &'static str,
1955    value: Option<Duration>,
1956) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1957    value
1958        .map(|value| {
1959            activity_protocol_seconds(value).ok_or_else(|| {
1960                ActivityOptionsError::new(
1961                    ActivityOptionsErrorKind::TimeoutOverflow,
1962                    Some(field),
1963                    format!("{field} is too large for the worker protocol"),
1964                )
1965            })
1966        })
1967        .transpose()
1968}
1969
1970fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1971    value
1972        .as_secs()
1973        .checked_add(u64::from(value.subsec_nanos() > 0))
1974}
1975
1976fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1977    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1978}
1979
1980fn validate_activity_retry_policy(
1981    policy: &ActivityRetryPolicy,
1982) -> std::result::Result<Value, ActivityOptionsError> {
1983    if policy.max_attempts.is_none()
1984        && policy.backoff.is_none()
1985        && policy.non_retryable_error_types.is_empty()
1986    {
1987        return Err(ActivityOptionsError::new(
1988            ActivityOptionsErrorKind::EmptyRetryPolicy,
1989            Some("retry_policy"),
1990            "retry_policy must configure at least one field",
1991        ));
1992    }
1993    if policy.max_attempts == Some(0) {
1994        return Err(ActivityOptionsError::new(
1995            ActivityOptionsErrorKind::InvalidMaxAttempts,
1996            Some("retry_policy.max_attempts"),
1997            "max_attempts must be >= 1",
1998        ));
1999    }
2000    if policy
2001        .non_retryable_error_types
2002        .iter()
2003        .any(|error_type| error_type.trim().is_empty())
2004    {
2005        return Err(ActivityOptionsError::new(
2006            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2007            Some("retry_policy.non_retryable_error_types"),
2008            "non_retryable_error_types must not contain empty values",
2009        ));
2010    }
2011
2012    let backoff_seconds = match &policy.backoff {
2013        None => None,
2014        Some(backoff) => {
2015            let max_attempts = policy.max_attempts.ok_or_else(|| {
2016                ActivityOptionsError::new(
2017                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2018                    Some("retry_policy.backoff"),
2019                    "backoff requires max_attempts",
2020                )
2021            })?;
2022            let retry_count = max_attempts.saturating_sub(1) as usize;
2023            let intervals = match backoff {
2024                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2025                ActivityBackoff::Exponential {
2026                    initial_interval,
2027                    coefficient,
2028                    maximum_interval,
2029                } => {
2030                    if *coefficient < 1 {
2031                        return Err(ActivityOptionsError::new(
2032                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2033                            Some("retry_policy.backoff.coefficient"),
2034                            "backoff coefficient must be >= 1",
2035                        ));
2036                    }
2037                    if retry_count > 10_000 {
2038                        return Err(ActivityOptionsError::new(
2039                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2040                            Some("retry_policy.max_attempts"),
2041                            "generated backoff supports at most 10000 retry intervals",
2042                        ));
2043                    }
2044                    let mut current = *initial_interval;
2045                    let mut intervals = Vec::with_capacity(retry_count);
2046                    for _ in 0..retry_count {
2047                        let interval = maximum_interval
2048                            .map(|maximum| current.min(maximum))
2049                            .unwrap_or(current);
2050                        intervals.push(interval);
2051                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2052                            break;
2053                        }
2054                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2055                            ActivityOptionsError::new(
2056                                ActivityOptionsErrorKind::BackoffOverflow,
2057                                Some("retry_policy.backoff"),
2058                                "generated backoff interval overflowed",
2059                            )
2060                        })?;
2061                    }
2062                    intervals
2063                }
2064            };
2065            Some(
2066                intervals
2067                    .into_iter()
2068                    .map(|interval| {
2069                        activity_protocol_seconds(interval).ok_or_else(|| {
2070                            ActivityOptionsError::new(
2071                                ActivityOptionsErrorKind::BackoffOverflow,
2072                                Some("retry_policy.backoff"),
2073                                "backoff interval is too large for the worker protocol",
2074                            )
2075                        })
2076                    })
2077                    .collect::<std::result::Result<Vec<_>, _>>()?,
2078            )
2079        }
2080    };
2081
2082    let mut encoded = serde_json::Map::new();
2083    if let Some(max_attempts) = policy.max_attempts {
2084        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2085    }
2086    if let Some(backoff_seconds) = backoff_seconds {
2087        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2088    }
2089    if !policy.non_retryable_error_types.is_empty() {
2090        let mut canonical_error_types = Vec::new();
2091        for error_type in policy
2092            .non_retryable_error_types
2093            .iter()
2094            .map(|error_type| error_type.trim())
2095        {
2096            if !canonical_error_types.contains(&error_type) {
2097                canonical_error_types.push(error_type);
2098            }
2099        }
2100        encoded.insert(
2101            "non_retryable_error_types".to_string(),
2102            json!(canonical_error_types),
2103        );
2104    }
2105    Ok(Value::Object(encoded))
2106}
2107
2108/// A stable, machine-readable failure raised when workflow code no longer
2109/// reconstructs the durable command stream recorded in history.
2110#[derive(Clone, Debug, Error)]
2111#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2112pub struct ReplayFailure {
2113    pub reason: String,
2114    pub sequence: Option<u64>,
2115    pub expected: Option<String>,
2116    pub actual: Option<String>,
2117    pub message: String,
2118}
2119
2120impl ReplayFailure {
2121    fn new(
2122        reason: impl Into<String>,
2123        sequence: Option<u64>,
2124        expected: Option<String>,
2125        actual: Option<String>,
2126        message: impl Into<String>,
2127    ) -> Self {
2128        Self {
2129            reason: reason.into(),
2130            sequence,
2131            expected,
2132            actual,
2133            message: message.into(),
2134        }
2135    }
2136}
2137
2138/// A stable, machine-readable workflow query or query-task settlement failure.
2139#[derive(Clone, Debug, Error)]
2140#[error("query failed ({reason}, HTTP {status}): {message}")]
2141pub struct QueryFailure {
2142    pub status: u16,
2143    pub reason: String,
2144    pub message: String,
2145    pub body: Value,
2146}
2147
2148/// A stable failure returned when a server rejects an SDK protocol version.
2149#[derive(Clone, Debug, Error)]
2150#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2151pub struct ProtocolFailure {
2152    pub status: u16,
2153    pub reason: String,
2154    pub message: String,
2155    pub supported_version: Option<String>,
2156    pub requested_version: Option<String>,
2157    pub body: Value,
2158}
2159
2160#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2161pub struct PayloadEnvelope {
2162    pub codec: String,
2163    pub blob: String,
2164}
2165
2166impl PayloadEnvelope {
2167    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2168        encode_payload(value, DEFAULT_CODEC)
2169    }
2170
2171    /// Encode an explicit typed value, including the bytes branch that JSON
2172    /// serialization cannot represent.
2173    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2174        encode_avro_value(value)
2175    }
2176}
2177
2178/// Native adapter for the fixed language-neutral Avro Value schema.
2179#[derive(Clone, Debug)]
2180pub enum AvroValue {
2181    Null,
2182    Boolean(bool),
2183    Long(i64),
2184    Double(f64),
2185    Bytes(Vec<u8>),
2186    String(String),
2187    Array(Vec<AvroValue>),
2188    Map(BTreeMap<String, AvroValue>),
2189}
2190
2191impl PartialEq for AvroValue {
2192    fn eq(&self, other: &Self) -> bool {
2193        match (self, other) {
2194            (Self::Null, Self::Null) => true,
2195            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2196            (Self::Long(left), Self::Long(right)) => left == right,
2197            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2198            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2199            (Self::String(left), Self::String(right)) => left == right,
2200            (Self::Array(left), Self::Array(right)) => left == right,
2201            (Self::Map(left), Self::Map(right)) => left == right,
2202            _ => false,
2203        }
2204    }
2205}
2206
2207impl AvroValue {
2208    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2209        Self::from_serde_value(
2210            serde_value::to_value(value).map_err(|error| {
2211                Error::Codec(format!("could not adapt value for Avro: {error}"))
2212            })?,
2213        )
2214    }
2215
2216    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2217        use serde_value::Value as SerdeValue;
2218
2219        match value {
2220            SerdeValue::Unit => Ok(Self::Null),
2221            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2222            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2223            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2224            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2225            SerdeValue::I64(value) => Ok(Self::Long(value)),
2226            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2227            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2228            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2229            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2230                Error::Codec(
2231                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2232                        .to_string(),
2233                )
2234            }),
2235            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2236            SerdeValue::F64(value) => Self::finite_double(value),
2237            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2238            SerdeValue::String(value) => Ok(Self::String(value)),
2239            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2240            SerdeValue::Option(None) => Ok(Self::Null),
2241            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2242                Self::from_serde_value(*value)
2243            }
2244            SerdeValue::Seq(values) => values
2245                .into_iter()
2246                .map(Self::from_serde_value)
2247                .collect::<Result<Vec<_>>>()
2248                .map(Self::Array),
2249            SerdeValue::Map(values) => values
2250                .into_iter()
2251                .map(|(key, value)| {
2252                    let SerdeValue::String(key) = key else {
2253                        return Err(Error::Codec(
2254                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2255                        ));
2256                    };
2257
2258                    Ok((key, Self::from_serde_value(value)?))
2259                })
2260                .collect::<Result<BTreeMap<_, _>>>()
2261                .map(Self::Map),
2262        }
2263    }
2264
2265    fn finite_double(value: f64) -> Result<Self> {
2266        if !value.is_finite() {
2267            return Err(Error::Codec(
2268                "non_finite_float: Avro Value doubles must be finite".to_string(),
2269            ));
2270        }
2271
2272        Ok(Self::Double(value))
2273    }
2274
2275    fn into_json(self) -> Result<Value> {
2276        match self {
2277            Self::Null => Ok(Value::Null),
2278            Self::Boolean(value) => Ok(Value::Bool(value)),
2279            Self::Long(value) => Ok(Value::Number(value.into())),
2280            Self::Double(value) => serde_json::Number::from_f64(value)
2281                .map(Value::Number)
2282                .ok_or_else(|| {
2283                    Error::Codec(
2284                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2285                    )
2286                }),
2287            Self::Bytes(value) => Ok(json!({
2288                "$type": "bytes",
2289                "base64": BASE64.encode(value),
2290            })),
2291            Self::String(value) => Ok(Value::String(value)),
2292            Self::Array(values) => values
2293                .into_iter()
2294                .map(Self::into_json)
2295                .collect::<Result<Vec<_>>>()
2296                .map(Value::Array),
2297            Self::Map(values) => values
2298                .into_iter()
2299                .map(|(key, value)| Ok((key, value.into_json()?)))
2300                .collect::<Result<serde_json::Map<_, _>>>()
2301                .map(Value::Object),
2302        }
2303    }
2304
2305    fn into_serde_value(self) -> serde_value::Value {
2306        use serde_value::Value as SerdeValue;
2307
2308        match self {
2309            Self::Null => SerdeValue::Unit,
2310            Self::Boolean(value) => SerdeValue::Bool(value),
2311            Self::Long(value) => SerdeValue::I64(value),
2312            Self::Double(value) => SerdeValue::F64(value),
2313            Self::Bytes(value) => SerdeValue::Bytes(value),
2314            Self::String(value) => SerdeValue::String(value),
2315            Self::Array(values) => {
2316                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2317            }
2318            Self::Map(values) => SerdeValue::Map(
2319                values
2320                    .into_iter()
2321                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2322                    .collect(),
2323            ),
2324        }
2325    }
2326
2327    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2328        self.into_serde_value().deserialize_into().map_err(|error| {
2329            Error::Codec(format!(
2330                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2331            ))
2332        })
2333    }
2334}
2335
2336impl Serialize for AvroValue {
2337    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2338    where
2339        S: Serializer,
2340    {
2341        match self {
2342            Self::Null => serializer.serialize_unit(),
2343            Self::Boolean(value) => serializer.serialize_bool(*value),
2344            Self::Long(value) => serializer.serialize_i64(*value),
2345            Self::Double(value) => serializer.serialize_f64(*value),
2346            Self::Bytes(value) => serializer.serialize_bytes(value),
2347            Self::String(value) => serializer.serialize_str(value),
2348            Self::Array(values) => {
2349                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2350                for value in values {
2351                    sequence.serialize_element(value)?;
2352                }
2353                sequence.end()
2354            }
2355            Self::Map(values) => {
2356                let mut map = serializer.serialize_map(Some(values.len()))?;
2357                for (key, value) in values {
2358                    map.serialize_entry(key, value)?;
2359                }
2360                map.end()
2361            }
2362        }
2363    }
2364}
2365
2366pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2367    let datum = avro_value_to_datum(value)?;
2368    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2369        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2370    let mut bytes = Vec::with_capacity(datum.len() + 10);
2371    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2372    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2373    bytes.extend_from_slice(&datum);
2374    Ok(PayloadEnvelope {
2375        codec: DEFAULT_CODEC.to_string(),
2376        blob: BASE64.encode(bytes),
2377    })
2378}
2379
2380pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2381    if envelope.codec != DEFAULT_CODEC {
2382        return Err(unsupported_payload_codec(&envelope.codec));
2383    }
2384    decode_avro_value_blob(&envelope.blob)
2385}
2386
2387pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2388    let blob = match codec {
2389        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2390        other => return Err(unsupported_payload_codec(other)),
2391    };
2392
2393    Ok(PayloadEnvelope {
2394        codec: codec.to_string(),
2395        blob,
2396    })
2397}
2398
2399pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2400    match envelope.codec.as_str() {
2401        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2402        other => Err(unsupported_payload_codec(other)),
2403    }
2404}
2405
2406fn handler_type_error<T>(
2407    handler_kind: HandlerKind,
2408    handler_name: &str,
2409    value_kind: HandlerValueKind,
2410    message: impl Into<String>,
2411) -> Error {
2412    Error::HandlerType {
2413        handler_kind,
2414        handler_name: handler_name.to_string(),
2415        value_kind,
2416        rust_type: type_name::<T>(),
2417        message: message.into(),
2418    }
2419}
2420
2421fn decode_handler_input<T: DeserializeOwned>(
2422    arguments: AvroValue,
2423    handler_kind: HandlerKind,
2424    handler_name: &str,
2425) -> Result<T> {
2426    let argument = match arguments {
2427        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2428            arguments.pop().expect("one typed handler argument")
2429        }
2430        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2431        AvroValue::Array(arguments) => {
2432            return Err(handler_type_error::<T>(
2433                handler_kind,
2434                handler_name,
2435                HandlerValueKind::Input,
2436                format!(
2437                    "typed handlers accept one request value, but the task carried {} arguments",
2438                    arguments.len()
2439                ),
2440            ));
2441        }
2442        argument => argument,
2443    };
2444
2445    argument.deserialize().map_err(|error| {
2446        handler_type_error::<T>(
2447            handler_kind,
2448            handler_name,
2449            HandlerValueKind::Input,
2450            error.to_string(),
2451        )
2452    })
2453}
2454
2455fn decode_workflow_entry<T: DeserializeOwned>(
2456    arguments: AvroValue,
2457    workflow_type: &str,
2458) -> Result<T> {
2459    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2460        // Serde errors may contain recorded values. The entry refusal exposes
2461        // only the registered workflow and expected Rust type.
2462        handler_type_error::<T>(
2463            HandlerKind::Workflow,
2464            workflow_type,
2465            HandlerValueKind::Input,
2466            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2467        )
2468    })
2469}
2470
2471fn encode_handler_result<T: Serialize>(
2472    result: &T,
2473    handler_kind: HandlerKind,
2474    handler_name: &str,
2475) -> Result<AvroValue> {
2476    AvroValue::from_serialize(result).map_err(|error| {
2477        handler_type_error::<T>(
2478            handler_kind,
2479            handler_name,
2480            HandlerValueKind::Result,
2481            error.to_string(),
2482        )
2483    })
2484}
2485
2486fn decode_handler_result<T: DeserializeOwned>(
2487    result: AvroValue,
2488    handler_kind: HandlerKind,
2489    handler_name: &str,
2490) -> Result<T> {
2491    result.deserialize().map_err(|error| {
2492        handler_type_error::<T>(
2493            handler_kind,
2494            handler_name,
2495            HandlerValueKind::Result,
2496            error.to_string(),
2497        )
2498    })
2499}
2500
2501#[cfg(test)]
2502fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2503    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2504}
2505
2506fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2507    validate_payload_codec(fallback_codec)?;
2508
2509    if value.is_null() {
2510        return Ok(Value::Null);
2511    }
2512
2513    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2514        return decode_blob(blob, codec);
2515    }
2516
2517    if let Some(blob) = value.as_str() {
2518        return decode_blob(blob, fallback_codec);
2519    }
2520
2521    Err(untagged_payload_value())
2522}
2523
2524fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2525    let envelope = match codec {
2526        DEFAULT_CODEC => encode_avro_value(value)?,
2527        other => return Err(unsupported_payload_codec(other)),
2528    };
2529    Ok(serde_json::to_value(envelope)?)
2530}
2531
2532fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2533    validate_payload_codec(fallback_codec)?;
2534
2535    if value.is_null() {
2536        return Ok(AvroValue::Null);
2537    }
2538
2539    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2540        validate_payload_codec(codec)?;
2541        return decode_avro_value_blob(blob);
2542    }
2543
2544    if let Some(blob) = value.as_str() {
2545        return match fallback_codec {
2546            DEFAULT_CODEC => decode_avro_value_blob(blob),
2547            other => Err(unsupported_payload_codec(other)),
2548        };
2549    }
2550
2551    Err(untagged_payload_value())
2552}
2553
2554fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2555    match value {
2556        AvroValue::Null => AvroValue::Array(Vec::new()),
2557        AvroValue::Array(_) => value,
2558        other => AvroValue::Array(vec![other]),
2559    }
2560}
2561
2562fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2563    match codec {
2564        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2565        other => Err(unsupported_payload_codec(other)),
2566    }
2567}
2568
2569fn validate_payload_codec(codec: &str) -> Result<()> {
2570    match codec {
2571        DEFAULT_CODEC => Ok(()),
2572        MISSING_TASK_PAYLOAD_CODEC => {
2573            Err(invalid_task_payload_codec("task payload_codec is missing"))
2574        }
2575        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2576        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2577            "task payload_codec must be a string",
2578        )),
2579        other => Err(unsupported_payload_codec(other)),
2580    }
2581}
2582
2583fn invalid_task_payload_codec(reason: &str) -> Error {
2584    Error::Codec(format!(
2585        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2586    ))
2587}
2588
2589fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2590    let Some(object) = value.as_object() else {
2591        return Ok(None);
2592    };
2593    if !object.contains_key("codec") && !object.contains_key("blob") {
2594        return Ok(None);
2595    }
2596
2597    let codec = object
2598        .get("codec")
2599        .and_then(Value::as_str)
2600        .ok_or_else(invalid_payload_envelope)?;
2601    validate_payload_codec(codec)?;
2602    let blob = object
2603        .get("blob")
2604        .and_then(Value::as_str)
2605        .ok_or_else(invalid_payload_envelope)?;
2606    Ok(Some((codec, blob)))
2607}
2608
2609fn invalid_payload_envelope() -> Error {
2610    Error::Codec(
2611        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2612            .to_string(),
2613    )
2614}
2615
2616fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2617    for command in commands {
2618        let Some(command) = command.as_object() else {
2619            continue;
2620        };
2621        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2622            continue;
2623        };
2624        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2625            continue;
2626        };
2627
2628        if let Some(codec) = command.get("payload_codec") {
2629            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2630            validate_payload_codec(codec)?;
2631        }
2632
2633        let payload = command
2634            .get(payload_field)
2635            .ok_or_else(invalid_payload_envelope)?;
2636        if runtime_payloads::Reference::parse(payload)?.is_none() {
2637            validate_outbound_payload_envelope(payload)?;
2638        }
2639    }
2640    Ok(())
2641}
2642
2643fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2644    if commands.iter().any(|command| {
2645        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2646            && command
2647                .get("condition_wait_occurrence_id")
2648                .and_then(Value::as_str)
2649                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2650    }) {
2651        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2652    } else if commands.iter().any(|command| {
2653        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2654            && command.get("attribute_types").is_some()
2655    }) {
2656        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2657    } else if commands
2658        .iter()
2659        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2660    {
2661        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2662    } else if commands
2663        .iter()
2664        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2665    {
2666        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2667    } else if commands.iter().any(|command| {
2668        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2669    }) {
2670        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2671    } else {
2672        MINIMUM_WORKER_PROTOCOL_VERSION
2673    }
2674}
2675
2676fn workflow_completion_protocol_version_with_message_streams(
2677    commands: &[Value],
2678    has_message_stream_metadata: bool,
2679) -> &'static str {
2680    let command_protocol = workflow_completion_protocol_version(commands);
2681    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2682        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2683    } else {
2684        command_protocol
2685    }
2686}
2687
2688fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2689    match command_type {
2690        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2691        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2692        "start_service_operation" => Some("request_payload"),
2693        "upsert_memo" => Some("entries"),
2694        _ => None,
2695    }
2696}
2697
2698fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2699    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2700        return Err(untagged_payload_value());
2701    };
2702    validate_payload_codec(codec)?;
2703    decode_avro_value_blob(blob)?;
2704    Ok(())
2705}
2706
2707fn unsupported_payload_codec(codec: &str) -> Error {
2708    Error::Codec(format!(
2709        "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"
2710    ))
2711}
2712
2713fn untagged_payload_value() -> Error {
2714    Error::Codec(
2715        "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"
2716            .to_string(),
2717    )
2718}
2719
2720fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2721    let bytes = BASE64.decode(blob).map_err(|err| {
2722        Error::Codec(format!(
2723            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2724        ))
2725    })?;
2726
2727    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2728        return Err(unsupported_payload_codec("json"));
2729    }
2730
2731    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2732        return Err(Error::Codec(
2733            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2734        ));
2735    }
2736
2737    let fingerprint: [u8; 8] = bytes[2..10]
2738        .try_into()
2739        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2740    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2741        return Err(Error::Codec(format!(
2742            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2743            fingerprint
2744                .iter()
2745                .map(|byte| format!("{byte:02x}"))
2746                .collect::<String>()
2747        )));
2748    }
2749
2750    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2751    // The current fingerprint selects the current immutable schema, so reader
2752    // resolution would only re-walk the same recursive union. Future retained
2753    // writer fingerprints supply a distinct reader schema in this branch.
2754    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2755    if datum_reader.truncated {
2756        return Err(Error::Codec(
2757            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2758        ));
2759    }
2760    let datum = datum.map_err(|err| {
2761        Error::Codec(format!(
2762            "invalid_payload_framing: malformed Avro Value datum: {err}"
2763        ))
2764    })?;
2765    if datum_reader.remaining() != 0 {
2766        return Err(Error::Codec(format!(
2767            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2768            datum_reader.remaining()
2769        )));
2770    }
2771    avro_value_from_datum(datum)
2772}
2773
2774struct StrictAvroDatumReader<'a> {
2775    bytes: &'a [u8],
2776    offset: usize,
2777    truncated: bool,
2778}
2779
2780impl<'a> StrictAvroDatumReader<'a> {
2781    fn new(bytes: &'a [u8]) -> Self {
2782        Self {
2783            bytes,
2784            offset: 0,
2785            truncated: false,
2786        }
2787    }
2788
2789    fn remaining(&self) -> usize {
2790        self.bytes.len() - self.offset
2791    }
2792}
2793
2794impl Read for StrictAvroDatumReader<'_> {
2795    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2796        let count = buffer.len().min(self.remaining());
2797        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2798        self.offset += count;
2799        if count < buffer.len() {
2800            self.truncated = true;
2801        }
2802
2803        Ok(count)
2804    }
2805}
2806
2807fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2808    let branch = match value {
2809        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2810        AvroValue::Boolean(value) => AvroDatum::Union(
2811            1,
2812            Box::new(AvroDatum::Record(vec![(
2813                "boolean".to_string(),
2814                AvroDatum::Boolean(*value),
2815            )])),
2816        ),
2817        AvroValue::Long(value) => AvroDatum::Union(
2818            2,
2819            Box::new(AvroDatum::Record(vec![(
2820                "long".to_string(),
2821                AvroDatum::Long(*value),
2822            )])),
2823        ),
2824        AvroValue::Double(value) => {
2825            if !value.is_finite() {
2826                return Err(Error::Codec(
2827                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2828                ));
2829            }
2830            AvroDatum::Union(
2831                3,
2832                Box::new(AvroDatum::Record(vec![(
2833                    "double".to_string(),
2834                    AvroDatum::Double(*value),
2835                )])),
2836            )
2837        }
2838        AvroValue::Bytes(value) => AvroDatum::Union(
2839            4,
2840            Box::new(AvroDatum::Record(vec![(
2841                "bytes".to_string(),
2842                AvroDatum::Bytes(value.clone()),
2843            )])),
2844        ),
2845        AvroValue::String(value) => AvroDatum::Union(
2846            5,
2847            Box::new(AvroDatum::Record(vec![(
2848                "string".to_string(),
2849                AvroDatum::String(value.clone()),
2850            )])),
2851        ),
2852        AvroValue::Array(values) => AvroDatum::Union(
2853            6,
2854            Box::new(AvroDatum::Record(vec![(
2855                "items".to_string(),
2856                AvroDatum::Array(
2857                    values
2858                        .iter()
2859                        .map(avro_value_to_datum)
2860                        .collect::<Result<Vec<_>>>()?,
2861                ),
2862            )])),
2863        ),
2864        AvroValue::Map(values) => AvroDatum::Union(
2865            7,
2866            Box::new(AvroDatum::Record(vec![(
2867                "entries".to_string(),
2868                AvroDatum::Array(
2869                    values
2870                        .iter()
2871                        .map(|(key, value)| {
2872                            Ok(AvroDatum::Record(vec![
2873                                ("key".to_string(), AvroDatum::String(key.clone())),
2874                                ("value".to_string(), avro_value_to_datum(value)?),
2875                            ]))
2876                        })
2877                        .collect::<Result<Vec<_>>>()?,
2878                ),
2879            )])),
2880        ),
2881    };
2882    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2883}
2884
2885fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2886    let AvroDatum::Record(mut outer) = datum else {
2887        return Err(Error::Codec(
2888            "invalid_payload_framing: datum is not a Value record".to_string(),
2889        ));
2890    };
2891    let (_, branch) = outer
2892        .pop()
2893        .filter(|(name, _)| name == "value")
2894        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2895    let AvroDatum::Union(_, branch) = branch else {
2896        return Err(Error::Codec(
2897            "invalid_payload_framing: invalid Value union".to_string(),
2898        ));
2899    };
2900    match *branch {
2901        AvroDatum::Null => Ok(AvroValue::Null),
2902        AvroDatum::Record(mut fields) => {
2903            let (name, value) = fields.pop().ok_or_else(|| {
2904                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2905            })?;
2906            match (name.as_str(), value) {
2907                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2908                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2909                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2910                    Ok(AvroValue::Double(value))
2911                }
2912                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2913                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2914                ("items", AvroDatum::Array(values)) => values
2915                    .into_iter()
2916                    .map(avro_value_from_datum)
2917                    .collect::<Result<Vec<_>>>()
2918                    .map(AvroValue::Array),
2919                ("entries", AvroDatum::Map(values)) => values
2920                    .into_iter()
2921                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2922                    .collect::<Result<BTreeMap<_, _>>>()
2923                    .map(AvroValue::Map),
2924                _ => Err(Error::Codec(
2925                    "invalid_payload_framing: unknown Value branch".to_string(),
2926                )),
2927            }
2928        }
2929        _ => Err(Error::Codec(
2930            "invalid_payload_framing: invalid Value branch".to_string(),
2931        )),
2932    }
2933}
2934
2935fn avro_value_schema() -> Result<&'static Schema> {
2936    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2937        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2938            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2939    }) {
2940        Ok(schema) => Ok(schema),
2941        Err(message) => Err(Error::Codec(message.clone())),
2942    }
2943}
2944
2945fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2946    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2947        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2948        // have the same block representation when each ordered array record
2949        // contains the map key followed by its value, so this encoding-only
2950        // adaptation lets the official encoder retain BTreeMap wire order.
2951        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2952            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2953        let entries_schema = schema
2954            .pointer_mut("/fields/0/type/7/fields/0/type")
2955            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2956        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2957            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2958        }
2959        *entries_schema = json!({
2960            "type": "array",
2961            "items": {
2962                "type": "record",
2963                "name": "MapEntry",
2964                "fields": [
2965                    {"name": "key", "type": "string"},
2966                    {"name": "value", "type": "Value"}
2967                ]
2968            }
2969        });
2970        Schema::parse_str(&schema.to_string())
2971            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2972    }) {
2973        Ok(schema) => Ok(schema),
2974        Err(message) => Err(Error::Codec(message.clone())),
2975    }
2976}
2977
2978#[derive(Clone, Debug)]
2979pub struct Client {
2980    http: reqwest::Client,
2981    hydration_timeout: Duration,
2982    base_url: String,
2983    token: Option<String>,
2984    control_token: Option<String>,
2985    worker_token: Option<String>,
2986    namespace: String,
2987    max_external_payload_bytes: usize,
2988    worker_storage_admission: Option<WorkerStorageAdmission>,
2989    worker_task_slot: Option<Arc<worker_capacity::TaskSlotMarker>>,
2990    cooperative_worker_protocol: bool,
2991    worker_protocol_version: WorkerProtocolVersion,
2992    local_activities_enabled: bool,
2993    worker_sessions_enabled: bool,
2994    max_concurrent_worker_sessions: usize,
2995    worker_build_id: Option<String>,
2996    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2997    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2998    activity_lease_renewal_supported: Arc<AtomicBool>,
2999    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
3000    #[cfg(feature = "telemetry")]
3001    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
3002    #[cfg(feature = "telemetry")]
3003    observability_context_supported: Arc<AtomicBool>,
3004}
3005
3006impl Client {
3007    /// Configure optional propagation. Actual cluster discovery must advertise
3008    /// the exact supported capability before any command carries context.
3009    #[cfg(feature = "telemetry")]
3010    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3011        self.execution_telemetry = Some(telemetry);
3012        self
3013    }
3014
3015    #[cfg(feature = "telemetry")]
3016    fn with_observability_context(&self, mut body: Value) -> Value {
3017        if self.observability_context_supported.load(Ordering::SeqCst) {
3018            if let Some(context) = self
3019                .execution_telemetry
3020                .as_ref()
3021                .and_then(|telemetry| telemetry.capture())
3022            {
3023                body["observability_context"] = context;
3024            }
3025        }
3026        body
3027    }
3028
3029    #[cfg(not(feature = "telemetry"))]
3030    fn with_observability_context(&self, body: Value) -> Value {
3031        body
3032    }
3033
3034    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3035        Self::builder(base_url).build()
3036    }
3037
3038    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3039        ClientBuilder {
3040            base_url: base_url.into(),
3041            token: None,
3042            control_token: None,
3043            worker_token: None,
3044            namespace: "default".to_string(),
3045            timeout: Duration::from_secs(60),
3046            max_external_payload_bytes: 64 * 1024 * 1024,
3047            worker_protocol_version: WorkerProtocolVersion::default(),
3048            additional_root_certificates: Vec::new(),
3049        }
3050    }
3051
3052    pub async fn health(&self) -> Result<Value> {
3053        self.request_json(
3054            reqwest::Method::GET,
3055            "/health",
3056            RequestProtocol::ControlPlane,
3057            Option::<&Value>::None,
3058        )
3059        .await
3060    }
3061
3062    pub async fn cluster_info(&self) -> Result<Value> {
3063        let discovery: Value = self
3064            .request_json(
3065                reqwest::Method::GET,
3066                "/cluster/info",
3067                RequestProtocol::ControlPlane,
3068                Option::<&Value>::None,
3069            )
3070            .await?;
3071        self.observe_activity_lease_capabilities(
3072            &discovery["worker_protocol"]["server_capabilities"],
3073        );
3074        Ok(discovery)
3075    }
3076
3077    pub async fn start_workflow<T: Serialize>(
3078        &self,
3079        workflow_type: &str,
3080        task_queue: &str,
3081        workflow_id: &str,
3082        input: T,
3083    ) -> Result<WorkflowHandle> {
3084        self.start_workflow_with_options(
3085            workflow_type,
3086            task_queue,
3087            workflow_id,
3088            WorkflowStartOptions::default(),
3089            input,
3090        )
3091        .await
3092    }
3093
3094    /// Start a workflow with explicit server-enforced execution and run
3095    /// deadlines.
3096    pub async fn start_workflow_with_options<T: Serialize>(
3097        &self,
3098        workflow_type: &str,
3099        task_queue: &str,
3100        workflow_id: &str,
3101        options: WorkflowStartOptions,
3102        input: T,
3103    ) -> Result<WorkflowHandle> {
3104        options.validate()?;
3105        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3106        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3107        let body = self.with_observability_context(json!({
3108            "workflow_id": workflow_id,
3109            "workflow_type": workflow_type,
3110            "task_queue": task_queue,
3111            "input": input_envelope,
3112            "execution_timeout_seconds": options.execution_timeout_seconds,
3113            "run_timeout_seconds": options.run_timeout_seconds
3114        }));
3115
3116        let data: Value = self
3117            .request_json(
3118                reqwest::Method::POST,
3119                "/workflows",
3120                RequestProtocol::ControlPlane,
3121                Some(&body),
3122            )
3123            .await?;
3124
3125        Ok(WorkflowHandle {
3126            client: self.clone(),
3127            workflow_id: data
3128                .get("workflow_id")
3129                .and_then(Value::as_str)
3130                .unwrap_or(workflow_id)
3131                .to_string(),
3132            run_id: data
3133                .get("run_id")
3134                .and_then(Value::as_str)
3135                .map(str::to_string),
3136            workflow_type: data
3137                .get("workflow_type")
3138                .and_then(Value::as_str)
3139                .unwrap_or(workflow_type)
3140                .to_string(),
3141        })
3142    }
3143
3144    /// Send a signal with an SDK-generated caller command key.
3145    ///
3146    /// The key is sent as the `request_id` body field and is present in the
3147    /// returned receipt's `request_id`. A Server that already retains the key
3148    /// for the same signal intent returns the original receipt with
3149    /// `retained: true`; a different intent is refused with
3150    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3151    /// [`Client::signal_workflow_with_request_id`] when the application must be
3152    /// able to retry the same logical signal after a transport failure.
3153    pub async fn signal_workflow<T: Serialize>(
3154        &self,
3155        workflow_id: &str,
3156        signal_name: &str,
3157        input: T,
3158    ) -> Result<Value> {
3159        let request_id = Self::generate_signal_request_id();
3160        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3161            .await
3162    }
3163
3164    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3165    ///
3166    /// Resend the identical signal with the same key after an uncertain
3167    /// outcome: the Server returns the retained receipt instead of admitting a
3168    /// second signal, for as long as the retained run's details are kept.
3169    pub async fn signal_workflow_with_request_id<T: Serialize>(
3170        &self,
3171        workflow_id: &str,
3172        signal_name: &str,
3173        input: T,
3174        request_id: &str,
3175    ) -> Result<Value> {
3176        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3177            .await
3178    }
3179
3180    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3181    ///
3182    /// Methods without an explicit key generate one of these per call. Obtain it
3183    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3184    /// transport failure does not lose the key needed for a safe retry.
3185    pub fn generate_signal_request_id() -> String {
3186        generated_request_id("signal")
3187    }
3188
3189    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3190    ///
3191    /// [`Client::update_workflow`] generates one of these when `request_id` is
3192    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3193    /// does not lose the key needed for a safe retry.
3194    pub fn generate_update_request_id() -> String {
3195        generated_request_id("update")
3196    }
3197
3198    /// Append one idempotently identified item to an instance-scoped input stream.
3199    pub async fn append_message_stream<T: Serialize>(
3200        &self,
3201        workflow_id: &str,
3202        stream_name: &str,
3203        message_id: &str,
3204        input: T,
3205    ) -> Result<Value> {
3206        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3207        let body = json!({
3208            "message_id": message_id,
3209            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3210        });
3211        self.request_json(
3212            reqwest::Method::POST,
3213            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
3214            RequestProtocol::ControlPlane,
3215            Some(&body),
3216        )
3217        .await
3218    }
3219
3220    /// Signal only if `run_id` is still the current run for this instance,
3221    /// with an SDK-generated caller command key.
3222    pub async fn signal_workflow_run<T: Serialize>(
3223        &self,
3224        workflow_id: &str,
3225        run_id: &str,
3226        signal_name: &str,
3227        input: T,
3228    ) -> Result<Value> {
3229        let request_id = Self::generate_signal_request_id();
3230        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3231            .await
3232    }
3233
3234    /// Signal only if `run_id` is still the current run for this instance,
3235    /// with an explicit caller command key (1 to 255 Unicode characters).
3236    ///
3237    /// The selected run is part of the signal's intent: retrying with the same
3238    /// key and a different run target is a `request_id_conflict` refusal.
3239    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3240        &self,
3241        workflow_id: &str,
3242        run_id: &str,
3243        signal_name: &str,
3244        input: T,
3245        request_id: &str,
3246    ) -> Result<Value> {
3247        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3248            .await
3249    }
3250
3251    async fn signal_workflow_target<T: Serialize>(
3252        &self,
3253        workflow_id: &str,
3254        run_id: Option<&str>,
3255        signal_name: &str,
3256        input: T,
3257        request_id: &str,
3258    ) -> Result<Value> {
3259        validate_user_signal_name(signal_name)?;
3260        validate_request_id(request_id)?;
3261        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3262        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3263        let body = self.with_observability_context(json!({
3264            "input": input_envelope,
3265            "request_id": request_id,
3266        }));
3267        let path = match run_id {
3268            Some(run_id) => {
3269                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3270            }
3271            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3272        };
3273        let receipt = self
3274            .request_json(
3275                reqwest::Method::POST,
3276                &path,
3277                RequestProtocol::ControlPlane,
3278                Some(&body),
3279            )
3280            .await?;
3281        Ok(with_request_id(receipt, request_id))
3282    }
3283
3284    /// Close the current run as cancelled immediately.
3285    ///
3286    /// Server revokes open tasks and timers without resuming workflow code for
3287    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3288    /// request on a supporting runtime and opted-in worker.
3289    pub async fn cancel_workflow(
3290        &self,
3291        workflow_id: &str,
3292        options: WorkflowCommandOptions,
3293    ) -> Result<WorkflowCommandResult> {
3294        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3295            .await
3296    }
3297
3298    /// Close the selected run as cancelled, only if `run_id` is still current.
3299    pub async fn cancel_workflow_run(
3300        &self,
3301        workflow_id: &str,
3302        run_id: &str,
3303        options: WorkflowCommandOptions,
3304    ) -> Result<WorkflowCommandResult> {
3305        self.workflow_command(
3306            workflow_id,
3307            Some(run_id),
3308            WorkflowCommandKind::Cancel,
3309            options,
3310        )
3311        .await
3312    }
3313
3314    /// Forcefully terminate the current run for an instance.
3315    pub async fn terminate_workflow(
3316        &self,
3317        workflow_id: &str,
3318        options: WorkflowCommandOptions,
3319    ) -> Result<WorkflowCommandResult> {
3320        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3321            .await
3322    }
3323
3324    /// Forcefully terminate only if `run_id` is still current.
3325    pub async fn terminate_workflow_run(
3326        &self,
3327        workflow_id: &str,
3328        run_id: &str,
3329        options: WorkflowCommandOptions,
3330    ) -> Result<WorkflowCommandResult> {
3331        self.workflow_command(
3332            workflow_id,
3333            Some(run_id),
3334            WorkflowCommandKind::Terminate,
3335            options,
3336        )
3337        .await
3338    }
3339
3340    /// Continue a failed run from its recorded activity failure boundary.
3341    pub async fn redrive_workflow_run(
3342        &self,
3343        workflow_id: &str,
3344        failed_run_id: &str,
3345        request_id: Option<&str>,
3346    ) -> Result<WorkflowRedriveResult> {
3347        let body = request_id
3348            .map(|id| json!({"request_id": id}))
3349            .unwrap_or_else(|| json!({}));
3350        let data: Value = self
3351            .request_json(
3352                reqwest::Method::POST,
3353                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3354                RequestProtocol::ControlPlane,
3355                Some(&body),
3356            )
3357            .await?;
3358        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3359            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3360        {
3361            return Err(Error::Codec(
3362                "redrive response was not accepted".to_string(),
3363            ));
3364        }
3365        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3366            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3367        {
3368            return Err(Error::Codec(
3369                "redrive response does not match the requested source run".to_string(),
3370            ));
3371        }
3372        let run_id = data
3373            .get("run_id")
3374            .and_then(Value::as_str)
3375            .filter(|id| !id.is_empty() && *id != failed_run_id)
3376            .ok_or_else(|| {
3377                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3378            })?;
3379        let resume_step_sequence = data
3380            .get("resume_step_sequence")
3381            .and_then(Value::as_u64)
3382            .filter(|sequence| *sequence > 0)
3383            .ok_or_else(|| {
3384                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3385            })?;
3386        Ok(WorkflowRedriveResult {
3387            workflow_id: workflow_id.to_string(),
3388            source_run_id: failed_run_id.to_string(),
3389            run_id: run_id.to_string(),
3390            resume_step_sequence,
3391            raw: data,
3392        })
3393    }
3394
3395    async fn workflow_command(
3396        &self,
3397        workflow_id: &str,
3398        run_id: Option<&str>,
3399        command: WorkflowCommandKind,
3400        options: WorkflowCommandOptions,
3401    ) -> Result<WorkflowCommandResult> {
3402        #[cfg(feature = "telemetry")]
3403        let body = if command == WorkflowCommandKind::Cancel {
3404            self.with_observability_context(serde_json::to_value(&options)?)
3405        } else {
3406            serde_json::to_value(&options)?
3407        };
3408        #[cfg(not(feature = "telemetry"))]
3409        let body = &options;
3410        let path = match run_id {
3411            Some(run_id) => format!(
3412                "/workflows/{workflow_id}/runs/{run_id}/{}",
3413                command.as_str()
3414            ),
3415            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3416        };
3417        let data = match self
3418            .request_json(
3419                reqwest::Method::POST,
3420                &path,
3421                RequestProtocol::ControlPlane,
3422                Some(&body),
3423            )
3424            .await
3425        {
3426            Ok(data) => data,
3427            Err(Error::Http { status, body }) => {
3428                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3429                    command,
3430                    status,
3431                    body,
3432                    workflow_id,
3433                    run_id,
3434                )));
3435            }
3436            Err(error) => return Err(error),
3437        };
3438
3439        Ok(workflow_command_result(command, data, workflow_id, run_id))
3440    }
3441
3442    /// Execute a named, read-only query against a running or completed workflow.
3443    ///
3444    /// Arguments and results use the platform payload envelope. Server and
3445    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3446    /// reason, HTTP status, and original response body.
3447    pub async fn query_workflow<T: Serialize>(
3448        &self,
3449        workflow_id: &str,
3450        query_name: &str,
3451        input: T,
3452    ) -> Result<Value> {
3453        self.query_workflow_target(workflow_id, None, query_name, input)
3454            .await
3455    }
3456
3457    /// Query only if `run_id` is still current, preventing accidental retargeting.
3458    pub async fn query_workflow_run<T: Serialize>(
3459        &self,
3460        workflow_id: &str,
3461        run_id: &str,
3462        query_name: &str,
3463        input: T,
3464    ) -> Result<Value> {
3465        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3466            .await
3467    }
3468
3469    /// Query a workflow and return the lossless fixed Avro Value result.
3470    pub async fn query_workflow_avro_value<T: Serialize>(
3471        &self,
3472        workflow_id: &str,
3473        query_name: &str,
3474        input: T,
3475    ) -> Result<AvroValue> {
3476        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3477            .await
3478    }
3479
3480    /// Query a selected run and return the lossless fixed Avro Value result.
3481    pub async fn query_workflow_run_avro_value<T: Serialize>(
3482        &self,
3483        workflow_id: &str,
3484        run_id: &str,
3485        query_name: &str,
3486        input: T,
3487    ) -> Result<AvroValue> {
3488        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3489            .await
3490    }
3491
3492    async fn query_workflow_avro_value_target<T: Serialize>(
3493        &self,
3494        workflow_id: &str,
3495        run_id: Option<&str>,
3496        query_name: &str,
3497        input: T,
3498    ) -> Result<AvroValue> {
3499        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3500        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3501        let path = match run_id {
3502            Some(run_id) => {
3503                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3504            }
3505            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3506        };
3507        let response: Value = match self
3508            .request_json(
3509                reqwest::Method::POST,
3510                &path,
3511                RequestProtocol::ControlPlane,
3512                Some(&body),
3513            )
3514            .await
3515        {
3516            Ok(response) => response,
3517            Err(Error::Http { status, body }) => {
3518                return Err(Error::QueryFailed(query_failure(status, body)));
3519            }
3520            Err(error) => return Err(error),
3521        };
3522
3523        let envelope = response
3524            .get("result_envelope")
3525            .filter(|envelope| !envelope.is_null())
3526            .ok_or_else(|| {
3527                Error::Codec(
3528                    "missing_payload_envelope: typed query result requires result_envelope"
3529                        .to_string(),
3530                )
3531            })?;
3532        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3533    }
3534
3535    async fn query_workflow_target<T: Serialize>(
3536        &self,
3537        workflow_id: &str,
3538        run_id: Option<&str>,
3539        query_name: &str,
3540        input: T,
3541    ) -> Result<Value> {
3542        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3543        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3544        let body = json!({
3545            "input": input_envelope
3546        });
3547        let path = match run_id {
3548            Some(run_id) => {
3549                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3550            }
3551            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3552        };
3553        let response: Value = match self
3554            .request_json(
3555                reqwest::Method::POST,
3556                &path,
3557                RequestProtocol::ControlPlane,
3558                Some(&body),
3559            )
3560            .await
3561        {
3562            Ok(response) => response,
3563            Err(Error::Http { status, body }) => {
3564                return Err(Error::QueryFailed(query_failure(status, body)));
3565            }
3566            Err(error) => return Err(error),
3567        };
3568
3569        if let Some(envelope) = response
3570            .get("result_envelope")
3571            .filter(|envelope| !envelope.is_null())
3572        {
3573            return decode_wire_value(envelope, DEFAULT_CODEC);
3574        }
3575
3576        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3577    }
3578
3579    /// Send a synchronous update using fixed Avro Value arguments.
3580    ///
3581    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
3582    /// `request_id` body field; `None` generates one with
3583    /// [`Client::generate_update_request_id`]. A Server that already retains the
3584    /// key for the same update intent returns the original update's receipt and
3585    /// result instead of admitting a second update; a different intent is
3586    /// refused with [`Error::is_request_id_conflict`].
3587    pub async fn update_workflow<T: Serialize>(
3588        &self,
3589        workflow_id: &str,
3590        update_name: &str,
3591        input: T,
3592        request_id: Option<&str>,
3593    ) -> Result<Value> {
3594        let response = self
3595            .update_workflow_response(workflow_id, update_name, input, request_id)
3596            .await?;
3597        if let Some(envelope) = response
3598            .get("result_envelope")
3599            .filter(|envelope| !envelope.is_null())
3600        {
3601            return decode_wire_value(envelope, DEFAULT_CODEC);
3602        }
3603        Ok(response.get("result").cloned().unwrap_or(response))
3604    }
3605
3606    /// Send a synchronous update and retain a bytes-capable Avro result.
3607    pub async fn update_workflow_avro_value<T: Serialize>(
3608        &self,
3609        workflow_id: &str,
3610        update_name: &str,
3611        input: T,
3612        request_id: Option<&str>,
3613    ) -> Result<AvroValue> {
3614        let response = self
3615            .update_workflow_response(workflow_id, update_name, input, request_id)
3616            .await?;
3617        let envelope = response
3618            .get("result_envelope")
3619            .filter(|envelope| !envelope.is_null())
3620            .ok_or_else(|| {
3621                Error::Codec(
3622                    "missing_payload_envelope: typed update result requires result_envelope"
3623                        .to_string(),
3624                )
3625            })?;
3626        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3627    }
3628
3629    async fn update_workflow_response<T: Serialize>(
3630        &self,
3631        workflow_id: &str,
3632        update_name: &str,
3633        input: T,
3634        request_id: Option<&str>,
3635    ) -> Result<Value> {
3636        let request_id = match request_id {
3637            Some(request_id) => {
3638                validate_request_id(request_id)?;
3639                request_id.to_string()
3640            }
3641            None => Self::generate_update_request_id(),
3642        };
3643        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3644        let body = self.with_observability_context(json!({
3645            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3646            "wait_for": "completed",
3647            "request_id": request_id,
3648        }));
3649        let receipt = self
3650            .request_json(
3651                reqwest::Method::POST,
3652                &format!("/workflows/{workflow_id}/update/{update_name}"),
3653                RequestProtocol::ControlPlane,
3654                Some(&body),
3655            )
3656            .await?;
3657        Ok(with_request_id(receipt, &request_id))
3658    }
3659
3660    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3661        let path = format!("/workflows/{workflow_id}");
3662        let mut data: WorkflowDescription = self
3663            .request_json(
3664                reqwest::Method::GET,
3665                &path,
3666                RequestProtocol::ControlPlane,
3667                Option::<&Value>::None,
3668            )
3669            .await?;
3670        data.decode_payloads()?;
3671        Ok(data)
3672    }
3673
3674    /// Describe one selected run, including historical terminal runs.
3675    pub async fn describe_workflow_run(
3676        &self,
3677        workflow_id: &str,
3678        run_id: &str,
3679    ) -> Result<WorkflowDescription> {
3680        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3681        let mut data: WorkflowDescription = self
3682            .request_json(
3683                reqwest::Method::GET,
3684                &path,
3685                RequestProtocol::ControlPlane,
3686                Option::<&Value>::None,
3687            )
3688            .await?;
3689        data.decode_payloads()?;
3690        Ok(data)
3691    }
3692
3693    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3694        let mut path = format!(
3695            "/workflows/{}/runs/{}/streams",
3696            percent_encode_path_segment(workflow_id),
3697            percent_encode_path_segment(run_id),
3698        );
3699        if let Some(stream_name) = stream_name {
3700            path.push('/');
3701            path.push_str(&percent_encode_path_segment(stream_name));
3702        }
3703        path
3704    }
3705
3706    /// List the run-scoped output streams already opened by a workflow.
3707    pub async fn list_workflow_streams(
3708        &self,
3709        workflow_id: &str,
3710        run_id: &str,
3711    ) -> Result<Vec<WorkflowStreamDescription>> {
3712        let response: WorkflowStreamListResponse = self
3713            .request_json(
3714                reqwest::Method::GET,
3715                &Self::workflow_stream_path(workflow_id, run_id, None),
3716                RequestProtocol::ControlPlane,
3717                Option::<&Value>::None,
3718            )
3719            .await?;
3720        Ok(response.streams)
3721    }
3722
3723    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3724    pub async fn describe_workflow_stream(
3725        &self,
3726        workflow_id: &str,
3727        run_id: &str,
3728        stream_name: &str,
3729    ) -> Result<WorkflowStreamDescription> {
3730        let response: WorkflowStreamDescriptionResponse = self
3731            .request_json(
3732                reqwest::Method::GET,
3733                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3734                RequestProtocol::ControlPlane,
3735                Option::<&Value>::None,
3736            )
3737            .await?;
3738        Ok(response.stream)
3739    }
3740
3741    /// Read one bounded page beginning at a zero-based offset.
3742    ///
3743    /// Delivery is at least once: persist `next_offset` only after processing
3744    /// the page. The future is cancellation-safe; dropping it cancels the
3745    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3746    /// service contract.
3747    pub async fn subscribe_workflow_stream(
3748        &self,
3749        workflow_id: &str,
3750        run_id: &str,
3751        stream_name: &str,
3752        from_offset: u64,
3753        max_items: usize,
3754        wait: Duration,
3755    ) -> Result<WorkflowStreamPage> {
3756        let max_items = max_items.clamp(1, 500);
3757        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3758        let path = format!(
3759            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3760            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3761        );
3762        let response: WorkflowStreamPageResponse = self
3763            .request_json_with_timeout(
3764                reqwest::Method::GET,
3765                &path,
3766                RequestProtocol::ControlPlane,
3767                Option::<&Value>::None,
3768                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3769            )
3770            .await?;
3771
3772        let items = response
3773            .items
3774            .into_iter()
3775            .map(|raw| {
3776                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3777                let envelope = raw.get("payload").cloned();
3778                let payload = envelope
3779                    .as_ref()
3780                    .filter(|value| value.get("blob").is_some())
3781                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3782                    .transpose()?
3783                    .map(AvroValue::into_json)
3784                    .transpose()?;
3785                Ok(WorkflowStreamItem {
3786                    offset,
3787                    payload,
3788                    payload_envelope: envelope,
3789                    payload_reference: raw
3790                        .get("payload_reference")
3791                        .and_then(Value::as_str)
3792                        .map(str::to_string),
3793                    payload_codec: raw
3794                        .get("payload_codec")
3795                        .and_then(Value::as_str)
3796                        .map(str::to_string),
3797                    idempotency_key: raw
3798                        .get("idempotency_key")
3799                        .and_then(Value::as_str)
3800                        .map(str::to_string),
3801                    item_type: raw
3802                        .get("item_type")
3803                        .and_then(Value::as_str)
3804                        .map(str::to_string),
3805                    content_type: raw
3806                        .get("content_type")
3807                        .and_then(Value::as_str)
3808                        .map(str::to_string),
3809                    origin: raw
3810                        .get("origin")
3811                        .and_then(Value::as_str)
3812                        .map(str::to_string),
3813                    origin_reference: raw
3814                        .get("origin_reference")
3815                        .and_then(Value::as_str)
3816                        .map(str::to_string),
3817                    emitted_at: raw
3818                        .get("emitted_at")
3819                        .and_then(Value::as_str)
3820                        .map(str::to_string),
3821                    raw,
3822                })
3823            })
3824            .collect::<Result<Vec<_>>>()?;
3825        Ok(WorkflowStreamPage {
3826            stream: response.stream,
3827            items,
3828            next_offset: response.next_offset,
3829            terminal: response.terminal,
3830        })
3831    }
3832
3833    /// Append inline Avro envelopes or opaque external payload references.
3834    pub async fn append_workflow_stream(
3835        &self,
3836        workflow_id: &str,
3837        run_id: &str,
3838        stream_name: &str,
3839        items: &[WorkflowStreamAppendItem],
3840        max_pending_items: Option<u64>,
3841    ) -> Result<WorkflowStreamAppendResult> {
3842        if items.is_empty() {
3843            return Err(Error::Codec(
3844                "workflow_stream_items_empty: append requires at least one item".to_string(),
3845            ));
3846        }
3847        let mut body = json!({
3848            "items": items
3849                .iter()
3850                .map(|item| item.wire_value(None))
3851                .collect::<Vec<_>>(),
3852        });
3853        if let Some(max_pending_items) = max_pending_items {
3854            if max_pending_items == 0 {
3855                return Err(Error::Codec(
3856                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3857                        .to_string(),
3858                ));
3859            }
3860            body["max_pending_items"] = json!(max_pending_items);
3861        }
3862        let response: WorkflowStreamAppendResponse = self
3863            .request_json(
3864                reqwest::Method::POST,
3865                &format!(
3866                    "{}/items",
3867                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3868                ),
3869                RequestProtocol::ControlPlane,
3870                Some(&body),
3871            )
3872            .await?;
3873        Ok(WorkflowStreamAppendResult {
3874            stream: response.stream,
3875            accepted_offsets: response.accepted_offsets,
3876            accepted: response.accepted,
3877            deduped: response.deduped,
3878        })
3879    }
3880
3881    /// Close a stream, or mark it errored when `error_reason` is supplied.
3882    pub async fn close_workflow_stream(
3883        &self,
3884        workflow_id: &str,
3885        run_id: &str,
3886        stream_name: &str,
3887        error_reason: Option<&str>,
3888        retention_seconds: Option<u64>,
3889    ) -> Result<WorkflowStreamDescription> {
3890        let mut body = json!({});
3891        if let Some(error_reason) = error_reason {
3892            body["error_reason"] = json!(error_reason);
3893        }
3894        if let Some(retention_seconds) = retention_seconds {
3895            if retention_seconds == 0 {
3896                return Err(Error::Codec(
3897                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3898                        .to_string(),
3899                ));
3900            }
3901            body["retention_seconds"] = json!(retention_seconds);
3902        }
3903        let response: WorkflowStreamDescriptionResponse = self
3904            .request_json(
3905                reqwest::Method::POST,
3906                &format!(
3907                    "{}/close",
3908                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3909                ),
3910                RequestProtocol::ControlPlane,
3911                Some(&body),
3912            )
3913            .await?;
3914        Ok(response.stream)
3915    }
3916
3917    pub async fn register_worker(
3918        &self,
3919        worker_id: &str,
3920        task_queue: &str,
3921        supported_workflow_types: Vec<String>,
3922        supported_activity_types: Vec<String>,
3923        max_concurrent_workflow_tasks: usize,
3924        max_concurrent_activity_tasks: usize,
3925    ) -> Result<RegisterWorkerResponse> {
3926        self.register_worker_with_capabilities(
3927            worker_id,
3928            task_queue,
3929            supported_workflow_types,
3930            supported_activity_types,
3931            max_concurrent_workflow_tasks,
3932            max_concurrent_activity_tasks,
3933            Vec::new(),
3934        )
3935        .await
3936    }
3937
3938    /// Register a worker and explicitly advertise additive worker capabilities.
3939    pub async fn register_worker_with_capabilities(
3940        &self,
3941        worker_id: &str,
3942        task_queue: &str,
3943        supported_workflow_types: Vec<String>,
3944        supported_activity_types: Vec<String>,
3945        max_concurrent_workflow_tasks: usize,
3946        max_concurrent_activity_tasks: usize,
3947        capabilities: Vec<String>,
3948    ) -> Result<RegisterWorkerResponse> {
3949        self.register_worker_with_command_contracts(
3950            worker_id,
3951            task_queue,
3952            supported_workflow_types,
3953            supported_activity_types,
3954            max_concurrent_workflow_tasks,
3955            max_concurrent_activity_tasks,
3956            capabilities,
3957            Value::Object(serde_json::Map::new()),
3958        )
3959        .await
3960    }
3961
3962    /// Register a worker and advertise its named query and update handlers.
3963    ///
3964    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3965    /// so a workflow contract with a non-empty or malformed
3966    /// `update_validators` declaration returns
3967    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3968    #[allow(clippy::too_many_arguments)]
3969    pub async fn register_worker_with_command_contracts(
3970        &self,
3971        worker_id: &str,
3972        task_queue: &str,
3973        supported_workflow_types: Vec<String>,
3974        supported_activity_types: Vec<String>,
3975        max_concurrent_workflow_tasks: usize,
3976        max_concurrent_activity_tasks: usize,
3977        capabilities: Vec<String>,
3978        workflow_command_contracts: Value,
3979    ) -> Result<RegisterWorkerResponse> {
3980        self.register_worker_with_definition_fingerprints(
3981            worker_id,
3982            task_queue,
3983            supported_workflow_types,
3984            supported_activity_types,
3985            max_concurrent_workflow_tasks,
3986            max_concurrent_activity_tasks,
3987            capabilities,
3988            workflow_command_contracts,
3989            None,
3990        )
3991        .await
3992    }
3993
3994    #[allow(clippy::too_many_arguments)]
3995    async fn register_worker_with_definition_fingerprints(
3996        &self,
3997        worker_id: &str,
3998        task_queue: &str,
3999        supported_workflow_types: Vec<String>,
4000        supported_activity_types: Vec<String>,
4001        max_concurrent_workflow_tasks: usize,
4002        max_concurrent_activity_tasks: usize,
4003        capabilities: Vec<String>,
4004        workflow_command_contracts: Value,
4005        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
4006    ) -> Result<RegisterWorkerResponse> {
4007        if let Some(contracts) = workflow_command_contracts.as_object() {
4008            for (workflow_type, contract) in contracts {
4009                let Some(update_validators) = contract.get("update_validators") else {
4010                    continue;
4011                };
4012                if !update_validators
4013                    .as_array()
4014                    .is_some_and(|validators| validators.is_empty())
4015                {
4016                    return Err(Error::UnsupportedUpdateValidators {
4017                        workflow_type: workflow_type.clone(),
4018                    });
4019                }
4020            }
4021        }
4022
4023        let mut body = json!({
4024            "worker_id": worker_id,
4025            "task_queue": task_queue,
4026            "runtime": "rust",
4027            "sdk_version": SDK_VERSION,
4028            "supported_workflow_types": supported_workflow_types,
4029            "supported_activity_types": supported_activity_types,
4030            "capabilities": capabilities,
4031            "capability_manifest": portable_worker_affinity_capability_manifest(),
4032            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4033            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4034        });
4035        if capabilities
4036            .iter()
4037            .any(|capability| capability == "nexus_cooperative_cancellation")
4038        {
4039            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4040                "supported":true, "minimum_protocol_version":"1.20",
4041                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4042            });
4043        }
4044        if let Some(build_id) = &self.worker_build_id {
4045            if build_id.is_empty() || build_id.len() > 255 {
4046                return Err(Error::WorkerLoop(
4047                    "worker build ID must contain 1 to 255 bytes".into(),
4048                ));
4049            }
4050            body["build_id"] = json!(build_id);
4051        }
4052        if self.sticky_cache.is_some() {
4053            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4054                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4055                "implementation":"bounded_durable_history_cache"});
4056        }
4057        if self.local_activities_enabled {
4058            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4059                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4060        }
4061        if self.worker_sessions_enabled {
4062            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4063                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4064            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4065        }
4066        if workflow_command_contracts
4067            .as_object()
4068            .is_some_and(|contracts| !contracts.is_empty())
4069        {
4070            body["workflow_command_contracts"] = workflow_command_contracts;
4071        }
4072        if let Some(fingerprints) = workflow_definition_fingerprints {
4073            body["workflow_definition_fingerprints"] = json!(fingerprints);
4074        }
4075
4076        let response: Value = self
4077            .request_json(
4078                reqwest::Method::POST,
4079                "/worker/register",
4080                RequestProtocol::DefaultWorker,
4081                Some(&body),
4082            )
4083            .await?;
4084        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4085            self.observe_activity_lease_capabilities(&response["server_capabilities"]);
4086        }
4087        if self.sticky_cache.is_some() {
4088            self.confirm_sticky_registration(&response, worker_id, task_queue)
4089                .await?;
4090        }
4091        if self.local_activities_enabled || self.worker_sessions_enabled {
4092            let compatible = response["registered"].as_bool() == Some(true)
4093                && response["worker_id"].as_str() == Some(worker_id)
4094                && response["namespace"].as_str() == Some(self.namespace.as_str())
4095                && response["task_queue"].as_str() == Some(task_queue)
4096                && response["protocol_version"]
4097                    .as_str()
4098                    .and_then(|version| version.strip_prefix("1."))
4099                    .and_then(|minor| minor.parse::<u64>().ok())
4100                    .is_some_and(|minor| minor >= 18)
4101                && (!self.local_activities_enabled
4102                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4103                        == Some(true))
4104                && (!self.worker_sessions_enabled
4105                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4106                        == Some(true)
4107                        && response["capabilities"].as_array().is_some_and(|accepted| {
4108                            capabilities.iter().all(|capability| {
4109                                accepted
4110                                    .iter()
4111                                    .any(|value| value.as_str() == Some(capability.as_str()))
4112                            })
4113                        })));
4114            if !compatible {
4115                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4116                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4117                } else {
4118                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4119                });
4120                if response["registered"] == true
4121                    && response["worker_id"].as_str() == Some(worker_id)
4122                {
4123                    if let Err(deregistration) =
4124                        self.deregister_worker_registration(worker_id).await
4125                    {
4126                        return Err(Error::WorkerShutdown {
4127                            primary: Box::new(error),
4128                            deregistration: Box::new(deregistration),
4129                        });
4130                    }
4131                }
4132                return Err(error);
4133            }
4134        }
4135        if self.cooperative_worker_protocol {
4136            let compatible = response["registered"].as_bool() == Some(true)
4137                && response["worker_id"].as_str() == Some(worker_id)
4138                && response["namespace"].as_str() == Some(self.namespace.as_str())
4139                && response["task_queue"].as_str() == Some(task_queue)
4140                && response["protocol_version"]
4141                    .as_str()
4142                    .is_some_and(cooperative_cancellation::supports_protocol)
4143                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4144                    == Some(true)
4145                && (!capabilities
4146                    .iter()
4147                    .any(|capability| capability == "nexus_cooperative_cancellation")
4148                    || nexus::installed_cooperation(&response["server_capabilities"]))
4149                && response["capabilities"].as_array().is_some_and(|accepted| {
4150                    capabilities.iter().all(|capability| {
4151                        accepted
4152                            .iter()
4153                            .any(|value| value.as_str() == Some(capability.as_str()))
4154                    })
4155                });
4156            if !compatible {
4157                let error = Error::CooperativeCancellationUnavailable(
4158                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4159                );
4160                if response["registered"].as_bool() == Some(true)
4161                    && response["worker_id"].as_str() == Some(worker_id)
4162                {
4163                    if let Err(deregistration) =
4164                        self.deregister_worker_registration(worker_id).await
4165                    {
4166                        return Err(Error::WorkerShutdown {
4167                            primary: Box::new(error),
4168                            deregistration: Box::new(deregistration),
4169                        });
4170                    }
4171                }
4172                return Err(error);
4173            }
4174        }
4175        Ok(serde_json::from_value(response)?)
4176    }
4177
4178    /// Gracefully remove one worker's registration through the worker plane.
4179    ///
4180    /// This operation is separate from operator-facing worker management. It
4181    /// uses worker-protocol authentication and returns the server's lease
4182    /// recovery result.
4183    pub async fn deregister_worker_registration(
4184        &self,
4185        worker_id: &str,
4186    ) -> Result<WorkerDeregistrationEnvelope> {
4187        let path = format!(
4188            "/worker/registrations/{}",
4189            percent_encode_path_segment(worker_id)
4190        );
4191        self.request_json(
4192            reqwest::Method::DELETE,
4193            &path,
4194            RequestProtocol::DefaultWorker,
4195            Option::<&Value>::None,
4196        )
4197        .await
4198    }
4199
4200    /// Long-poll for an ephemeral, read-only workflow query task.
4201    pub async fn poll_query_task(
4202        &self,
4203        worker_id: &str,
4204        task_queue: &str,
4205        timeout: Duration,
4206    ) -> Result<Option<QueryTask>> {
4207        Ok(self
4208            .poll_query_task_response(worker_id, task_queue, timeout)
4209            .await?
4210            .task)
4211    }
4212
4213    /// Poll a query task while preserving server stop and drain metadata.
4214    pub async fn poll_query_task_response(
4215        &self,
4216        worker_id: &str,
4217        task_queue: &str,
4218        timeout: Duration,
4219    ) -> Result<PollQueryTaskResponse> {
4220        let poll_request_id = unique_request_id("rust-query-poll");
4221        self.poll_query_task_response_with_request_id(
4222            worker_id,
4223            task_queue,
4224            timeout,
4225            &poll_request_id,
4226            1,
4227        )
4228        .await
4229    }
4230
4231    async fn poll_query_task_response_with_request_id(
4232        &self,
4233        worker_id: &str,
4234        task_queue: &str,
4235        timeout: Duration,
4236        poll_request_id: &str,
4237        transport_retries: usize,
4238    ) -> Result<PollQueryTaskResponse> {
4239        let timeout_seconds = long_poll_timeout_seconds(timeout);
4240        let body = json!({
4241            "worker_id": worker_id,
4242            "task_queue": task_queue,
4243            "poll_request_id": poll_request_id,
4244            "timeout_seconds": timeout_seconds,
4245        });
4246        self.poll_request_json(
4247            "/worker/query-tasks/poll",
4248            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4249            &body,
4250            timeout + Duration::from_secs(5),
4251            transport_retries,
4252        )
4253        .await
4254    }
4255
4256    /// Complete a query task without appending workflow history.
4257    pub async fn complete_query_task<T: Serialize>(
4258        &self,
4259        query_task_id: &str,
4260        lease_owner: &str,
4261        query_task_attempt: u64,
4262        result: T,
4263        codec: &str,
4264    ) -> Result<Value> {
4265        let typed_result = AvroValue::from_serialize(&result)?;
4266        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4267        self.complete_query_task_with_envelope(
4268            query_task_id,
4269            lease_owner,
4270            query_task_attempt,
4271            typed_result.into_json()?,
4272            result_envelope,
4273        )
4274        .await
4275    }
4276
4277    async fn complete_query_task_with_envelope(
4278        &self,
4279        query_task_id: &str,
4280        lease_owner: &str,
4281        query_task_attempt: u64,
4282        result: Value,
4283        result_envelope: Value,
4284    ) -> Result<Value> {
4285        let body = json!({
4286            "lease_owner": lease_owner,
4287            "query_task_attempt": query_task_attempt,
4288            "result": result,
4289            "result_envelope": result_envelope,
4290        });
4291        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4292        let response = self
4293            .request_json(
4294                reqwest::Method::POST,
4295                &path,
4296                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4297                Some(&body),
4298            )
4299            .await;
4300        query_task_response(response)
4301    }
4302
4303    /// Report a stable machine-readable query-task failure.
4304    pub async fn fail_query_task(
4305        &self,
4306        query_task_id: &str,
4307        lease_owner: &str,
4308        query_task_attempt: u64,
4309        message: impl Into<String>,
4310        reason: impl Into<String>,
4311        failure_type: impl Into<String>,
4312    ) -> Result<Value> {
4313        let body = json!({
4314            "lease_owner": lease_owner,
4315            "query_task_attempt": query_task_attempt,
4316            "failure": {
4317                "message": message.into(),
4318                "reason": reason.into(),
4319                "type": failure_type.into(),
4320            }
4321        });
4322        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4323        let response = self
4324            .request_json(
4325                reqwest::Method::POST,
4326                &path,
4327                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4328                Some(&body),
4329            )
4330            .await;
4331        query_task_response(response)
4332    }
4333
4334    pub async fn heartbeat_worker(
4335        &self,
4336        worker_id: &str,
4337        workflow_available: usize,
4338        activity_available: usize,
4339    ) -> Result<Value> {
4340        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4341            .await
4342    }
4343
4344    async fn heartbeat_worker_with_sessions(
4345        &self,
4346        worker_id: &str,
4347        workflow_available: usize,
4348        activity_available: usize,
4349        session_available: Option<usize>,
4350    ) -> Result<Value> {
4351        let mut body = json!({
4352            "worker_id": worker_id,
4353            "task_slots": {
4354                "workflow_available": workflow_available,
4355                "activity_available": activity_available
4356            },
4357            "process_metrics": {
4358                "process_id": std::process::id(),
4359                "process_uptime_seconds": 0
4360            }
4361        });
4362
4363        if let Some(available) = session_available {
4364            body["task_slots"]["session_available"] = json!(available);
4365        }
4366
4367        self.request_json(
4368            reqwest::Method::POST,
4369            "/worker/heartbeat",
4370            RequestProtocol::DefaultWorker,
4371            Some(&body),
4372        )
4373        .await
4374    }
4375
4376    pub async fn poll_workflow_task(
4377        &self,
4378        worker_id: &str,
4379        task_queue: &str,
4380        timeout: Duration,
4381    ) -> Result<Option<WorkflowTask>> {
4382        Ok(self
4383            .poll_workflow_task_response(worker_id, task_queue, timeout)
4384            .await?
4385            .task)
4386    }
4387
4388    pub async fn poll_workflow_task_response(
4389        &self,
4390        worker_id: &str,
4391        task_queue: &str,
4392        timeout: Duration,
4393    ) -> Result<PollWorkflowTaskResponse> {
4394        let poll_request_id = unique_request_id("rust-workflow-poll");
4395        self.poll_workflow_task_response_with_request_id(
4396            worker_id,
4397            task_queue,
4398            timeout,
4399            &poll_request_id,
4400            1,
4401        )
4402        .await
4403    }
4404
4405    async fn poll_workflow_task_response_with_request_id(
4406        &self,
4407        worker_id: &str,
4408        task_queue: &str,
4409        timeout: Duration,
4410        poll_request_id: &str,
4411        transport_retries: usize,
4412    ) -> Result<PollWorkflowTaskResponse> {
4413        let body = json!({
4414            "worker_id": worker_id,
4415            "task_queue": task_queue,
4416            "poll_request_id": poll_request_id,
4417            "timeout_seconds": long_poll_timeout_seconds(timeout),
4418            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4419        });
4420        let mut wire: Value = self
4421            .poll_request_json_unresolved(
4422                "/worker/workflow-tasks/poll",
4423                RequestProtocol::DefaultWorker,
4424                &body,
4425                timeout + Duration::from_secs(5),
4426                transport_retries,
4427            )
4428            .await?;
4429        let claim =
4430            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4431        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4432            self.resolve_runtime_payloads(
4433                &mut wire,
4434                "/worker/workflow-tasks/poll",
4435                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4436            )
4437            .await?;
4438            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4439            if let Some(task) = data.task.as_mut() {
4440                self.fetch_remaining_workflow_history(worker_id, task)
4441                    .await?;
4442            }
4443            Ok(data)
4444        })
4445        .await?;
4446        Ok(data)
4447    }
4448
4449    async fn fetch_remaining_workflow_history(
4450        &self,
4451        worker_id: &str,
4452        task: &mut WorkflowTask,
4453    ) -> Result<()> {
4454        let mut next_token = task.next_history_page_token.clone();
4455        let mut seen = BTreeSet::new();
4456
4457        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4458            if seen.len() >= 128 || !seen.insert(token.clone()) {
4459                return Err(Error::Codec(
4460                    "workflow history pagination exceeded its page bound or repeated a token"
4461                        .into(),
4462                ));
4463            }
4464            let lease_owner = task
4465                .lease_owner
4466                .clone()
4467                .unwrap_or_else(|| worker_id.to_string());
4468            let page = self
4469                .workflow_task_history_page(
4470                    &task.task_id,
4471                    &lease_owner,
4472                    task.workflow_task_attempt,
4473                    &token,
4474                )
4475                .await?;
4476
4477            task.append_history_page(page);
4478
4479            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4480                return Err(Error::Codec(
4481                    "workflow history pagination returned the same page token".to_string(),
4482                ));
4483            }
4484
4485            next_token = task.next_history_page_token.clone();
4486        }
4487
4488        Ok(())
4489    }
4490
4491    async fn workflow_task_history_page(
4492        &self,
4493        task_id: &str,
4494        lease_owner: &str,
4495        workflow_task_attempt: u64,
4496        next_history_page_token: &str,
4497    ) -> Result<WorkflowTaskHistoryPage> {
4498        let body = json!({
4499            "lease_owner": lease_owner,
4500            "workflow_task_attempt": workflow_task_attempt,
4501            "next_history_page_token": next_history_page_token
4502        });
4503        let path = format!("/worker/workflow-tasks/{task_id}/history");
4504
4505        self.request_json(
4506            reqwest::Method::POST,
4507            &path,
4508            RequestProtocol::DefaultWorker,
4509            Some(&body),
4510        )
4511        .await
4512    }
4513
4514    pub async fn complete_workflow_task(
4515        &self,
4516        task_id: &str,
4517        lease_owner: &str,
4518        workflow_task_attempt: u64,
4519        commands: Vec<Value>,
4520    ) -> Result<Value> {
4521        self.complete_workflow_task_with_message_streams(
4522            task_id,
4523            lease_owner,
4524            workflow_task_attempt,
4525            commands,
4526            Vec::new(),
4527            Vec::new(),
4528            None,
4529        )
4530        .await
4531    }
4532
4533    #[allow(clippy::too_many_arguments)]
4534    async fn complete_workflow_task_with_message_streams(
4535        &self,
4536        task_id: &str,
4537        lease_owner: &str,
4538        workflow_task_attempt: u64,
4539        commands: Vec<Value>,
4540        message_stream_cursors: Vec<Value>,
4541        message_stream_waits: Vec<Value>,
4542        sticky_cache: Option<Value>,
4543    ) -> Result<Value> {
4544        validate_workflow_task_commands(&commands)?;
4545        let has_message_stream_metadata =
4546            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4547        if has_message_stream_metadata
4548            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4549        {
4550            return Err(Error::Codec(
4551                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4552                    .to_string(),
4553            ));
4554        }
4555        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4556            &commands,
4557            has_message_stream_metadata,
4558        );
4559        let protocol_version = if sticky_cache.is_some()
4560            && protocol_version
4561                .strip_prefix("1.")
4562                .and_then(|minor| minor.parse::<u64>().ok())
4563                .is_some_and(|minor| minor < 18)
4564        {
4565            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4566        } else {
4567            protocol_version
4568        };
4569        let mut body = json!({
4570            "lease_owner": lease_owner,
4571            "workflow_task_attempt": workflow_task_attempt,
4572            "commands": commands
4573        });
4574        #[cfg(feature = "telemetry")]
4575        if self.observability_context_supported.load(Ordering::SeqCst)
4576            && opentelemetry::Context::current()
4577                .get::<telemetry::ExecutionFields>()
4578                .is_some()
4579        {
4580            if let Some(commands) = body["commands"].as_array_mut() {
4581                for command in commands {
4582                    if command.get("observability_context").is_none()
4583                        && matches!(
4584                            command["type"].as_str(),
4585                            Some("start_child_workflow" | "continue_as_new")
4586                        )
4587                    {
4588                        *command = self.with_observability_context(command.take());
4589                    }
4590                }
4591            }
4592        }
4593        if !message_stream_cursors.is_empty() {
4594            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4595        }
4596        if !message_stream_waits.is_empty() {
4597            body["message_stream_waits"] = Value::Array(message_stream_waits);
4598        }
4599        if let Some(claim) = sticky_cache {
4600            body["sticky_cache"] = claim;
4601        }
4602        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4603        self.request_json(
4604            reqwest::Method::POST,
4605            &path,
4606            RequestProtocol::Worker(protocol_version),
4607            Some(&body),
4608        )
4609        .await
4610    }
4611
4612    pub async fn fail_workflow_task(
4613        &self,
4614        task_id: &str,
4615        lease_owner: &str,
4616        workflow_task_attempt: u64,
4617        message: impl Into<String>,
4618    ) -> Result<Value> {
4619        self.fail_workflow_task_with_type(
4620            task_id,
4621            lease_owner,
4622            workflow_task_attempt,
4623            message,
4624            "RustWorkflowTaskFailure",
4625        )
4626        .await
4627    }
4628
4629    async fn fail_workflow_task_with_type(
4630        &self,
4631        task_id: &str,
4632        lease_owner: &str,
4633        workflow_task_attempt: u64,
4634        message: impl Into<String>,
4635        failure_type: &str,
4636    ) -> Result<Value> {
4637        self.fail_workflow_task_with_failure(
4638            task_id,
4639            lease_owner,
4640            workflow_task_attempt,
4641            json!({"message": message.into(), "type": failure_type}),
4642        )
4643        .await
4644    }
4645
4646    async fn fail_workflow_task_with_failure(
4647        &self,
4648        task_id: &str,
4649        lease_owner: &str,
4650        workflow_task_attempt: u64,
4651        failure: Value,
4652    ) -> Result<Value> {
4653        let body = json!({
4654            "lease_owner": lease_owner,
4655            "workflow_task_attempt": workflow_task_attempt,
4656            "failure": failure,
4657        });
4658        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4659        self.request_json(
4660            reqwest::Method::POST,
4661            &path,
4662            RequestProtocol::DefaultWorker,
4663            Some(&body),
4664        )
4665        .await
4666    }
4667
4668    pub async fn poll_activity_task(
4669        &self,
4670        worker_id: &str,
4671        task_queue: &str,
4672        timeout: Duration,
4673    ) -> Result<Option<ActivityTask>> {
4674        Ok(self
4675            .poll_activity_task_response(worker_id, task_queue, timeout)
4676            .await?
4677            .task)
4678    }
4679
4680    /// Poll an activity task while preserving server stop and drain metadata.
4681    pub async fn poll_activity_task_response(
4682        &self,
4683        worker_id: &str,
4684        task_queue: &str,
4685        timeout: Duration,
4686    ) -> Result<PollActivityTaskResponse> {
4687        let poll_request_id = unique_request_id("rust-activity-poll");
4688        self.poll_activity_task_response_with_request_id(
4689            worker_id,
4690            task_queue,
4691            timeout,
4692            &poll_request_id,
4693            1,
4694        )
4695        .await
4696        .map(worker_session::SessionPollResponse::ordinary)
4697    }
4698
4699    async fn poll_activity_task_response_with_request_id(
4700        &self,
4701        worker_id: &str,
4702        task_queue: &str,
4703        timeout: Duration,
4704        poll_request_id: &str,
4705        transport_retries: usize,
4706    ) -> Result<worker_session::SessionPollResponse> {
4707        let body = json!({
4708            "worker_id": worker_id,
4709            "task_queue": task_queue,
4710            "poll_request_id": poll_request_id,
4711            "timeout_seconds": long_poll_timeout_seconds(timeout),
4712        });
4713        let mut wire: Value = self
4714            .poll_request_json_unresolved(
4715                "/worker/activity-tasks/poll",
4716                RequestProtocol::DefaultWorker,
4717                &body,
4718                timeout + Duration::from_secs(5),
4719                transport_retries,
4720            )
4721            .await?;
4722        let lease =
4723            activity_lease::authority::Lease::confirm(self, &wire, worker_id, task_queue).await?;
4724        let observed = self.with_activity_lease_authority(
4725            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
4726        );
4727        let claim = if lease.is_none() {
4728            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
4729        } else {
4730            None
4731        };
4732        let loading = async {
4733            observed
4734                .resolve_runtime_payloads(
4735                    &mut wire,
4736                    "/worker/activity-tasks/poll",
4737                    RequestProtocol::DefaultWorker,
4738                )
4739                .await?;
4740            if let Some(lease) = &lease {
4741                lease
4742                    .authority
4743                    .refresh_delivery_session(&mut wire["task"])?;
4744            }
4745            Ok(serde_json::from_value(wire)?)
4746        };
4747        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
4748            Some(lease) => lease.authority.protect(loading).await?,
4749            None => {
4750                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
4751            }
4752        };
4753        if let Some(task) = data.task.as_mut() {
4754            task.hydration_claim = claim;
4755            task.activity_lease = lease;
4756        }
4757        Ok(data)
4758    }
4759
4760    pub async fn complete_activity_task<T: Serialize>(
4761        &self,
4762        task_id: &str,
4763        activity_attempt_id: &str,
4764        lease_owner: &str,
4765        result: T,
4766        codec: &str,
4767    ) -> Result<Value> {
4768        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4769        let body = json!({
4770            "activity_attempt_id": activity_attempt_id,
4771            "lease_owner": lease_owner,
4772            "result": result
4773        });
4774        let path = format!("/worker/activity-tasks/{task_id}/complete");
4775        activity_task_response(
4776            self.request_json(
4777                reqwest::Method::POST,
4778                &path,
4779                RequestProtocol::DefaultWorker,
4780                Some(&body),
4781            )
4782            .await,
4783            "complete",
4784            task_id,
4785            activity_attempt_id,
4786        )
4787    }
4788
4789    pub async fn fail_activity_task(
4790        &self,
4791        task_id: &str,
4792        activity_attempt_id: &str,
4793        lease_owner: &str,
4794        message: impl Into<String>,
4795        non_retryable: bool,
4796    ) -> Result<Value> {
4797        self.fail_activity_task_with_error(
4798            task_id,
4799            activity_attempt_id,
4800            lease_owner,
4801            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
4802        )
4803        .await
4804    }
4805
4806    /// Report an activity's application-defined failure type and retry marker.
4807    pub async fn fail_activity_task_with_error(
4808        &self,
4809        task_id: &str,
4810        activity_attempt_id: &str,
4811        lease_owner: &str,
4812        error: &ActivityError,
4813    ) -> Result<Value> {
4814        let error = error.validated();
4815        let body = json!({
4816            "activity_attempt_id": activity_attempt_id,
4817            "lease_owner": lease_owner,
4818            "failure": {
4819                "message": error.message,
4820                "type": error.exception_type,
4821                "non_retryable": error.non_retryable
4822            }
4823        });
4824        let path = format!("/worker/activity-tasks/{task_id}/fail");
4825        activity_task_response(
4826            self.request_json(
4827                reqwest::Method::POST,
4828                &path,
4829                RequestProtocol::DefaultWorker,
4830                Some(&body),
4831            )
4832            .await,
4833            "fail",
4834            task_id,
4835            activity_attempt_id,
4836        )
4837    }
4838
4839    /// Record a flat map of scalar/null activity progress metadata.
4840    ///
4841    /// Heartbeat details use the Server's bounded JSON progress contract.
4842    /// They are not workflow payload envelopes.
4843    pub async fn heartbeat_activity_task<T: Serialize>(
4844        &self,
4845        task_id: &str,
4846        activity_attempt_id: &str,
4847        lease_owner: &str,
4848        details: T,
4849    ) -> Result<ActivityHeartbeatResponse> {
4850        serde_json::from_value(
4851            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4852                .await?,
4853        )
4854        .map_err(Error::from)
4855    }
4856
4857    async fn heartbeat_activity_task_value<T: Serialize>(
4858        &self,
4859        task_id: &str,
4860        activity_attempt_id: &str,
4861        lease_owner: &str,
4862        details: T,
4863    ) -> Result<Value> {
4864        let details = AvroValue::from_serialize(&details)?.into_json()?;
4865        let body = json!({
4866            "activity_attempt_id": activity_attempt_id,
4867            "lease_owner": lease_owner,
4868            "details": details
4869        });
4870        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4871        let started = tokio::time::Instant::now();
4872        let response = activity_task_response(
4873            self.request_json(
4874                reqwest::Method::POST,
4875                &path,
4876                RequestProtocol::DefaultWorker,
4877                Some(&body),
4878            )
4879            .await,
4880            "heartbeat",
4881            task_id,
4882            activity_attempt_id,
4883        )?;
4884        if let Some(authority) = &self.activity_lease_authority {
4885            authority.progress(&response, started)?;
4886        }
4887        Ok(response)
4888    }
4889
4890    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4891        &self,
4892        method: reqwest::Method,
4893        path: &str,
4894        protocol: RequestProtocol,
4895        body: Option<&B>,
4896    ) -> Result<T> {
4897        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4898            .await
4899    }
4900
4901    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4902        &self,
4903        method: reqwest::Method,
4904        path: &str,
4905        protocol: RequestProtocol,
4906        body: Option<&B>,
4907        timeout: Duration,
4908    ) -> Result<T> {
4909        let mut value: Value = self
4910            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4911            .await?;
4912        let protocol = match protocol {
4913            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4914                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4915            }
4916            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4917        };
4918        self.resolve_runtime_payloads(&mut value, path, protocol)
4919            .await?;
4920        Ok(serde_json::from_value(value)?)
4921    }
4922
4923    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
4924        Ok(match protocol {
4925            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4926                let selected = self.worker_protocol_version.as_str();
4927                if self.cooperative_worker_protocol
4928                    && !cooperative_cancellation::supports_protocol(selected)
4929                {
4930                    return Err(Error::CooperativeCancellationUnavailable(
4931                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4932                    ));
4933                }
4934                if let RequestProtocol::Worker(minimum) = protocol {
4935                    let supported = minimum
4936                        .strip_prefix("1.")
4937                        .and_then(|minor| minor.parse::<u64>().ok())
4938                        .zip(
4939                            selected
4940                                .strip_prefix("1.")
4941                                .and_then(|minor| minor.parse::<u64>().ok()),
4942                        )
4943                        .is_some_and(|(minimum, selected)| selected >= minimum);
4944                    if !supported {
4945                        return Err(Error::WorkerLoop(format!(
4946                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4947                        )));
4948                    }
4949                }
4950                RequestProtocol::Worker(selected)
4951            }
4952            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4953        })
4954    }
4955
4956    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
4957        match &self.activity_lease_authority {
4958            Some(authority) => authority.check(path, body),
4959            None => Ok(()),
4960        }
4961    }
4962
4963    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4964        &self,
4965        method: reqwest::Method,
4966        path: &str,
4967        protocol: RequestProtocol,
4968        body: Option<&B>,
4969        timeout: Duration,
4970    ) -> Result<T> {
4971        #[cfg(feature = "telemetry")]
4972        self.begin_observability_discovery(&method, path);
4973        let protocol = self.worker_request_protocol(protocol)?;
4974        let auth_token = self.auth_token(protocol)?;
4975        let mut request = self
4976            .http
4977            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4978            .timeout(timeout)
4979            .header(reqwest::header::ACCEPT, "application/json")
4980            .header(reqwest::header::CONTENT_TYPE, "application/json")
4981            .header("X-Namespace", &self.namespace);
4982
4983        match protocol {
4984            RequestProtocol::DefaultWorker => {
4985                request = request.header(
4986                    "X-Durable-Workflow-Protocol-Version",
4987                    self.worker_protocol_version.as_str(),
4988                );
4989            }
4990            RequestProtocol::Worker(version) => {
4991                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4992            }
4993            RequestProtocol::ControlPlane => {
4994                request = request.header(
4995                    "X-Durable-Workflow-Control-Plane-Version",
4996                    CONTROL_PLANE_VERSION,
4997                );
4998            }
4999        }
5000
5001        if let Some(token) = auth_token {
5002            request = request.bearer_auth(token);
5003        }
5004
5005        if let Some(body) = body {
5006            let mut body = serde_json::to_value(body)?;
5007            if matches!(
5008                method,
5009                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5010            ) {
5011                self.check_activity_lease_request(path, Some(&body))?;
5012                self.externalize_runtime_payloads(&mut body, path, protocol)
5013                    .await?;
5014                self.check_activity_lease_request(path, Some(&body))?;
5015            }
5016            request = request.json(&body);
5017        }
5018
5019        let request = request.build()?;
5020        let request_body = request
5021            .body()
5022            .and_then(reqwest::Body::as_bytes)
5023            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5024        let poll_request_id = path.ends_with("/poll").then(|| {
5025            request_body
5026                .as_ref()
5027                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5028                .unwrap_or_default()
5029        });
5030        let mut storage_retries = 0_usize;
5031        let mut deferred_workflow_completion = false;
5032
5033        loop {
5034            // Keep the serialized body and lease/poll identity across admission pauses.
5035            self.check_activity_lease_request(path, request_body.as_ref())?;
5036            let receive = async {
5037                let response = self
5038                    .http
5039                    .execute(request.try_clone().ok_or_else(|| {
5040                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5041                    })?)
5042                    .await?;
5043                let status = response.status();
5044                Ok::<_, Error>((status, response.bytes().await?))
5045            };
5046            let retry_deadline = self
5047                .worker_storage_admission
5048                .as_ref()
5049                .and_then(|admission| admission.workflow_completion_retry_deadline);
5050            if deferred_workflow_completion
5051                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5052            {
5053                return Err(Error::Timeout);
5054            }
5055            let received = async {
5056                match retry_deadline.filter(|_| deferred_workflow_completion) {
5057                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5058                        .await
5059                        .map_err(|_| Error::Timeout)?,
5060                    None => receive.await,
5061                }
5062            };
5063            let (status, bytes) = match self
5064                .activity_lease_authority
5065                .as_ref()
5066                .filter(|authority| authority.governs(path))
5067            {
5068                Some(authority) => authority.protect(received).await?,
5069                None => received.await?,
5070            };
5071
5072            if !status.is_success() {
5073                let body = String::from_utf8_lossy(&bytes).to_string();
5074                if let Some(protocol) = protocol_failure(status, &body) {
5075                    return Err(Error::Protocol(protocol));
5076                }
5077                let error = Error::Http { status, body };
5078                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5079                    &error,
5080                    path,
5081                    request_body.as_ref(),
5082                )
5083                .is_some();
5084                if self
5085                    .wait_for_storage_admission(
5086                        &error,
5087                        protocol,
5088                        Some(path),
5089                        poll_request_id.as_deref(),
5090                        request_body.as_ref(),
5091                        &mut storage_retries,
5092                    )
5093                    .await
5094                {
5095                    continue;
5096                }
5097                return Err(error);
5098            }
5099
5100            if bytes.is_empty() {
5101                return Ok(serde_json::from_value(Value::Null)?);
5102            }
5103
5104            #[cfg(feature = "telemetry")]
5105            return self.decode_observability_response(
5106                &method,
5107                path,
5108                request_body.as_ref(),
5109                &bytes,
5110            );
5111
5112            #[cfg(not(feature = "telemetry"))]
5113            return Ok(serde_json::from_slice(&bytes)?);
5114        }
5115    }
5116
5117    #[cfg(feature = "telemetry")]
5118    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5119        if *method == reqwest::Method::GET && path == "/cluster/info" {
5120            self.observability_context_supported
5121                .store(false, Ordering::SeqCst);
5122        }
5123    }
5124
5125    #[cfg(feature = "telemetry")]
5126    fn decode_observability_response<T: DeserializeOwned>(
5127        &self,
5128        method: &reqwest::Method,
5129        path: &str,
5130        request_body: Option<&Value>,
5131        bytes: &[u8],
5132    ) -> Result<T> {
5133        if *method == reqwest::Method::POST
5134            && self.execution_telemetry.is_some()
5135            && matches!(
5136                path,
5137                "/worker/workflow-tasks/poll"
5138                    | "/worker/activity-tasks/poll"
5139                    | "/worker/query-tasks/poll"
5140            )
5141        {
5142            let mut wire: Value = serde_json::from_slice(bytes)?;
5143            telemetry::carrier::retain_poll_observations(
5144                &mut wire,
5145                request_body.unwrap_or(&Value::Null),
5146                path,
5147                &self.namespace,
5148            );
5149            return Ok(serde_json::from_value(wire)?);
5150        }
5151        if *method == reqwest::Method::GET && path == "/cluster/info" {
5152            let info: Value = serde_json::from_slice(bytes)?;
5153            self.observability_context_supported
5154                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5155            return Ok(serde_json::from_value(info)?);
5156        }
5157        Ok(serde_json::from_slice(bytes)?)
5158    }
5159
5160    async fn wait_for_storage_admission(
5161        &self,
5162        error: &Error,
5163        protocol: RequestProtocol,
5164        path: Option<&str>,
5165        poll_request_id: Option<&str>,
5166        request_body: Option<&Value>,
5167        retries: &mut usize,
5168    ) -> bool {
5169        let Some(admission) = self
5170            .worker_storage_admission
5171            .as_ref()
5172            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5173        else {
5174            return false;
5175        };
5176        let completion_deferred = path.and_then(|path| {
5177            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5178        });
5179        let Some(advertised_delay) = completion_deferred
5180            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5181            .or_else(|| {
5182                path.and_then(|path| {
5183                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5184                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5185                })
5186            })
5187        else {
5188            return false;
5189        };
5190        *retries = retries.saturating_add(1);
5191        let delay = worker_retry_delay(admission.policy, *retries)
5192            .max(advertised_delay)
5193            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
5194        let delay = if completion_deferred.is_some() {
5195            delay.max(advertised_delay)
5196        } else {
5197            delay
5198        };
5199        let wait_deadline = tokio::time::Instant::now() + delay;
5200        loop {
5201            if admission.stop.load(Ordering::SeqCst) {
5202                return false;
5203            }
5204            let now = tokio::time::Instant::now();
5205            if admission
5206                .workflow_completion_retry_deadline
5207                .is_some_and(|deadline| now >= deadline)
5208            {
5209                return false;
5210            }
5211            let remaining = wait_deadline.saturating_duration_since(now);
5212            if remaining.is_zero() {
5213                return true;
5214            }
5215            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
5216        }
5217    }
5218
5219    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5220        &self,
5221        path: &str,
5222        protocol: RequestProtocol,
5223        body: &B,
5224        timeout: Duration,
5225        max_retries: usize,
5226    ) -> Result<T> {
5227        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
5228            .await
5229    }
5230
5231    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
5232        &self,
5233        path: &str,
5234        protocol: RequestProtocol,
5235        body: &B,
5236        timeout: Duration,
5237        max_retries: usize,
5238    ) -> Result<T> {
5239        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
5240            .await
5241    }
5242
5243    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
5244        &self,
5245        path: &str,
5246        protocol: RequestProtocol,
5247        body: &B,
5248        timeout: Duration,
5249        max_retries: usize,
5250        resolve: bool,
5251    ) -> Result<T> {
5252        let mut retries = 0;
5253
5254        loop {
5255            let response: Result<Value> = if resolve {
5256                self.request_json_with_timeout(
5257                    reqwest::Method::POST,
5258                    path,
5259                    protocol,
5260                    Some(body),
5261                    timeout,
5262                )
5263                .await
5264            } else {
5265                self.request_json_unresolved_with_timeout(
5266                    reqwest::Method::POST,
5267                    path,
5268                    protocol,
5269                    Some(body),
5270                    timeout,
5271                )
5272                .await
5273            };
5274
5275            match response {
5276                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
5277                response => {
5278                    let value = worker_poll_response(response)?;
5279                    if value.get("task").is_some_and(|task| !task.is_null()) {
5280                        if let Some(slot) = &self.worker_task_slot {
5281                            slot.claimed();
5282                        }
5283                    }
5284                    return Ok(serde_json::from_value(value)?);
5285                }
5286            }
5287        }
5288    }
5289
5290    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
5291        match protocol {
5292            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5293                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
5294                    return Ok(Some(token));
5295                }
5296                if self.control_token.is_some() {
5297                    return Err(Error::MissingRoleCredentials {
5298                        role: "worker",
5299                        opposite_role: "control",
5300                    });
5301                }
5302                Ok(None)
5303            }
5304            RequestProtocol::ControlPlane => {
5305                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
5306                    return Ok(Some(token));
5307                }
5308                if self.worker_token.is_some() {
5309                    return Err(Error::MissingRoleCredentials {
5310                        role: "control",
5311                        opposite_role: "worker",
5312                    });
5313                }
5314                Ok(None)
5315            }
5316        }
5317    }
5318}
5319
5320fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
5321    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5322    let reason = body
5323        .get("reason")
5324        .and_then(Value::as_str)
5325        .unwrap_or("query_rejected")
5326        .to_string();
5327    let message = body
5328        .get("message")
5329        .or_else(|| body.get("error"))
5330        .and_then(Value::as_str)
5331        .unwrap_or("workflow query was rejected")
5332        .to_string();
5333
5334    QueryFailure {
5335        status: status.as_u16(),
5336        reason,
5337        message,
5338        body,
5339    }
5340}
5341
5342fn workflow_command_result(
5343    command: WorkflowCommandKind,
5344    data: Value,
5345    workflow_id: &str,
5346    run_id: Option<&str>,
5347) -> WorkflowCommandResult {
5348    WorkflowCommandResult {
5349        command,
5350        workflow_id: data
5351            .get("workflow_id")
5352            .and_then(Value::as_str)
5353            .unwrap_or(workflow_id)
5354            .to_string(),
5355        run_id: data
5356            .get("run_id")
5357            .and_then(Value::as_str)
5358            .or(run_id)
5359            .map(str::to_string),
5360        outcome: data
5361            .get("outcome")
5362            .and_then(Value::as_str)
5363            .map(str::to_string),
5364        reason: data
5365            .get("reason")
5366            .and_then(Value::as_str)
5367            .map(str::to_string),
5368        command_status: data
5369            .get("command_status")
5370            .and_then(Value::as_str)
5371            .map(str::to_string),
5372        raw: data,
5373    }
5374}
5375
5376fn workflow_command_rejection(
5377    command: WorkflowCommandKind,
5378    status: reqwest::StatusCode,
5379    raw_body: String,
5380    workflow_id: &str,
5381    run_id: Option<&str>,
5382) -> WorkflowCommandRejection {
5383    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5384    WorkflowCommandRejection {
5385        command,
5386        status: status.as_u16(),
5387        reason: body
5388            .get("reason")
5389            .and_then(Value::as_str)
5390            .unwrap_or("workflow_command_rejected")
5391            .to_string(),
5392        message: body
5393            .get("message")
5394            .or_else(|| body.get("error"))
5395            .and_then(Value::as_str)
5396            .unwrap_or("workflow lifecycle command was rejected")
5397            .to_string(),
5398        workflow_id: body
5399            .get("workflow_id")
5400            .and_then(Value::as_str)
5401            .unwrap_or(workflow_id)
5402            .to_string(),
5403        run_id: body
5404            .get("run_id")
5405            .and_then(Value::as_str)
5406            .or(run_id)
5407            .map(str::to_string),
5408        target_scope: body
5409            .get("target_scope")
5410            .and_then(Value::as_str)
5411            .map(str::to_string),
5412        body,
5413    }
5414}
5415
5416fn query_task_response(response: Result<Value>) -> Result<Value> {
5417    match response {
5418        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
5419        response => response,
5420    }
5421}
5422
5423fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
5424    match response {
5425        Err(Error::Http { status, body })
5426            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5427        {
5428            Ok(serde_json::from_str(&body)?)
5429        }
5430        response => response,
5431    }
5432}
5433
5434fn worker_poll_body_is_stop(body: &str) -> bool {
5435    serde_json::from_str::<Value>(body)
5436        .ok()
5437        .is_some_and(|body| {
5438            worker_poll_is_stop(
5439                body.get("poll_status").and_then(Value::as_str),
5440                body.get("reason").and_then(Value::as_str),
5441            )
5442        })
5443}
5444
5445fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5446    matches!(poll_status, Some("draining" | "stopped"))
5447        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5448}
5449
5450fn query_task_rejection_is_final(error: &Error) -> bool {
5451    matches!(
5452        error,
5453        Error::QueryFailed(failure)
5454            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5455    )
5456}
5457
5458fn activity_task_response<T>(
5459    response: Result<T>,
5460    operation: &str,
5461    task_id: &str,
5462    activity_attempt_id: &str,
5463) -> Result<T> {
5464    match response {
5465        Err(Error::Http { status, body }) => {
5466            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5467            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5468                operation: operation.to_string(),
5469                status: status.as_u16(),
5470                reason: body
5471                    .get("reason")
5472                    .and_then(Value::as_str)
5473                    .unwrap_or("activity_task_rejected")
5474                    .to_string(),
5475                task_id: body
5476                    .get("task_id")
5477                    .and_then(Value::as_str)
5478                    .unwrap_or(task_id)
5479                    .to_string(),
5480                activity_attempt_id: body
5481                    .get("activity_attempt_id")
5482                    .and_then(Value::as_str)
5483                    .unwrap_or(activity_attempt_id)
5484                    .to_string(),
5485                cancel_requested: body
5486                    .get("cancel_requested")
5487                    .and_then(Value::as_bool)
5488                    .unwrap_or(false),
5489                can_continue: body.get("can_continue").and_then(Value::as_bool),
5490                run_closed_reason: body
5491                    .get("run_closed_reason")
5492                    .and_then(Value::as_str)
5493                    .map(str::to_string),
5494                body,
5495            }))
5496        }
5497        response => response,
5498    }
5499}
5500
5501fn activity_task_rejection_is_final(error: &Error) -> bool {
5502    matches!(
5503        error,
5504        Error::ActivityTaskRejected(rejection)
5505            if matches!(
5506                rejection.reason.as_str(),
5507                "run_cancelled"
5508                    | "run_terminated"
5509                    | "attempt_closed"
5510                    | "stale_attempt"
5511                    | "activity_cancelled"
5512                    | "task_cancelled"
5513                    | "run_closed"
5514                    | "activity_not_running"
5515                    | "attempt_not_found"
5516            )
5517    )
5518}
5519
5520fn workflow_task_completion_is_terminal_timeout(
5521    error: &Error,
5522    task_id: &str,
5523    workflow_task_attempt: u64,
5524    run_id: Option<&str>,
5525) -> bool {
5526    let Error::Http { status, body } = error else {
5527        return false;
5528    };
5529    if *status != reqwest::StatusCode::CONFLICT {
5530        return false;
5531    }
5532
5533    let Some(run_id) = run_id else {
5534        return false;
5535    };
5536    let Ok(body) = serde_json::from_str::<Value>(body) else {
5537        return false;
5538    };
5539
5540    body.get("recorded").and_then(Value::as_bool) == Some(false)
5541        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5542        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5543        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5544        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5545        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5546}
5547
5548fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5549    let body: Value = serde_json::from_str(raw_body).ok()?;
5550    let reason = body.get("reason")?.as_str()?;
5551    if !matches!(
5552        reason,
5553        "missing_protocol_version"
5554            | "unsupported_protocol_version"
5555            | "missing_control_plane_version"
5556            | "unsupported_control_plane_version"
5557    ) {
5558        return None;
5559    }
5560
5561    Some(ProtocolFailure {
5562        status: status.as_u16(),
5563        reason: reason.to_string(),
5564        message: body
5565            .get("message")
5566            .or_else(|| body.get("error"))
5567            .and_then(Value::as_str)
5568            .unwrap_or("protocol version rejected")
5569            .to_string(),
5570        supported_version: body
5571            .get("supported_version")
5572            .and_then(Value::as_str)
5573            .map(str::to_string),
5574        requested_version: body
5575            .get("requested_version")
5576            .and_then(Value::as_str)
5577            .map(str::to_string),
5578        body,
5579    })
5580}
5581
5582fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5583    timeout
5584        .as_secs()
5585        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5586        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5587}
5588
5589fn worker_operation_is_retryable(error: &Error) -> bool {
5590    if worker_poll_capacity_retry_after(error).is_some()
5591        || worker_storage_admission_body(error).is_some()
5592        || worker_backend_unavailable_body(error).is_some()
5593        || worker_operation_is_explicitly_non_retryable(error)
5594    {
5595        return false;
5596    }
5597
5598    match error {
5599        Error::Transport(error) => {
5600            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5601        }
5602        Error::Http { status, .. } => {
5603            matches!(
5604                *status,
5605                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5606            ) || status.is_server_error()
5607        }
5608        _ => false,
5609    }
5610}
5611
5612fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5613    let body: Value = match error {
5614        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5615        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5616        _ => return None,
5617    };
5618    matches!(
5619        body.get("reason").and_then(Value::as_str),
5620        Some("storage_pressure" | "storage_admission_unavailable")
5621    )
5622    .then_some(body)
5623}
5624
5625fn worker_storage_admission_retry_after(
5626    error: &Error,
5627    poll_request_id: Option<&str>,
5628) -> Option<Duration> {
5629    let Error::Http { status, .. } = error else {
5630        return None;
5631    };
5632    let body = worker_storage_admission_body(error)?;
5633    let delay = body.get("retry_after_seconds")?.as_u64()?;
5634    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5635        || delay == 0
5636        || body.get("retryable") != Some(&Value::Bool(true))
5637        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5638        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5639        || body
5640            .get("request_admitted")
5641            .is_some_and(|admitted| admitted != &Value::Bool(false))
5642    {
5643        return None;
5644    }
5645    match poll_request_id {
5646        Some(id) => {
5647            if id.is_empty()
5648                || body.get("task") != Some(&Value::Null)
5649                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5650                || body.get("poll_status") != body.get("reason")
5651                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5652                || body.get("claim_admitted") != Some(&Value::Bool(false))
5653            {
5654                return None;
5655            }
5656        }
5657        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5658        None => {}
5659    }
5660    Some(Duration::from_secs(delay))
5661}
5662
5663fn worker_backend_unavailable_retry_after(
5664    error: &Error,
5665    path: &str,
5666    poll_request_id: Option<&str>,
5667) -> Option<Duration> {
5668    let operation = match path {
5669        "/worker/register" => "register_worker",
5670        "/worker/heartbeat" => "heartbeat_worker",
5671        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5672        "/worker/activity-tasks/poll" => "poll_activity_task",
5673        "/worker/query-tasks/poll" => "poll_query_task",
5674        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5675        _ => return None,
5676    };
5677    let body = worker_backend_unavailable_body(error)?;
5678    let delay = body.get("retry_after_seconds")?.as_u64()?;
5679    if delay == 0
5680        || body.get("operation")?.as_str()? != operation
5681        || body.get("outcome")?.as_str()? != "unknown"
5682        || body.get("retryable") != Some(&Value::Bool(true))
5683        || body.get("worker_id")?.as_str()?.is_empty()
5684    {
5685        return None;
5686    }
5687    if let Some(id) = poll_request_id {
5688        if id.is_empty()
5689            || body.get("task") != Some(&Value::Null)
5690            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5691            || body.get("poll_request_id")?.as_str()? != id
5692            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5693        {
5694            return None;
5695        }
5696    } else if path.ends_with("/poll") {
5697        return None;
5698    }
5699    Some(Duration::from_secs(delay))
5700}
5701
5702fn worker_fenced_completion_retry_after(
5703    error: &Error,
5704    path: &str,
5705    request_body: Option<&Value>,
5706) -> Option<Duration> {
5707    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5708        .strip_prefix("/worker/workflow-tasks/")
5709        .and_then(|tail| tail.strip_suffix("/complete"))
5710    {
5711        ("complete_workflow_task", task_id, "workflow_task_attempt")
5712    } else if let Some(task_id) = path
5713        .strip_prefix("/worker/activity-tasks/")
5714        .and_then(|tail| tail.strip_suffix("/complete"))
5715    {
5716        ("complete_activity_task", task_id, "activity_attempt_id")
5717    } else {
5718        return None;
5719    };
5720    if task_id.is_empty() || task_id.contains('/') {
5721        return None;
5722    }
5723
5724    let request = request_body?.as_object()?;
5725    let lease_owner = request.get("lease_owner")?.as_str()?;
5726    if lease_owner.is_empty() {
5727        return None;
5728    }
5729    let attempt = request.get(attempt_field)?;
5730    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5731        || (attempt_field == "activity_attempt_id"
5732            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5733    {
5734        return None;
5735    }
5736
5737    let body = worker_backend_unavailable_body(error)?;
5738    let delay = body.get("retry_after_seconds")?.as_u64()?;
5739    if delay == 0
5740        || body.get("operation")?.as_str()? != operation
5741        || body.get("outcome")?.as_str()? != "unknown"
5742        || body.get("retryable") != Some(&Value::Bool(true))
5743        || body.get("worker_id")?.as_str()? != lease_owner
5744        || body.get("task_queue") != Some(&Value::Null)
5745        || body.get("task_id")?.as_str()? != task_id
5746        || body.get("lease_owner")?.as_str()? != lease_owner
5747        || body.get(attempt_field) != Some(attempt)
5748    {
5749        return None;
5750    }
5751
5752    Some(Duration::from_secs(delay))
5753}
5754
5755fn worker_deferred_workflow_completion_retry_after(
5756    error: &Error,
5757    path: &str,
5758    request_body: Option<&Value>,
5759) -> Option<Duration> {
5760    let task_id = path
5761        .strip_prefix("/worker/workflow-tasks/")?
5762        .strip_suffix("/complete")?;
5763    if task_id.is_empty() || task_id.contains('/') {
5764        return None;
5765    }
5766    let request = request_body?.as_object()?;
5767    let owner = request.get("lease_owner")?.as_str()?;
5768    let attempt = request.get("workflow_task_attempt")?;
5769    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5770        return None;
5771    }
5772    let Error::Http { status, body } = error else {
5773        return None;
5774    };
5775    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5776        return None;
5777    }
5778    let body: Value = serde_json::from_str(body).ok()?;
5779    let delay = body.get("retry_after_seconds")?.as_u64()?;
5780    if !(1..=5).contains(&delay)
5781        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5782        || body.get("operation")?.as_str()? != "complete_workflow_task"
5783        || body.get("outcome")?.as_str()? != "deferred"
5784        || body.get("recorded") != Some(&Value::Bool(false))
5785        || body.get("retryable") != Some(&Value::Bool(true))
5786        || body.get("task_id")?.as_str()? != task_id
5787        || body.get("lease_owner")?.as_str()? != owner
5788        || body.get("workflow_task_attempt") != Some(attempt)
5789        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5790    {
5791        return None;
5792    }
5793    Some(Duration::from_secs(delay))
5794}
5795
5796fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5797    let Error::Http { status, body } = error else {
5798        return None;
5799    };
5800    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5801        return None;
5802    }
5803    let body: Value = serde_json::from_str(body).ok()?;
5804    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5805}
5806
5807fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5808    let Error::Http { body, .. } = error else {
5809        return false;
5810    };
5811
5812    serde_json::from_str::<Value>(body)
5813        .ok()
5814        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5815        == Some(false)
5816}
5817
5818fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5819    let Error::Http { status, body } = error else {
5820        return None;
5821    };
5822    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5823        return None;
5824    }
5825
5826    let body = serde_json::from_str::<Value>(body).ok()?;
5827    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5828        == Some("long_poll_capacity_exhausted")
5829        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5830    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5831        return None;
5832    }
5833
5834    Some(Duration::from_secs(
5835        body.get("retry_after_seconds")
5836            .and_then(Value::as_u64)
5837            .unwrap_or_default(),
5838    ))
5839}
5840
5841fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5842    let exponent = retry.saturating_sub(1).min(31) as u32;
5843    policy
5844        .initial_backoff
5845        .saturating_mul(1_u32 << exponent)
5846        .min(policy.max_backoff)
5847}
5848
5849#[derive(Debug)]
5850pub struct ClientBuilder {
5851    base_url: String,
5852    token: Option<String>,
5853    control_token: Option<String>,
5854    worker_token: Option<String>,
5855    namespace: String,
5856    timeout: Duration,
5857    max_external_payload_bytes: usize,
5858    worker_protocol_version: WorkerProtocolVersion,
5859    additional_root_certificates: Vec<reqwest::Certificate>,
5860}
5861
5862impl ClientBuilder {
5863    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5864    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5865        self.worker_protocol_version = version;
5866        self
5867    }
5868
5869    pub fn token(mut self, token: Option<String>) -> Self {
5870        self.token = token;
5871        self
5872    }
5873
5874    pub fn control_token(mut self, token: Option<String>) -> Self {
5875        self.control_token = token;
5876        self
5877    }
5878
5879    pub fn worker_token(mut self, token: Option<String>) -> Self {
5880        self.worker_token = token;
5881        self
5882    }
5883
5884    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5885        self.namespace = namespace.into();
5886        self
5887    }
5888
5889    pub fn timeout(mut self, timeout: Duration) -> Self {
5890        self.timeout = timeout;
5891        self
5892    }
5893
5894    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5895    /// References are fetched only from this client's authenticated runtime.
5896    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5897        self.max_external_payload_bytes = bytes;
5898        self
5899    }
5900
5901    pub fn build(self) -> Result<Client> {
5902        let base_url = self.base_url.trim_end_matches('/').to_string();
5903        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5904            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5905            .unwrap_or_else(|_| base_url.ends_with("/api"));
5906
5907        if has_sdk_api_suffix {
5908            return Err(Error::InvalidBaseUrl);
5909        }
5910
5911        let mut http = reqwest::Client::builder()
5912            .timeout(self.timeout)
5913            .redirect(reqwest::redirect::Policy::none());
5914        for certificate in self.additional_root_certificates {
5915            http = http.add_root_certificate(certificate);
5916        }
5917        Ok(Client {
5918            http: http.build()?,
5919            hydration_timeout: self.timeout,
5920            base_url,
5921            token: self.token,
5922            control_token: self.control_token,
5923            worker_token: self.worker_token,
5924            namespace: self.namespace,
5925            max_external_payload_bytes: self.max_external_payload_bytes,
5926            worker_storage_admission: None,
5927            worker_task_slot: None,
5928            cooperative_worker_protocol: false,
5929            worker_protocol_version: self.worker_protocol_version,
5930            local_activities_enabled: false,
5931            worker_sessions_enabled: false,
5932            max_concurrent_worker_sessions: 10,
5933            worker_build_id: None,
5934            sticky_cache: None,
5935            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5936            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
5937            activity_lease_authority: None,
5938            #[cfg(feature = "telemetry")]
5939            execution_telemetry: None,
5940            #[cfg(feature = "telemetry")]
5941            observability_context_supported: Arc::new(AtomicBool::new(false)),
5942        })
5943    }
5944}
5945
5946#[derive(Clone, Debug)]
5947pub struct WorkflowHandle {
5948    client: Client,
5949    pub workflow_id: String,
5950    pub run_id: Option<String>,
5951    pub workflow_type: String,
5952}
5953
5954impl WorkflowHandle {
5955    /// Describe whichever run is current for this stable workflow instance.
5956    pub async fn describe(&self) -> Result<WorkflowDescription> {
5957        self.client.describe_workflow(&self.workflow_id).await
5958    }
5959
5960    /// Describe the run identity originally selected by this handle.
5961    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5962        let run_id = self.run_id.as_deref().ok_or_else(|| {
5963            Error::Codec("run_id is required for selected-run description".to_string())
5964        })?;
5965        self.client
5966            .describe_workflow_run(&self.workflow_id, run_id)
5967            .await
5968    }
5969
5970    /// Signal this workflow with an SDK-generated caller command key.
5971    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5972        self.client
5973            .signal_workflow(&self.workflow_id, signal_name, input)
5974            .await
5975    }
5976
5977    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
5978    pub async fn signal_with_request_id<T: Serialize>(
5979        &self,
5980        signal_name: &str,
5981        input: T,
5982        request_id: &str,
5983    ) -> Result<Value> {
5984        self.client
5985            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
5986            .await
5987    }
5988
5989    pub async fn append_message<T: Serialize>(
5990        &self,
5991        stream_name: &str,
5992        message_id: &str,
5993        input: T,
5994    ) -> Result<Value> {
5995        self.client
5996            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5997            .await
5998    }
5999
6000    /// Signal only if this handle's selected run is still current, with an
6001    /// SDK-generated caller command key.
6002    pub async fn signal_selected_run<T: Serialize>(
6003        &self,
6004        signal_name: &str,
6005        input: T,
6006    ) -> Result<Value> {
6007        let run_id = self.run_id.as_deref().ok_or_else(|| {
6008            Error::Codec("run_id is required for selected-run signaling".to_string())
6009        })?;
6010        self.client
6011            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
6012            .await
6013    }
6014
6015    /// Signal only if this handle's selected run is still current, with an
6016    /// explicit caller command key (1 to 255 Unicode characters).
6017    pub async fn signal_selected_run_with_request_id<T: Serialize>(
6018        &self,
6019        signal_name: &str,
6020        input: T,
6021        request_id: &str,
6022    ) -> Result<Value> {
6023        let run_id = self.run_id.as_deref().ok_or_else(|| {
6024            Error::Codec("run_id is required for selected-run signaling".to_string())
6025        })?;
6026        self.client
6027            .signal_workflow_run_with_request_id(
6028                &self.workflow_id,
6029                run_id,
6030                signal_name,
6031                input,
6032                request_id,
6033            )
6034            .await
6035    }
6036
6037    /// Close whichever run is current as cancelled, without workflow cleanup.
6038    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
6039        self.client
6040            .cancel_workflow(&self.workflow_id, options)
6041            .await
6042    }
6043
6044    /// Request cancellation only if this handle's selected run is still current.
6045    pub async fn cancel_selected_run(
6046        &self,
6047        options: WorkflowCommandOptions,
6048    ) -> Result<WorkflowCommandResult> {
6049        let run_id = self.run_id.as_deref().ok_or_else(|| {
6050            Error::Codec("run_id is required for selected-run cancellation".to_string())
6051        })?;
6052        self.client
6053            .cancel_workflow_run(&self.workflow_id, run_id, options)
6054            .await
6055    }
6056
6057    /// Forcefully terminate whichever run is current.
6058    pub async fn terminate(
6059        &self,
6060        options: WorkflowCommandOptions,
6061    ) -> Result<WorkflowCommandResult> {
6062        self.client
6063            .terminate_workflow(&self.workflow_id, options)
6064            .await
6065    }
6066
6067    /// Terminate only if this handle's selected run is still current.
6068    pub async fn terminate_selected_run(
6069        &self,
6070        options: WorkflowCommandOptions,
6071    ) -> Result<WorkflowCommandResult> {
6072        let run_id = self.run_id.as_deref().ok_or_else(|| {
6073            Error::Codec("run_id is required for selected-run termination".to_string())
6074        })?;
6075        self.client
6076            .terminate_workflow_run(&self.workflow_id, run_id, options)
6077            .await
6078    }
6079
6080    /// Continue this handle's failed run without repeating completed activities.
6081    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
6082        let run_id = self
6083            .run_id
6084            .as_deref()
6085            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
6086        self.client
6087            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
6088            .await
6089    }
6090
6091    /// Execute a named, read-only query against this workflow.
6092    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
6093        self.client
6094            .query_workflow(&self.workflow_id, query_name, input)
6095            .await
6096    }
6097
6098    pub async fn query_avro_value<T: Serialize>(
6099        &self,
6100        query_name: &str,
6101        input: T,
6102    ) -> Result<AvroValue> {
6103        self.client
6104            .query_workflow_avro_value(&self.workflow_id, query_name, input)
6105            .await
6106    }
6107
6108    pub async fn update<T: Serialize>(
6109        &self,
6110        update_name: &str,
6111        input: T,
6112        request_id: Option<&str>,
6113    ) -> Result<Value> {
6114        self.client
6115            .update_workflow(&self.workflow_id, update_name, input, request_id)
6116            .await
6117    }
6118
6119    pub async fn update_avro_value<T: Serialize>(
6120        &self,
6121        update_name: &str,
6122        input: T,
6123        request_id: Option<&str>,
6124    ) -> Result<AvroValue> {
6125        self.client
6126            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
6127            .await
6128    }
6129
6130    /// Query only if this handle's selected run is still current.
6131    pub async fn query_selected_run<T: Serialize>(
6132        &self,
6133        query_name: &str,
6134        input: T,
6135    ) -> Result<Value> {
6136        let run_id = self
6137            .run_id
6138            .as_deref()
6139            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
6140        self.client
6141            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
6142            .await
6143    }
6144
6145    /// Await the final terminal outcome of the current continue-as-new chain.
6146    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
6147        self.result_target(options, None).await
6148    }
6149
6150    /// Await the final result without projecting Avro bytes through JSON.
6151    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
6152        self.result_avro_value_target(options, None).await
6153    }
6154
6155    /// Await the final result and decode it into a Serde application type.
6156    pub async fn result_typed<T: DeserializeOwned>(
6157        &self,
6158        options: WorkflowResultOptions,
6159    ) -> Result<T> {
6160        let result = self.result_avro_value(options).await?;
6161        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6162    }
6163
6164    /// Await only the run identity originally selected by this handle.
6165    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
6166        let run_id = self.run_id.as_deref().ok_or_else(|| {
6167            Error::Codec("run_id is required for selected-run result".to_string())
6168        })?;
6169        self.result_target(options, Some(run_id)).await
6170    }
6171
6172    /// Await the selected run's result on the lossless Avro Value surface.
6173    pub async fn result_selected_run_avro_value(
6174        &self,
6175        options: WorkflowResultOptions,
6176    ) -> Result<AvroValue> {
6177        let run_id = self.run_id.as_deref().ok_or_else(|| {
6178            Error::Codec("run_id is required for selected-run result".to_string())
6179        })?;
6180        self.result_avro_value_target(options, Some(run_id)).await
6181    }
6182
6183    /// Await the selected run and decode its result into a Serde type.
6184    pub async fn result_selected_run_typed<T: DeserializeOwned>(
6185        &self,
6186        options: WorkflowResultOptions,
6187    ) -> Result<T> {
6188        let result = self.result_selected_run_avro_value(options).await?;
6189        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6190    }
6191
6192    async fn result_avro_value_target(
6193        &self,
6194        options: WorkflowResultOptions,
6195        selected_run_id: Option<&str>,
6196    ) -> Result<AvroValue> {
6197        let started = Instant::now();
6198
6199        loop {
6200            let description = match selected_run_id {
6201                Some(run_id) => {
6202                    self.client
6203                        .describe_workflow_run(&self.workflow_id, run_id)
6204                        .await?
6205                }
6206                None => self.describe().await?,
6207            };
6208            if description.is_completed() {
6209                return description.output_avro_value.ok_or_else(|| {
6210                    Error::Codec(
6211                        "missing_payload_envelope: typed workflow result requires output_envelope"
6212                            .to_string(),
6213                    )
6214                });
6215            }
6216            if description.is_terminal() {
6217                let outcome =
6218                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6219                return Err(match outcome.kind {
6220                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6221                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6222                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6223                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6224                });
6225            }
6226            if started.elapsed() >= options.timeout {
6227                return Err(Error::Timeout);
6228            }
6229            tokio::time::sleep(options.poll_interval).await;
6230        }
6231    }
6232
6233    async fn result_target(
6234        &self,
6235        options: WorkflowResultOptions,
6236        selected_run_id: Option<&str>,
6237    ) -> Result<Value> {
6238        let started = Instant::now();
6239
6240        loop {
6241            let description = match selected_run_id {
6242                Some(run_id) => {
6243                    self.client
6244                        .describe_workflow_run(&self.workflow_id, run_id)
6245                        .await?
6246                }
6247                None => self.describe().await?,
6248            };
6249            if description.is_completed() {
6250                return Ok(description.output.unwrap_or(Value::Null));
6251            }
6252
6253            if description.is_terminal() {
6254                let outcome =
6255                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6256                return Err(match outcome.kind {
6257                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6258                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6259                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6260                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6261                });
6262            }
6263
6264            if started.elapsed() >= options.timeout {
6265                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
6266                    kind: WorkflowTerminalKind::TimedOut,
6267                    workflow_id: description
6268                        .workflow_id
6269                        .clone()
6270                        .unwrap_or_else(|| self.workflow_id.clone()),
6271                    run_id: description
6272                        .run_id
6273                        .clone()
6274                        .or_else(|| selected_run_id.map(str::to_string)),
6275                    reason: "result_wait_timeout".to_string(),
6276                    failure_category: Some("client_timeout".to_string()),
6277                    failure_id: None,
6278                    exception_type: None,
6279                    exception_class: None,
6280                    non_retryable: None,
6281                    message: Some(format!(
6282                        "workflow result was not terminal within {:?}",
6283                        options.timeout
6284                    )),
6285                    exception: None,
6286                    raw: description.raw_value(),
6287                }));
6288            }
6289
6290            tokio::time::sleep(options.poll_interval).await;
6291        }
6292    }
6293}
6294
6295#[derive(Clone, Copy, Debug)]
6296pub struct WorkflowResultOptions {
6297    pub poll_interval: Duration,
6298    pub timeout: Duration,
6299}
6300
6301impl Default for WorkflowResultOptions {
6302    fn default() -> Self {
6303        Self {
6304            poll_interval: Duration::from_millis(500),
6305            timeout: Duration::from_secs(30),
6306        }
6307    }
6308}
6309
6310#[derive(Clone, Debug, Deserialize)]
6311pub struct WorkflowDescription {
6312    pub workflow_id: Option<String>,
6313    pub run_id: Option<String>,
6314    pub workflow_type: Option<String>,
6315    pub status: Option<String>,
6316    #[serde(default)]
6317    pub closed_reason: Option<String>,
6318    #[serde(default)]
6319    pub error: Option<String>,
6320    #[serde(default)]
6321    pub failure: Option<Value>,
6322    #[serde(default)]
6323    pub exception: Option<Value>,
6324    #[serde(default)]
6325    pub failures: Vec<Value>,
6326    #[serde(default)]
6327    pub output: Option<Value>,
6328    #[serde(default)]
6329    pub output_envelope: Option<Value>,
6330    #[serde(skip)]
6331    pub output_avro_value: Option<AvroValue>,
6332    #[serde(flatten)]
6333    pub raw: HashMap<String, Value>,
6334}
6335
6336/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
6337#[derive(Clone, Debug, Deserialize)]
6338pub struct WorkflowStreamDescription {
6339    pub stream_name: String,
6340    pub status: String,
6341    pub last_offset: i64,
6342    pub total_items: u64,
6343    pub pending_items: u64,
6344    #[serde(default)]
6345    pub opened_at: Option<String>,
6346    #[serde(default)]
6347    pub last_appended_at: Option<String>,
6348    #[serde(default)]
6349    pub closed_at: Option<String>,
6350    #[serde(default)]
6351    pub error_reason: Option<String>,
6352    #[serde(default)]
6353    pub retention_seconds: Option<u64>,
6354    #[serde(flatten)]
6355    pub raw: HashMap<String, Value>,
6356}
6357
6358impl WorkflowStreamDescription {
6359    pub fn is_terminal(&self) -> bool {
6360        matches!(self.status.as_str(), "closed" | "errored")
6361    }
6362}
6363
6364/// One item for direct or replay-safe append.
6365#[derive(Clone, Debug, Default)]
6366pub struct WorkflowStreamAppendItem {
6367    pub payload_envelope: Option<Value>,
6368    pub payload_reference: Option<String>,
6369    pub item_type: Option<String>,
6370    pub content_type: Option<String>,
6371    pub idempotency_key: Option<String>,
6372}
6373
6374impl WorkflowStreamAppendItem {
6375    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
6376    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
6377        let value = AvroValue::from_serialize(&payload)?;
6378        Ok(Self {
6379            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
6380            ..Self::default()
6381        })
6382    }
6383
6384    /// Preserve an external payload URI as an opaque service-contract reference.
6385    pub fn from_reference(reference: impl Into<String>) -> Self {
6386        Self {
6387            payload_reference: Some(reference.into()),
6388            ..Self::default()
6389        }
6390    }
6391
6392    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
6393        self.item_type = Some(item_type.into());
6394        self
6395    }
6396
6397    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
6398        self.content_type = Some(content_type.into());
6399        self
6400    }
6401
6402    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
6403        self.idempotency_key = Some(idempotency_key.into());
6404        self
6405    }
6406
6407    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
6408        let mut item = serde_json::Map::new();
6409        if let Some(payload) = &self.payload_envelope {
6410            item.insert("payload".to_string(), payload.clone());
6411            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
6412        }
6413        if let Some(reference) = &self.payload_reference {
6414            item.insert("payload_reference".to_string(), json!(reference));
6415        }
6416        if let Some(item_type) = &self.item_type {
6417            item.insert("item_type".to_string(), json!(item_type));
6418        }
6419        if let Some(content_type) = &self.content_type {
6420            item.insert("content_type".to_string(), json!(content_type));
6421        }
6422        if let Some(key) = derived_idempotency_key
6423            .as_ref()
6424            .or(self.idempotency_key.as_ref())
6425        {
6426            item.insert("idempotency_key".to_string(), json!(key));
6427        }
6428        Value::Object(item)
6429    }
6430}
6431
6432/// One durable item at its stable zero-based offset.
6433#[derive(Clone, Debug)]
6434pub struct WorkflowStreamItem {
6435    pub offset: u64,
6436    pub payload: Option<Value>,
6437    pub payload_envelope: Option<Value>,
6438    pub payload_reference: Option<String>,
6439    pub payload_codec: Option<String>,
6440    pub idempotency_key: Option<String>,
6441    pub item_type: Option<String>,
6442    pub content_type: Option<String>,
6443    pub origin: Option<String>,
6444    pub origin_reference: Option<String>,
6445    pub emitted_at: Option<String>,
6446    pub raw: Value,
6447}
6448
6449/// One bounded at-least-once subscription page.
6450#[derive(Clone, Debug)]
6451pub struct WorkflowStreamPage {
6452    pub stream: WorkflowStreamDescription,
6453    pub items: Vec<WorkflowStreamItem>,
6454    pub next_offset: u64,
6455    pub terminal: bool,
6456}
6457
6458/// Durable acceptance and deduplication outcome for an append request.
6459#[derive(Clone, Debug)]
6460pub struct WorkflowStreamAppendResult {
6461    pub stream: WorkflowStreamDescription,
6462    pub accepted_offsets: Vec<u64>,
6463    pub accepted: u64,
6464    pub deduped: u64,
6465}
6466
6467#[derive(Deserialize)]
6468struct WorkflowStreamListResponse {
6469    #[serde(default)]
6470    streams: Vec<WorkflowStreamDescription>,
6471}
6472
6473#[derive(Deserialize)]
6474struct WorkflowStreamDescriptionResponse {
6475    stream: WorkflowStreamDescription,
6476}
6477
6478#[derive(Deserialize)]
6479struct WorkflowStreamPageResponse {
6480    stream: WorkflowStreamDescription,
6481    #[serde(default)]
6482    items: Vec<Value>,
6483    next_offset: u64,
6484    terminal: bool,
6485}
6486
6487#[derive(Deserialize)]
6488struct WorkflowStreamAppendResponse {
6489    stream: WorkflowStreamDescription,
6490    #[serde(default)]
6491    accepted_offsets: Vec<u64>,
6492    accepted: u64,
6493    deduped: u64,
6494}
6495
6496impl WorkflowDescription {
6497    pub fn is_completed(&self) -> bool {
6498        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6499    }
6500
6501    pub fn is_terminal(&self) -> bool {
6502        matches!(
6503            self.status.as_deref(),
6504            Some(
6505                "completed"
6506                    | "Completed"
6507                    | "failed"
6508                    | "Failed"
6509                    | "cancelled"
6510                    | "Cancelled"
6511                    | "terminated"
6512                    | "Terminated"
6513                    | "timed_out"
6514                    | "TimedOut",
6515            )
6516        )
6517    }
6518
6519    fn decode_payloads(&mut self) -> Result<()> {
6520        if let Some(envelope) = &self.output_envelope {
6521            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6522            self.output = Some(value.clone().into_json()?);
6523            self.output_avro_value = Some(value);
6524        }
6525
6526        Ok(())
6527    }
6528
6529    fn raw_value(&self) -> Value {
6530        let mut data = self.raw.clone();
6531        data.insert(
6532            "workflow_id".to_string(),
6533            self.workflow_id
6534                .clone()
6535                .map(Value::String)
6536                .unwrap_or(Value::Null),
6537        );
6538        data.insert(
6539            "run_id".to_string(),
6540            self.run_id
6541                .clone()
6542                .map(Value::String)
6543                .unwrap_or(Value::Null),
6544        );
6545        data.insert(
6546            "workflow_type".to_string(),
6547            self.workflow_type
6548                .clone()
6549                .map(Value::String)
6550                .unwrap_or(Value::Null),
6551        );
6552        data.insert(
6553            "status".to_string(),
6554            self.status
6555                .clone()
6556                .map(Value::String)
6557                .unwrap_or(Value::Null),
6558        );
6559        data.insert(
6560            "closed_reason".to_string(),
6561            self.closed_reason
6562                .clone()
6563                .map(Value::String)
6564                .unwrap_or(Value::Null),
6565        );
6566        if let Some(failure) = &self.failure {
6567            data.insert("failure".to_string(), failure.clone());
6568        }
6569        if let Some(exception) = &self.exception {
6570            data.insert("exception".to_string(), exception.clone());
6571        }
6572        Value::Object(data.into_iter().collect())
6573    }
6574}
6575
6576fn workflow_terminal_outcome(
6577    description: &WorkflowDescription,
6578    workflow_id: &str,
6579    run_id: Option<&str>,
6580) -> WorkflowTerminalOutcome {
6581    let terminal_kind = description
6582        .closed_reason
6583        .as_deref()
6584        .or(description.status.as_deref())
6585        .unwrap_or("failed")
6586        .to_ascii_lowercase();
6587    let kind = match terminal_kind.as_str() {
6588        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6589        "terminated" => WorkflowTerminalKind::Terminated,
6590        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6591        _ => WorkflowTerminalKind::Failed,
6592    };
6593    let default_reason = match kind {
6594        WorkflowTerminalKind::Failed => "workflow_failed",
6595        WorkflowTerminalKind::Cancelled => "cancelled",
6596        WorkflowTerminalKind::Terminated => "terminated",
6597        WorkflowTerminalKind::TimedOut => "timed_out",
6598    };
6599    let failure = description
6600        .failure
6601        .as_ref()
6602        .filter(|value| value.is_object());
6603    let nested_failure = failure
6604        .and_then(|value| value.get("failures"))
6605        .and_then(Value::as_array)
6606        .and_then(|failures| failures.last())
6607        .or_else(|| description.failures.last());
6608    let exception = description
6609        .exception
6610        .clone()
6611        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6612        .or_else(|| {
6613            nested_failure
6614                .and_then(|value| value.get("exception_payload"))
6615                .cloned()
6616        });
6617    let string_field = |name: &str| {
6618        failure
6619            .and_then(|value| value.get(name))
6620            .and_then(Value::as_str)
6621            .or_else(|| {
6622                nested_failure
6623                    .and_then(|value| value.get(name))
6624                    .and_then(Value::as_str)
6625            })
6626            .map(str::to_string)
6627    };
6628    let exception_field = |name: &str| {
6629        exception
6630            .as_ref()
6631            .and_then(|value| value.get(name))
6632            .and_then(Value::as_str)
6633            .map(str::to_string)
6634    };
6635    let message = description
6636        .error
6637        .clone()
6638        .or_else(|| string_field("message"))
6639        .or_else(|| exception_field("message"));
6640    let reason = description
6641        .raw
6642        .get("reason")
6643        .and_then(Value::as_str)
6644        .map(str::to_string)
6645        .or_else(|| {
6646            failure
6647                .and_then(|value| value.get("reason"))
6648                .and_then(Value::as_str)
6649                .map(str::to_string)
6650        })
6651        .or_else(|| description.closed_reason.clone())
6652        .unwrap_or_else(|| default_reason.to_string());
6653    let failure_id = string_field("failure_id").or_else(|| {
6654        nested_failure
6655            .and_then(|value| value.get("id"))
6656            .and_then(Value::as_str)
6657            .map(str::to_string)
6658    });
6659
6660    WorkflowTerminalOutcome {
6661        kind,
6662        workflow_id: description
6663            .workflow_id
6664            .clone()
6665            .unwrap_or_else(|| workflow_id.to_string()),
6666        run_id: description
6667            .run_id
6668            .clone()
6669            .or_else(|| run_id.map(str::to_string)),
6670        reason,
6671        failure_category: string_field("failure_category")
6672            .or_else(|| Some(default_reason.to_string())),
6673        failure_id,
6674        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6675        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6676        non_retryable: failure
6677            .and_then(|value| value.get("non_retryable"))
6678            .and_then(Value::as_bool)
6679            .or_else(|| {
6680                nested_failure
6681                    .and_then(|value| value.get("non_retryable"))
6682                    .and_then(Value::as_bool)
6683            }),
6684        message,
6685        exception,
6686        raw: description.raw_value(),
6687    }
6688}
6689
6690#[derive(Clone, Debug, Deserialize)]
6691pub struct RegisterWorkerResponse {
6692    pub worker_id: String,
6693    pub registered: bool,
6694    #[serde(default)]
6695    pub heartbeat_interval_seconds: Option<u64>,
6696    #[serde(default)]
6697    pub protocol_version: Option<String>,
6698    #[serde(default)]
6699    pub server_capabilities: Option<Value>,
6700}
6701
6702/// Result of gracefully removing a worker-plane registration.
6703#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6704pub struct WorkerDeregistrationEnvelope {
6705    pub worker_id: String,
6706    pub outcome: String,
6707    pub recovered_workflow_task_count: u64,
6708}
6709
6710#[derive(Clone, Debug, Deserialize)]
6711pub struct PollWorkflowTaskResponse {
6712    #[serde(default)]
6713    pub task: Option<WorkflowTask>,
6714    #[serde(default)]
6715    pub poll_status: Option<String>,
6716    #[serde(default)]
6717    pub reason: Option<String>,
6718    #[serde(default)]
6719    pub protocol_version: Option<String>,
6720    #[serde(default)]
6721    pub server_capabilities: Option<Value>,
6722}
6723
6724impl PollWorkflowTaskResponse {
6725    /// Classify this response without parsing server display text.
6726    pub fn outcome(&self) -> WorkerPollOutcome {
6727        worker_poll_outcome(
6728            self.task.is_some(),
6729            self.poll_status.as_deref(),
6730            self.reason.as_deref(),
6731        )
6732    }
6733}
6734
6735fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6736    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6737        return false;
6738    };
6739    let supported = capabilities
6740        .get("workflow_memo_updates")
6741        .and_then(Value::as_object)
6742        .and_then(|memo| memo.get("supported"))
6743        .and_then(Value::as_bool)
6744        == Some(true);
6745    let command_advertised = capabilities
6746        .get("supported_workflow_task_commands")
6747        .and_then(Value::as_array)
6748        .is_some_and(|commands| {
6749            commands
6750                .iter()
6751                .any(|command| command.as_str() == Some("upsert_memo"))
6752        });
6753    supported && command_advertised
6754}
6755
6756fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6757    commands
6758        .iter()
6759        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6760}
6761
6762#[derive(Clone, Debug, Deserialize)]
6763pub struct PollActivityTaskResponse {
6764    #[serde(default)]
6765    pub task: Option<ActivityTask>,
6766    #[serde(default)]
6767    pub poll_status: Option<String>,
6768    #[serde(default)]
6769    pub reason: Option<String>,
6770}
6771
6772impl PollActivityTaskResponse {
6773    /// Classify this response without parsing server display text.
6774    pub fn outcome(&self) -> WorkerPollOutcome {
6775        worker_poll_outcome(
6776            self.task.is_some(),
6777            self.poll_status.as_deref(),
6778            self.reason.as_deref(),
6779        )
6780    }
6781}
6782
6783#[derive(Clone, Debug, Deserialize)]
6784pub struct PollQueryTaskResponse {
6785    #[serde(default)]
6786    pub task: Option<QueryTask>,
6787    #[serde(default)]
6788    pub poll_status: Option<String>,
6789    #[serde(default)]
6790    pub reason: Option<String>,
6791}
6792
6793impl PollQueryTaskResponse {
6794    /// Classify this response without parsing server display text.
6795    pub fn outcome(&self) -> WorkerPollOutcome {
6796        worker_poll_outcome(
6797            self.task.is_some(),
6798            self.poll_status.as_deref(),
6799            self.reason.as_deref(),
6800        )
6801    }
6802}
6803
6804/// Stable classification for worker poll responses.
6805#[derive(Clone, Debug, PartialEq, Eq)]
6806pub enum WorkerPollOutcome {
6807    /// A task was leased and is available on the response.
6808    Task,
6809    /// No task was leased, but the worker should continue polling.
6810    Idle {
6811        poll_status: Option<String>,
6812        reason: Option<String>,
6813    },
6814    /// The server asked this worker to stop claiming new work.
6815    Stop {
6816        poll_status: Option<String>,
6817        reason: Option<String>,
6818    },
6819}
6820
6821impl WorkerPollOutcome {
6822    pub fn should_stop(&self) -> bool {
6823        matches!(self, Self::Stop { .. })
6824    }
6825}
6826
6827fn worker_poll_outcome(
6828    has_task: bool,
6829    poll_status: Option<&str>,
6830    reason: Option<&str>,
6831) -> WorkerPollOutcome {
6832    if worker_poll_is_stop(poll_status, reason) {
6833        return WorkerPollOutcome::Stop {
6834            poll_status: poll_status.map(str::to_string),
6835            reason: reason.map(str::to_string),
6836        };
6837    }
6838
6839    if has_task {
6840        WorkerPollOutcome::Task
6841    } else {
6842        WorkerPollOutcome::Idle {
6843            poll_status: poll_status.map(str::to_string),
6844            reason: reason.map(str::to_string),
6845        }
6846    }
6847}
6848
6849/// An ephemeral server-routed query task.
6850#[derive(Clone, Debug, Deserialize)]
6851pub struct QueryTask {
6852    pub query_task_id: String,
6853    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6854    #[serde(default)]
6855    pub observability_context: Option<Value>,
6856    #[serde(default)]
6857    pub dispatch_observability_context: Option<Value>,
6858    #[serde(default)]
6859    pub observability_links: Option<Value>,
6860    #[serde(default = "default_workflow_task_attempt")]
6861    pub query_task_attempt: u64,
6862    #[serde(default)]
6863    pub lease_owner: Option<String>,
6864    #[serde(default)]
6865    pub workflow_id: Option<String>,
6866    #[serde(default)]
6867    pub run_id: Option<String>,
6868    pub workflow_type: String,
6869    pub query_name: String,
6870    #[serde(
6871        default = "missing_task_payload_codec",
6872        deserialize_with = "deserialize_task_payload_codec"
6873    )]
6874    pub payload_codec: String,
6875    #[serde(default)]
6876    pub workflow_arguments: Option<Value>,
6877    #[serde(default)]
6878    pub query_arguments: Option<Value>,
6879    #[serde(default)]
6880    pub history_events: Vec<HistoryEvent>,
6881    #[serde(default)]
6882    pub history_export: Option<Value>,
6883    #[serde(default)]
6884    pub run_status: Option<String>,
6885}
6886
6887#[derive(Clone, Debug, Deserialize)]
6888pub struct WorkflowTask {
6889    pub task_id: String,
6890    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6891    #[serde(default)]
6892    pub observability_context: Option<Value>,
6893    #[serde(default)]
6894    pub dispatch_observability_context: Option<Value>,
6895    #[serde(default)]
6896    pub observability_links: Option<Value>,
6897    #[serde(default)]
6898    pub workflow_command_id: Option<String>,
6899    #[serde(default)]
6900    pub workflow_id: Option<String>,
6901    #[serde(default)]
6902    pub run_id: Option<String>,
6903    pub workflow_type: String,
6904    #[serde(default)]
6905    pub cancel_requested: bool,
6906    #[serde(
6907        default = "missing_task_payload_codec",
6908        deserialize_with = "deserialize_task_payload_codec"
6909    )]
6910    pub payload_codec: String,
6911    #[serde(default)]
6912    pub arguments: Option<Value>,
6913    #[serde(default)]
6914    pub history_events: Vec<HistoryEvent>,
6915    #[serde(default)]
6916    pub total_history_events: Option<u64>,
6917    #[serde(default)]
6918    pub history_size_bytes: Option<u64>,
6919    #[serde(default)]
6920    pub continue_as_new_recommended: Option<bool>,
6921    #[serde(default)]
6922    pub history_budget_pressure: Option<String>,
6923    #[serde(default)]
6924    pub next_history_page_token: Option<String>,
6925    #[serde(default = "default_workflow_task_attempt")]
6926    pub workflow_task_attempt: u64,
6927    #[serde(default)]
6928    pub workflow_signal_id: Option<String>,
6929    #[serde(default)]
6930    pub signal_name: Option<String>,
6931    #[serde(default)]
6932    pub signal_arguments: Option<Value>,
6933    #[serde(default)]
6934    pub workflow_update_id: Option<String>,
6935    #[serde(default)]
6936    pub update_name: Option<String>,
6937    #[serde(default)]
6938    pub lease_owner: Option<String>,
6939}
6940
6941impl WorkflowTask {
6942    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6943        self.history_events.extend(page.history_events);
6944
6945        if page.total_history_events.is_some() {
6946            self.total_history_events = page.total_history_events;
6947        }
6948
6949        self.next_history_page_token = page
6950            .next_history_page_token
6951            .filter(|token| !token.is_empty());
6952    }
6953}
6954
6955#[derive(Clone, Debug, Deserialize)]
6956struct WorkflowTaskHistoryPage {
6957    #[serde(default)]
6958    history_events: Vec<HistoryEvent>,
6959    #[serde(default)]
6960    total_history_events: Option<u64>,
6961    #[serde(default)]
6962    next_history_page_token: Option<String>,
6963}
6964
6965#[derive(Clone, Debug, Deserialize)]
6966pub struct ActivityTask {
6967    pub task_id: String,
6968    #[serde(default)]
6969    pub workflow_id: Option<String>,
6970    #[serde(default)]
6971    pub run_id: Option<String>,
6972    #[serde(default)]
6973    pub activity_execution_id: Option<String>,
6974    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6975    #[serde(default)]
6976    pub observability_context: Option<Value>,
6977    #[serde(default)]
6978    pub dispatch_observability_context: Option<Value>,
6979    #[serde(default)]
6980    pub observability_links: Option<Value>,
6981    #[serde(default)]
6982    pub activity_attempt_id: Option<String>,
6983    #[serde(default)]
6984    pub attempt_id: Option<String>,
6985    pub activity_type: String,
6986    #[serde(
6987        default = "missing_task_payload_codec",
6988        deserialize_with = "deserialize_task_payload_codec"
6989    )]
6990    pub payload_codec: String,
6991    #[serde(default)]
6992    pub arguments: Option<Value>,
6993    #[serde(default = "default_attempt_number")]
6994    pub attempt_number: u64,
6995    #[serde(default)]
6996    pub lease_owner: Option<String>,
6997}
6998
6999#[derive(Clone, Debug, Serialize, Deserialize)]
7000pub struct HistoryEvent {
7001    #[serde(alias = "type")]
7002    pub event_type: String,
7003    #[serde(default)]
7004    pub payload: Value,
7005    #[serde(flatten)]
7006    pub raw: HashMap<String, Value>,
7007}
7008
7009/// One decoded signal in the committed workflow-history snapshot.
7010#[derive(Clone, Debug, PartialEq)]
7011pub struct QuerySignal {
7012    pub id: Option<String>,
7013    pub name: String,
7014    pub arguments: Vec<Value>,
7015    avro_arguments: Vec<AvroValue>,
7016    pub workflow_sequence: Option<u64>,
7017}
7018
7019impl QuerySignal {
7020    /// Lossless fixed Avro Value arguments for this committed signal.
7021    pub fn arguments_avro_value(&self) -> &[AvroValue] {
7022        &self.avro_arguments
7023    }
7024}
7025
7026/// Immutable state supplied to a registered query handler.
7027///
7028/// This context intentionally exposes no activity, signal-wait, or command
7029/// APIs. Query handlers inspect committed history and return a value; query
7030/// completion does not append an event or advance deterministic execution.
7031#[derive(Clone, Debug)]
7032pub struct QueryContext {
7033    pub workflow_id: Option<String>,
7034    pub run_id: Option<String>,
7035    pub workflow_type: String,
7036    pub run_status: Option<String>,
7037    workflow_input: Value,
7038    workflow_input_avro_value: AvroValue,
7039    history_events: Arc<Vec<HistoryEvent>>,
7040    signal_events: Arc<Vec<QuerySignal>>,
7041}
7042
7043impl QueryContext {
7044    /// The normalized argument list used to start the workflow.
7045    pub fn workflow_input(&self) -> &Value {
7046        &self.workflow_input
7047    }
7048
7049    /// The lossless fixed Avro Value argument list used to start the workflow.
7050    pub fn workflow_input_avro_value(&self) -> &AvroValue {
7051        &self.workflow_input_avro_value
7052    }
7053
7054    /// The immutable committed history used for this query snapshot.
7055    pub fn history_events(&self) -> &[HistoryEvent] {
7056        self.history_events.as_slice()
7057    }
7058
7059    /// All decoded signals in committed workflow order.
7060    pub fn signal_events(&self) -> &[QuerySignal] {
7061        self.signal_events.as_slice()
7062    }
7063
7064    /// Decoded argument lists for each committed signal with `signal_name`.
7065    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
7066        self.signal_events
7067            .iter()
7068            .filter(|signal| signal.name == signal_name)
7069            .map(|signal| signal.arguments.clone())
7070            .collect()
7071    }
7072
7073    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
7074    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
7075        self.signal_events
7076            .iter()
7077            .filter(|signal| signal.name == signal_name)
7078            .map(|signal| signal.avro_arguments.clone())
7079            .collect()
7080    }
7081}
7082
7083#[derive(Clone, Debug, Deserialize)]
7084pub struct ActivityHeartbeatResponse {
7085    #[serde(default)]
7086    pub cancel_requested: bool,
7087    #[serde(default)]
7088    pub heartbeat_recorded: bool,
7089    #[serde(default)]
7090    pub can_continue: Option<bool>,
7091    #[serde(default)]
7092    pub reason: Option<String>,
7093    #[serde(default)]
7094    pub run_closed_reason: Option<String>,
7095    #[serde(default)]
7096    pub run_closed_at: Option<String>,
7097    #[serde(default)]
7098    pub lease_expires_at: Option<String>,
7099    #[serde(default)]
7100    pub last_heartbeat_at: Option<String>,
7101}
7102
7103impl ActivityHeartbeatResponse {
7104    /// Whether the activity should stop instead of attempting completion.
7105    pub fn should_stop(&self) -> bool {
7106        self.cancel_requested || self.can_continue == Some(false)
7107    }
7108}
7109
7110fn missing_task_payload_codec() -> String {
7111    MISSING_TASK_PAYLOAD_CODEC.to_string()
7112}
7113
7114fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
7115where
7116    D: Deserializer<'de>,
7117{
7118    Ok(match Value::deserialize(deserializer)? {
7119        Value::String(codec) => codec,
7120        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
7121        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
7122    })
7123}
7124
7125fn default_workflow_task_attempt() -> u64 {
7126    1
7127}
7128
7129fn default_attempt_number() -> u64 {
7130    1
7131}
7132
7133type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7134type WorkflowHandler =
7135    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
7136type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
7137type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
7138type ReplayedWorkflowHandler =
7139    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
7140type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7141type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
7142type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7143type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7144type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7145type ReplayedQueryHandler = Arc<
7146    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
7147        + Send
7148        + Sync,
7149>;
7150type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
7151
7152struct ReplayedWorkflowInvocation {
7153    future: WorkflowFuture,
7154    snapshot: WorkflowStateSnapshot,
7155}
7156
7157#[derive(Clone)]
7158struct RegisteredWorkflow {
7159    execute: WorkflowHandler,
7160    replay: Option<ReplayedWorkflowHandler>,
7161    state_type: Option<TypeId>,
7162    definition_fingerprint: Option<String>,
7163}
7164
7165fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
7166    names
7167        .iter()
7168        .map(|name| {
7169            json!({
7170                "name": name,
7171                "parameters": [{
7172                    "name": "args",
7173                    "position": 0,
7174                    "required": false,
7175                    "variadic": true,
7176                    "type": null,
7177                    "allows_null": true,
7178                    "default_available": false,
7179                    "default": null,
7180                }],
7181            })
7182        })
7183        .collect()
7184}
7185
7186#[derive(Debug)]
7187struct WorkflowTaskDecision {
7188    commands: Vec<Value>,
7189    message_stream_cursors: Vec<Value>,
7190    message_stream_waits: Vec<Value>,
7191    cancellation_delivery: Option<CancellationDelivery>,
7192    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
7193    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
7194}
7195
7196enum PreparedWorkflowTask {
7197    Decision(WorkflowTaskDecision),
7198    Execution {
7199        task: WorkflowTask,
7200        context: WorkflowContext,
7201        future: WorkflowFuture,
7202    },
7203}
7204
7205impl WorkflowTaskDecision {
7206    fn without_message_streams(commands: Vec<Value>) -> Self {
7207        Self {
7208            commands,
7209            message_stream_cursors: Vec::new(),
7210            message_stream_waits: Vec::new(),
7211            cancellation_delivery: None,
7212            cancellation_scope_opening: None,
7213            cancellation_scope_delivery: None,
7214        }
7215    }
7216}
7217
7218#[derive(Clone)]
7219enum RegisteredQuery {
7220    Snapshot(QueryHandler),
7221    Replayed {
7222        state_type: TypeId,
7223        handler: ReplayedQueryHandler,
7224    },
7225}
7226
7227#[derive(Clone, Debug)]
7228pub struct WorkerHeartbeatObservation {
7229    pub worker_id: String,
7230    pub task_queue: String,
7231    pub acknowledged_at_unix_millis: u64,
7232    pub acknowledgement: Value,
7233}
7234
7235/// Bounded retry policy for worker poll acquisition and worker heartbeats.
7236///
7237/// Expected empty long polls and explicit Server capacity backpressure are
7238/// normal worker states. Capacity backpressure honors the advertised retry
7239/// delay without consuming this retry budget. Other transport failures,
7240/// retryable HTTP 408/429 responses, and server errors are retried with capped
7241/// exponential backoff. Authentication, protocol, codec, and handler failures
7242/// are never retried by the worker.
7243/// Explicit storage admission pauses also preserve the already-serialized worker
7244/// request without consuming this budget or rerunning its handler. The delay is
7245/// capped by `max_backoff`, except an explicit completion deferral must honor
7246/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
7247/// completion retries remain bounded by the original cleanup deadline.
7248/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
7249/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
7250/// and `max_retries = 0` disables ordinary retries in either mode.
7251#[derive(Clone, Copy, Debug)]
7252pub struct WorkerRetryPolicy {
7253    /// Number of retries after the initial request fails.
7254    pub max_retries: usize,
7255    /// Delay before the first retry.
7256    pub initial_backoff: Duration,
7257    /// Maximum delay between retries.
7258    pub max_backoff: Duration,
7259}
7260
7261impl Default for WorkerRetryPolicy {
7262    fn default() -> Self {
7263        Self {
7264            max_retries: 5,
7265            initial_backoff: Duration::from_millis(100),
7266            max_backoff: Duration::from_secs(5),
7267        }
7268    }
7269}
7270
7271#[derive(Clone, Debug)]
7272struct WorkerStorageAdmission {
7273    policy: WorkerRetryPolicy,
7274    stop: Arc<AtomicBool>,
7275    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
7276}
7277
7278struct StopWorkerOnDrop(Arc<AtomicBool>);
7279
7280impl Drop for StopWorkerOnDrop {
7281    fn drop(&mut self) {
7282        self.0.store(true, Ordering::SeqCst);
7283    }
7284}
7285
7286async fn wait_for_worker_stop(stop: &AtomicBool) {
7287    while !stop.load(Ordering::SeqCst) {
7288        tokio::time::sleep(Duration::from_millis(100)).await;
7289    }
7290}
7291
7292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7293enum ManagedPollOutcome {
7294    Idle,
7295    Handled,
7296    Stop,
7297}
7298
7299#[derive(Clone)]
7300pub struct Worker {
7301    #[cfg(feature = "telemetry")]
7302    telemetry: Option<telemetry::ExecutionTelemetry>,
7303    client: Client,
7304    worker_id: String,
7305    task_queue: String,
7306    workflows: HashMap<String, RegisteredWorkflow>,
7307    activities: HashMap<String, ActivityHandler>,
7308    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
7309    signals: HashMap<String, Vec<String>>,
7310    updates: HashMap<String, HashMap<String, UpdateHandler>>,
7311    registration_definitions:
7312        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
7313    registration_error: Option<DuplicateRegistrationError>,
7314    max_concurrent_workflow_tasks: usize,
7315    max_concurrent_activity_tasks: usize,
7316    workflow_capacity: Arc<worker_capacity::TaskCapacity>,
7317    activity_capacity: Arc<worker_capacity::TaskCapacity>,
7318    poll_timeout: Duration,
7319    heartbeat_interval: Duration,
7320    retry_policy: WorkerRetryPolicy,
7321    recover_transient_outages: bool,
7322    run_stop: Option<Arc<AtomicBool>>,
7323    heartbeat_observer: Option<WorkerHeartbeatObserver>,
7324    cooperative_cancellation_enabled: bool,
7325    nexus_cooperative_cancellation_enabled: bool,
7326    allow_cancellation_scope_authoring: bool,
7327    allow_cancellation_scope_delivery: bool,
7328    cooperative_registration_confirmed: Arc<AtomicBool>,
7329    nexus_registration_confirmed: Arc<AtomicBool>,
7330    local_registration_confirmed: Arc<AtomicBool>,
7331    session_registration_confirmed: Arc<AtomicBool>,
7332    sticky_registration_confirmed: Arc<AtomicBool>,
7333    require_query_task_authority: bool,
7334    query_authority_confirmed: Arc<AtomicBool>,
7335    resource_capabilities: Vec<String>,
7336    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
7337}
7338
7339impl Worker {
7340    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
7341        Self {
7342            #[cfg(feature = "telemetry")]
7343            telemetry: None,
7344            client,
7345            worker_id: default_worker_id(),
7346            task_queue: task_queue.into(),
7347            workflows: HashMap::new(),
7348            activities: HashMap::new(),
7349            queries: HashMap::new(),
7350            signals: HashMap::new(),
7351            updates: HashMap::new(),
7352            registration_definitions: HashMap::new(),
7353            registration_error: None,
7354            max_concurrent_workflow_tasks: 10,
7355            max_concurrent_activity_tasks: 10,
7356            workflow_capacity: worker_capacity::TaskCapacity::new(10),
7357            activity_capacity: worker_capacity::TaskCapacity::new(10),
7358            poll_timeout: Duration::from_secs(30),
7359            heartbeat_interval: Duration::from_secs(60),
7360            retry_policy: WorkerRetryPolicy::default(),
7361            recover_transient_outages: false,
7362            run_stop: None,
7363            heartbeat_observer: None,
7364            cooperative_cancellation_enabled: false,
7365            nexus_cooperative_cancellation_enabled: false,
7366            allow_cancellation_scope_authoring: false,
7367            allow_cancellation_scope_delivery: false,
7368            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
7369            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
7370            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
7371            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
7372            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
7373            require_query_task_authority: false,
7374            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
7375            resource_capabilities: Vec::new(),
7376            sessions: Arc::new(Mutex::new(HashMap::new())),
7377        }
7378    }
7379
7380    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
7381        self.worker_id = worker_id.into();
7382        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7383        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7384        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7385        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
7386        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
7387        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
7388        self.client.reset_sticky_cache();
7389        self.sessions = Arc::new(Mutex::new(HashMap::new()));
7390        self
7391    }
7392
7393    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
7394        self.poll_timeout = timeout;
7395        self
7396    }
7397
7398    /// Opt in to execution spans using application-owned OpenTelemetry providers.
7399    /// No exporter, logging bridge, global provider or Server carrier is installed.
7400    #[cfg(feature = "telemetry")]
7401    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
7402        self.client.execution_telemetry = Some(telemetry.clone());
7403        self.telemetry = Some(telemetry);
7404        self
7405    }
7406
7407    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
7408        self.heartbeat_interval = interval;
7409        self
7410    }
7411
7412    /// Require original query timing and non-renewing runtime observation.
7413    ///
7414    /// Registration refuses before creating a Worker unless protocol 1.20 and
7415    /// the runtime's `query_task_authority` capability are available. By default,
7416    /// older Servers retain their weaker, disclosed local-timing behavior.
7417    pub fn require_query_task_authority(mut self, required: bool) -> Self {
7418        self.require_query_task_authority = required;
7419        self
7420    }
7421
7422    /// Explicitly enable inline local activities in this workflow worker.
7423    ///
7424    /// The worker advertises the capability to Server only when enabled.
7425    /// These callbacks must yield to Tokio and have idempotent side effects.
7426    /// Cooperative prepared local supervision is a separate capability.
7427    pub fn local_activities(mut self, enabled: bool) -> Self {
7428        self.client.local_activities_enabled = enabled;
7429        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7430        self
7431    }
7432
7433    /// Opt in to separate cooperative workflow cancellation requests.
7434    ///
7435    /// Registration requires the Server to acknowledge this exact worker,
7436    /// namespace, queue and capabilities with compatible protocol 1.20. Task
7437    /// processing uses canonical delivery and activity ownership fences.
7438    /// Existing terminal cancel and terminate operations remain terminal.
7439    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
7440    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
7441    /// and [`Worker::run_until`] register automatically.
7442    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
7443        self.cooperative_cancellation_enabled = enabled;
7444        self.client.cooperative_worker_protocol = enabled;
7445        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7446        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7447        if !enabled {
7448            self.nexus_cooperative_cancellation_enabled = false;
7449        }
7450        self
7451    }
7452
7453    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
7454    ///
7455    /// This also enables ordinary cooperative cancellation. Registration checks
7456    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
7457    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
7458        let mut worker = if enabled {
7459            self.cooperative_cancellation(true)
7460        } else {
7461            self
7462        };
7463        worker.nexus_cooperative_cancellation_enabled = enabled;
7464        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7465        worker
7466    }
7467
7468    /// Enable candidate scope authoring without advertising scoped execution.
7469    #[doc(hidden)]
7470    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
7471        self.allow_cancellation_scope_authoring = enabled;
7472        self
7473    }
7474
7475    /// Enable the candidate scoped call consumer with canonical authoring.
7476    #[doc(hidden)]
7477    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
7478        self.allow_cancellation_scope_delivery = enabled;
7479        self
7480    }
7481
7482    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
7483    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
7484        self.retry_policy = policy;
7485        self
7486    }
7487
7488    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7489    ///
7490    /// Retries preserve the poll request identity and use capped exponential
7491    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7492    /// An in-flight poll is allowed to finish so leased work is not discarded.
7493    /// Authentication, protocol, codec, handler and task settlement failures
7494    /// remain errors. Registration and deregistration are not retried here.
7495    ///
7496    /// The default is disabled, preserving the bounded retry contract.
7497    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7498    /// even when this option is enabled.
7499    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7500        self.recover_transient_outages = enabled;
7501        self
7502    }
7503
7504    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7505    where
7506        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7507    {
7508        self.heartbeat_observer = Some(Arc::new(observer));
7509        self
7510    }
7511
7512    /// Bound simultaneous claimed workflow tasks, including loading and settlement.
7513    /// Defaults to 10. Use 1 for serial workflow-task execution.
7514    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7515        self.max_concurrent_workflow_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7516        self.workflow_capacity =
7517            worker_capacity::TaskCapacity::new(self.max_concurrent_workflow_tasks);
7518        self
7519    }
7520
7521    /// Bound simultaneous remote activity tasks, including loading and settlement.
7522    /// Defaults to 10. Use 1 for serial activity-task execution.
7523    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7524        self.max_concurrent_activity_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7525        self.activity_capacity =
7526            worker_capacity::TaskCapacity::new(self.max_concurrent_activity_tasks);
7527        self
7528    }
7529
7530    /// Validate local handler admission without making a Server request.
7531    ///
7532    /// Registration methods retain their existing signatures. A duplicate keeps
7533    /// the original handler and makes this Worker invalid, including its clones.
7534    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7535    /// any network request. Build a new Worker to correct an invalid configuration.
7536    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7537        match &self.registration_error {
7538            Some(error) => Err(error.clone()),
7539            None => Ok(()),
7540        }
7541    }
7542
7543    #[track_caller]
7544    fn admit_registration<F>(
7545        &mut self,
7546        handler_kind: RegistrationKind,
7547        workflow_type: Option<&str>,
7548        handler_name: &str,
7549        method: &'static str,
7550    ) -> bool {
7551        let location = std::panic::Location::caller();
7552        let definition = HandlerRegistration {
7553            method,
7554            handler_type: type_name::<F>(),
7555            file: location.file(),
7556            line: location.line(),
7557            column: location.column(),
7558        };
7559        let key = (
7560            handler_kind,
7561            workflow_type.map(str::to_owned),
7562            handler_name.to_owned(),
7563        );
7564        if let Some(first_definition) = self.registration_definitions.get(&key) {
7565            if self.registration_error.is_none() {
7566                self.registration_error = Some(DuplicateRegistrationError {
7567                    handler_kind,
7568                    workflow_type: key.1.clone(),
7569                    handler_name: key.2.clone(),
7570                    first_definition: first_definition.clone(),
7571                    second_definition: definition,
7572                });
7573            }
7574            return false;
7575        }
7576        self.registration_definitions.insert(key, definition);
7577        true
7578    }
7579
7580    /// Register a workflow handler.
7581    ///
7582    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7583    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7584    /// while acquiring or decoding a worker task remain worker-operation
7585    /// failures and do not get converted into workflow outcomes.
7586    #[track_caller]
7587    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7588    where
7589        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7590        Fut: Future<Output = Result<Value>> + Send + 'static,
7591    {
7592        let workflow_type = workflow_type.into();
7593        if !self.admit_registration::<F>(
7594            RegistrationKind::Workflow,
7595            None,
7596            &workflow_type,
7597            "register_workflow",
7598        ) {
7599            return;
7600        }
7601        let handler = Arc::new(handler);
7602        self.workflows.insert(
7603            workflow_type,
7604            RegisteredWorkflow {
7605                execute: Arc::new(move |ctx, input| {
7606                    let handler = Arc::clone(&handler);
7607                    Ok(Box::pin(async move {
7608                        let result = handler(ctx, input.into_json()?).await?;
7609                        AvroValue::from_serialize(&result)
7610                    }))
7611                }),
7612                replay: None,
7613                state_type: None,
7614                definition_fingerprint: None,
7615            },
7616        );
7617    }
7618
7619    /// Register a workflow with one Serde request value and a Serde result.
7620    ///
7621    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7622    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7623    /// workflow-specific schema. A task must contain zero arguments for a unit
7624    /// request or exactly one argument for every other request type.
7625    ///
7626    /// See the runnable
7627    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7628    /// for typed workflow and activity contracts with retry and timeout policy.
7629    #[track_caller]
7630    pub fn register_typed_workflow<I, O, F, Fut>(
7631        &mut self,
7632        workflow_type: impl Into<String>,
7633        handler: F,
7634    ) where
7635        I: DeserializeOwned + Send + 'static,
7636        O: Serialize + Send + 'static,
7637        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7638        Fut: Future<Output = Result<O>> + Send + 'static,
7639    {
7640        let workflow_type = workflow_type.into();
7641        if !self.admit_registration::<F>(
7642            RegistrationKind::Workflow,
7643            None,
7644            &workflow_type,
7645            "register_typed_workflow",
7646        ) {
7647            return;
7648        }
7649        let handler_name = workflow_type.clone();
7650        let handler = Arc::new(handler);
7651        self.workflows.insert(
7652            workflow_type,
7653            RegisteredWorkflow {
7654                execute: Arc::new(move |ctx, input| {
7655                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7656                    let handler = Arc::clone(&handler);
7657                    let handler_name = handler_name.clone();
7658                    Ok(Box::pin(async move {
7659                        let result = handler(ctx, input).await?;
7660                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7661                    }))
7662                }),
7663                replay: None,
7664                state_type: None,
7665                definition_fingerprint: None,
7666            },
7667        );
7668    }
7669
7670    /// Register a workflow on the lossless fixed Avro Value surface.
7671    #[track_caller]
7672    pub fn register_workflow_avro_value<F, Fut>(
7673        &mut self,
7674        workflow_type: impl Into<String>,
7675        handler: F,
7676    ) where
7677        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7678        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7679    {
7680        let workflow_type = workflow_type.into();
7681        if !self.admit_registration::<F>(
7682            RegistrationKind::Workflow,
7683            None,
7684            &workflow_type,
7685            "register_workflow_avro_value",
7686        ) {
7687            return;
7688        }
7689        self.workflows.insert(
7690            workflow_type,
7691            RegisteredWorkflow {
7692                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7693                replay: None,
7694                state_type: None,
7695                definition_fingerprint: None,
7696            },
7697        );
7698    }
7699
7700    /// Register a workflow whose typed instance state can be reconstructed for queries.
7701    ///
7702    /// `state_factory` creates a fresh instance for every normal workflow task and
7703    /// query replay. The workflow handler is the single source of truth for state
7704    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7705    /// resolve. Query replay runs this same handler over committed history and
7706    /// discards any commands it would emit.
7707    #[track_caller]
7708    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7709        &mut self,
7710        workflow_type: impl Into<String>,
7711        state_factory: Factory,
7712        handler: F,
7713    ) where
7714        S: Clone + Send + Sync + 'static,
7715        Factory: Fn() -> S + Send + Sync + 'static,
7716        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7717        Fut: Future<Output = Result<Value>> + Send + 'static,
7718    {
7719        let workflow_type = workflow_type.into();
7720        if !self.admit_registration::<F>(
7721            RegistrationKind::Workflow,
7722            None,
7723            &workflow_type,
7724            "register_replayed_workflow",
7725        ) {
7726            return;
7727        }
7728        let state_factory = Arc::new(state_factory);
7729        let handler = Arc::new(handler);
7730
7731        let execute_factory = Arc::clone(&state_factory);
7732        let execute_handler = Arc::clone(&handler);
7733        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7734            let state = WorkflowInstance::new(execute_factory());
7735            let handler = Arc::clone(&execute_handler);
7736            Ok(Box::pin(async move {
7737                let result = handler(ctx, input.into_json()?, state).await?;
7738                AvroValue::from_serialize(&result)
7739            }) as WorkflowFuture)
7740        });
7741
7742        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7743            let state = WorkflowInstance::new(state_factory());
7744            let snapshot_state = state.clone();
7745            let snapshot: WorkflowStateSnapshot =
7746                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7747            let replay_handler = Arc::clone(&handler);
7748            let future = async move {
7749                let result = replay_handler(ctx, input.into_json()?, state).await?;
7750                AvroValue::from_serialize(&result)
7751            };
7752            Ok(ReplayedWorkflowInvocation {
7753                future: Box::pin(future),
7754                snapshot,
7755            })
7756        });
7757
7758        self.workflows.insert(
7759            workflow_type,
7760            RegisteredWorkflow {
7761                execute,
7762                replay: Some(replay),
7763                state_type: Some(TypeId::of::<S>()),
7764                definition_fingerprint: None,
7765            },
7766        );
7767    }
7768
7769    /// Register a replayable workflow with one Serde request value and result.
7770    ///
7771    /// Normal task execution and instance-state query replay both decode and
7772    /// encode through the fixed Avro Value codec. The state factory and handler
7773    /// otherwise follow [`Worker::register_replayed_workflow`].
7774    #[track_caller]
7775    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7776        &mut self,
7777        workflow_type: impl Into<String>,
7778        state_factory: Factory,
7779        handler: F,
7780    ) where
7781        I: DeserializeOwned + Send + 'static,
7782        O: Serialize + Send + 'static,
7783        S: Clone + Send + Sync + 'static,
7784        Factory: Fn() -> S + Send + Sync + 'static,
7785        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7786        Fut: Future<Output = Result<O>> + Send + 'static,
7787    {
7788        let workflow_type = workflow_type.into();
7789        if !self.admit_registration::<F>(
7790            RegistrationKind::Workflow,
7791            None,
7792            &workflow_type,
7793            "register_typed_replayed_workflow",
7794        ) {
7795            return;
7796        }
7797        let state_factory = Arc::new(state_factory);
7798        let handler = Arc::new(handler);
7799
7800        let execute_name = workflow_type.clone();
7801        let execute_factory = Arc::clone(&state_factory);
7802        let execute_handler = Arc::clone(&handler);
7803        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7804            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7805            let state = WorkflowInstance::new(execute_factory());
7806            let handler = Arc::clone(&execute_handler);
7807            let handler_name = execute_name.clone();
7808            Ok(Box::pin(async move {
7809                let result = handler(ctx, input, state).await?;
7810                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7811            }) as WorkflowFuture)
7812        });
7813
7814        let replay_name = workflow_type.clone();
7815        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7816            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7817            let state = WorkflowInstance::new(state_factory());
7818            let snapshot_state = state.clone();
7819            let snapshot: WorkflowStateSnapshot =
7820                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7821            let handler = Arc::clone(&handler);
7822            let handler_name = replay_name.clone();
7823            let future = async move {
7824                let result = handler(ctx, input, state).await?;
7825                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7826            };
7827            Ok(ReplayedWorkflowInvocation {
7828                future: Box::pin(future),
7829                snapshot,
7830            })
7831        });
7832
7833        self.workflows.insert(
7834            workflow_type,
7835            RegisteredWorkflow {
7836                execute,
7837                replay: Some(replay),
7838                state_type: Some(TypeId::of::<S>()),
7839                definition_fingerprint: None,
7840            },
7841        );
7842    }
7843
7844    /// Declare the signal names consumed by a registered workflow.
7845    ///
7846    /// Call this after registering the workflow and before starting the worker.
7847    /// Names read through `wait_signal` or `signals` need a declaration for
7848    /// Server command admission. Arguments remain arbitrary positional values,
7849    /// including lossless Avro values. This replaces the previous declaration;
7850    /// an empty slice declares no signals. Names are sorted and deduplicated.
7851    /// Existing runs retain the declarations captured when they started.
7852    pub fn declare_workflow_signals(
7853        &mut self,
7854        workflow_type: &str,
7855        signal_names: &[&str],
7856    ) -> Result<()> {
7857        if !self.workflows.contains_key(workflow_type) {
7858            return Err(Error::Codec(format!(
7859                "workflow type {workflow_type:?} is not registered"
7860            )));
7861        }
7862        if signal_names
7863            .iter()
7864            .any(|name| name.is_empty() || *name != name.trim())
7865        {
7866            return Err(Error::Codec(
7867                "signal names must be non-empty and have no surrounding whitespace".into(),
7868            ));
7869        }
7870        let mut names = signal_names
7871            .iter()
7872            .map(|name| (*name).to_string())
7873            .collect::<Vec<_>>();
7874        names.sort();
7875        names.dedup();
7876        self.signals.insert(workflow_type.to_string(), names);
7877        Ok(())
7878    }
7879
7880    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7881    ///
7882    /// Supply `include_str!` values for the workflow body and every helper whose
7883    /// behavior can affect replay. Register the workflow once, then set its
7884    /// identity before starting the worker. Duplicate registrations are invalid. The server
7885    /// rejects reusing a worker ID when its prior fingerprint disappears.
7886    /// Workflows without source identity remain runnable but cannot be safely redriven.
7887    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7888    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7889    pub fn set_workflow_definition_sources(
7890        &mut self,
7891        workflow_type: &str,
7892        sources: &[&str],
7893    ) -> Result<()> {
7894        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7895            return Err(Error::Codec(
7896                "workflow definition sources must be non-empty".to_string(),
7897            ));
7898        }
7899        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7900            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7901        })?;
7902        let mut hasher = Sha256::new();
7903        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7904        hasher.update((workflow_type.len() as u64).to_be_bytes());
7905        hasher.update(workflow_type.as_bytes());
7906        for source in sources {
7907            hasher.update((source.len() as u64).to_be_bytes());
7908            hasher.update(source.as_bytes());
7909        }
7910        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7911        Ok(())
7912    }
7913
7914    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7915    #[track_caller]
7916    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7917        &mut self,
7918        workflow_type: impl Into<String>,
7919        state_factory: Factory,
7920        handler: F,
7921    ) where
7922        S: Clone + Send + Sync + 'static,
7923        Factory: Fn() -> S + Send + Sync + 'static,
7924        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7925        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7926    {
7927        let workflow_type = workflow_type.into();
7928        if !self.admit_registration::<F>(
7929            RegistrationKind::Workflow,
7930            None,
7931            &workflow_type,
7932            "register_replayed_workflow_avro_value",
7933        ) {
7934            return;
7935        }
7936        let state_factory = Arc::new(state_factory);
7937        let handler = Arc::new(handler);
7938
7939        let execute_factory = Arc::clone(&state_factory);
7940        let execute_handler = Arc::clone(&handler);
7941        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7942            let state = WorkflowInstance::new(execute_factory());
7943            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7944        });
7945
7946        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7947            let state = WorkflowInstance::new(state_factory());
7948            let snapshot_state = state.clone();
7949            let snapshot: WorkflowStateSnapshot =
7950                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7951            Ok(ReplayedWorkflowInvocation {
7952                future: Box::pin(handler(ctx, input, state)),
7953                snapshot,
7954            })
7955        });
7956
7957        self.workflows.insert(
7958            workflow_type,
7959            RegisteredWorkflow {
7960                execute,
7961                replay: Some(replay),
7962                state_type: Some(TypeId::of::<S>()),
7963                definition_fingerprint: None,
7964            },
7965        );
7966    }
7967
7968    #[track_caller]
7969    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7970    where
7971        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7972        Fut: Future<Output = Result<Value>> + Send + 'static,
7973    {
7974        let activity_type = activity_type.into();
7975        if !self.admit_registration::<F>(
7976            RegistrationKind::Activity,
7977            None,
7978            &activity_type,
7979            "register_activity",
7980        ) {
7981            return;
7982        }
7983        let handler = Arc::new(handler);
7984        self.activities.insert(
7985            activity_type,
7986            Arc::new(move |ctx, args| {
7987                let handler = Arc::clone(&handler);
7988                Box::pin(async move {
7989                    let result = handler(ctx, args.into_json()?).await?;
7990                    AvroValue::from_serialize(&result)
7991                })
7992            }),
7993        );
7994    }
7995
7996    /// Register an activity with one Serde request value and a Serde result.
7997    ///
7998    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7999    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
8000    /// with the activity name and Rust type.
8001    #[track_caller]
8002    pub fn register_typed_activity<I, O, F, Fut>(
8003        &mut self,
8004        activity_type: impl Into<String>,
8005        handler: F,
8006    ) where
8007        I: DeserializeOwned + Send + 'static,
8008        O: Serialize + Send + 'static,
8009        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
8010        Fut: Future<Output = Result<O>> + Send + 'static,
8011    {
8012        let activity_type = activity_type.into();
8013        if !self.admit_registration::<F>(
8014            RegistrationKind::Activity,
8015            None,
8016            &activity_type,
8017            "register_typed_activity",
8018        ) {
8019            return;
8020        }
8021        let handler_name = activity_type.clone();
8022        let handler = Arc::new(handler);
8023        self.activities.insert(
8024            activity_type,
8025            Arc::new(move |ctx, input| {
8026                let handler = Arc::clone(&handler);
8027                let handler_name = handler_name.clone();
8028                Box::pin(async move {
8029                    let input =
8030                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
8031                    let result = handler(ctx, input).await?;
8032                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
8033                })
8034            }),
8035        );
8036    }
8037
8038    /// Register an activity on the lossless fixed Avro Value surface.
8039    #[track_caller]
8040    pub fn register_activity_avro_value<F, Fut>(
8041        &mut self,
8042        activity_type: impl Into<String>,
8043        handler: F,
8044    ) where
8045        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
8046        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8047    {
8048        let activity_type = activity_type.into();
8049        if !self.admit_registration::<F>(
8050            RegistrationKind::Activity,
8051            None,
8052            &activity_type,
8053            "register_activity_avro_value",
8054        ) {
8055            return;
8056        }
8057        self.activities.insert(
8058            activity_type,
8059            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8060        );
8061    }
8062
8063    /// Register a named, read-only query handler for a workflow type.
8064    ///
8065    /// The workflow type must also be registered with [`Worker::register_workflow`]
8066    /// before the worker runs. The handler receives only an immutable committed
8067    /// state snapshot and normalized query arguments.
8068    #[track_caller]
8069    pub fn register_query<F, Fut>(
8070        &mut self,
8071        workflow_type: impl Into<String>,
8072        query_name: impl Into<String>,
8073        handler: F,
8074    ) where
8075        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8076        Fut: Future<Output = Result<Value>> + Send + 'static,
8077    {
8078        let workflow_type = workflow_type.into();
8079        let query_name = query_name.into();
8080        if !self.admit_registration::<F>(
8081            RegistrationKind::Query,
8082            Some(&workflow_type),
8083            &query_name,
8084            "register_query",
8085        ) {
8086            return;
8087        }
8088        let handler = Arc::new(handler);
8089        self.queries.entry(workflow_type).or_default().insert(
8090            query_name,
8091            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
8092                let handler = Arc::clone(&handler);
8093                Box::pin(async move {
8094                    let result = handler(ctx, args.into_json()?).await?;
8095                    AvroValue::from_serialize(&result)
8096                })
8097            })),
8098        );
8099    }
8100
8101    /// Register a query handler on the lossless fixed Avro Value surface.
8102    #[track_caller]
8103    pub fn register_query_avro_value<F, Fut>(
8104        &mut self,
8105        workflow_type: impl Into<String>,
8106        query_name: impl Into<String>,
8107        handler: F,
8108    ) where
8109        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8110        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8111    {
8112        let workflow_type = workflow_type.into();
8113        let query_name = query_name.into();
8114        if !self.admit_registration::<F>(
8115            RegistrationKind::Query,
8116            Some(&workflow_type),
8117            &query_name,
8118            "register_query_avro_value",
8119        ) {
8120            return;
8121        }
8122        self.queries.entry(workflow_type).or_default().insert(
8123            query_name,
8124            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
8125        );
8126    }
8127
8128    /// Register a named query against deterministically replayed instance state.
8129    ///
8130    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
8131    /// same state type `S`. The handler receives an immutable, detached state
8132    /// clone, so successful and failed queries cannot affect workflow execution
8133    /// or the state reconstructed by a later query.
8134    #[track_caller]
8135    pub fn register_replayed_query<S, F, Fut>(
8136        &mut self,
8137        workflow_type: impl Into<String>,
8138        query_name: impl Into<String>,
8139        handler: F,
8140    ) where
8141        S: Clone + Send + Sync + 'static,
8142        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
8143        Fut: Future<Output = Result<Value>> + Send + 'static,
8144    {
8145        let workflow_type = workflow_type.into();
8146        let query_name = query_name.into();
8147        if !self.admit_registration::<F>(
8148            RegistrationKind::Query,
8149            Some(&workflow_type),
8150            &query_name,
8151            "register_replayed_query",
8152        ) {
8153            return;
8154        }
8155        let handler = Arc::new(handler);
8156        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8157            let state = state.downcast::<S>().map_err(|_| {
8158                "registered query state type does not match the replayed workflow state".to_string()
8159            })?;
8160            let handler = Arc::clone(&handler);
8161            Ok(Box::pin(async move {
8162                let result = handler(ctx, state, args.into_json()?).await?;
8163                AvroValue::from_serialize(&result)
8164            }))
8165        });
8166
8167        self.queries.entry(workflow_type).or_default().insert(
8168            query_name,
8169            RegisteredQuery::Replayed {
8170                state_type: TypeId::of::<S>(),
8171                handler: erased_handler,
8172            },
8173        );
8174    }
8175
8176    /// Register a replayed-state query on the lossless fixed Avro Value surface.
8177    #[track_caller]
8178    pub fn register_replayed_query_avro_value<S, F, Fut>(
8179        &mut self,
8180        workflow_type: impl Into<String>,
8181        query_name: impl Into<String>,
8182        handler: F,
8183    ) where
8184        S: Clone + Send + Sync + 'static,
8185        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
8186        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8187    {
8188        let workflow_type = workflow_type.into();
8189        let query_name = query_name.into();
8190        if !self.admit_registration::<F>(
8191            RegistrationKind::Query,
8192            Some(&workflow_type),
8193            &query_name,
8194            "register_replayed_query_avro_value",
8195        ) {
8196            return;
8197        }
8198        let handler = Arc::new(handler);
8199        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8200            let state = state.downcast::<S>().map_err(|_| {
8201                "registered query state type does not match the replayed workflow state".to_string()
8202            })?;
8203            Ok(Box::pin(handler(ctx, state, args)))
8204        });
8205
8206        self.queries.entry(workflow_type).or_default().insert(
8207            query_name,
8208            RegisteredQuery::Replayed {
8209                state_type: TypeId::of::<S>(),
8210                handler: erased_handler,
8211            },
8212        );
8213    }
8214
8215    /// Register a synchronous workflow update handler.
8216    #[track_caller]
8217    pub fn register_update<F, Fut>(
8218        &mut self,
8219        workflow_type: impl Into<String>,
8220        update_name: impl Into<String>,
8221        handler: F,
8222    ) where
8223        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8224        Fut: Future<Output = Result<Value>> + Send + 'static,
8225    {
8226        let workflow_type = workflow_type.into();
8227        let update_name = update_name.into();
8228        if !self.admit_registration::<F>(
8229            RegistrationKind::Update,
8230            Some(&workflow_type),
8231            &update_name,
8232            "register_update",
8233        ) {
8234            return;
8235        }
8236        let handler = Arc::new(handler);
8237        self.updates.entry(workflow_type).or_default().insert(
8238            update_name,
8239            Arc::new(move |ctx, args| {
8240                let handler = Arc::clone(&handler);
8241                Box::pin(async move {
8242                    let result = handler(ctx, args.into_json()?).await?;
8243                    AvroValue::from_serialize(&result)
8244                })
8245            }),
8246        );
8247    }
8248
8249    /// Register an update handler on the lossless fixed Avro Value surface.
8250    #[track_caller]
8251    pub fn register_update_avro_value<F, Fut>(
8252        &mut self,
8253        workflow_type: impl Into<String>,
8254        update_name: impl Into<String>,
8255        handler: F,
8256    ) where
8257        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8258        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8259    {
8260        let workflow_type = workflow_type.into();
8261        let update_name = update_name.into();
8262        if !self.admit_registration::<F>(
8263            RegistrationKind::Update,
8264            Some(&workflow_type),
8265            &update_name,
8266            "register_update_avro_value",
8267        ) {
8268            return;
8269        }
8270        self.updates.entry(workflow_type).or_default().insert(
8271            update_name,
8272            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8273        );
8274    }
8275
8276    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
8277        self.validate_registration()?;
8278        self.nexus_registration_confirmed
8279            .store(false, Ordering::SeqCst);
8280        self.query_authority_confirmed
8281            .store(false, Ordering::SeqCst);
8282        if self.nexus_cooperative_cancellation_enabled {
8283            let info: Value = self
8284                .client
8285                .request_json(
8286                    reqwest::Method::GET,
8287                    "/cluster/info",
8288                    RequestProtocol::Worker("1.20"),
8289                    Option::<&Value>::None,
8290                )
8291                .await?;
8292            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
8293                return Err(Error::CooperativeCancellationUnavailable(
8294                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
8295                ));
8296            }
8297        }
8298        if self.require_query_task_authority {
8299            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
8300                return Err(Error::WorkerLoop(
8301                    "query authority requires worker protocol 1.20".into(),
8302                ));
8303            }
8304            // Discovery uses the Worker credential, including worker-only Clients.
8305            let discovery: Value = self
8306                .client
8307                .request_json_unresolved_with_timeout::<Value, Value>(
8308                    reqwest::Method::GET,
8309                    "/cluster/info",
8310                    RequestProtocol::Worker("1.20"),
8311                    None,
8312                    Duration::from_secs(5),
8313                )
8314                .await?;
8315            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
8316                return Err(Error::WorkerLoop(
8317                    "runtime does not advertise query_task_authority".into(),
8318                ));
8319            }
8320        }
8321        self.sticky_registration_confirmed
8322            .store(false, Ordering::SeqCst);
8323        self.session_registration_confirmed
8324            .store(false, Ordering::SeqCst);
8325        for capability in &self.resource_capabilities {
8326            worker_session::validate_resource_capability(capability)?;
8327        }
8328        self.local_registration_confirmed
8329            .store(false, Ordering::SeqCst);
8330        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
8331            return Err(Error::CooperativeCancellationUnavailable(
8332                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
8333            ));
8334        }
8335        let mut command_contracts = serde_json::Map::new();
8336        for workflow_type in self.workflows.keys() {
8337            let mut queries = self
8338                .queries
8339                .get(workflow_type)
8340                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8341                .unwrap_or_default();
8342            queries.sort();
8343            let mut updates = self
8344                .updates
8345                .get(workflow_type)
8346                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8347                .unwrap_or_default();
8348            updates.sort();
8349            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
8350            command_contracts.insert(
8351                workflow_type.clone(),
8352                json!({
8353                    "queries": queries,
8354                    "query_contracts": argument_vector_contracts(&queries),
8355                    "signals": signals,
8356                    "signal_contracts": argument_vector_contracts(&signals),
8357                    "updates": updates,
8358                    "update_contracts": argument_vector_contracts(&updates),
8359                    "update_validators": [],
8360                }),
8361            );
8362        }
8363
8364        self.cooperative_registration_confirmed
8365            .store(false, Ordering::SeqCst);
8366        #[cfg(feature = "telemetry")]
8367        if self
8368            .telemetry
8369            .as_ref()
8370            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
8371            && !self
8372                .client
8373                .observability_context_supported
8374                .load(Ordering::SeqCst)
8375        {
8376            // Optional startup discovery is bounded and cached. Its failure
8377            // cannot refuse registration or add retries to a business command.
8378            let _ = self
8379                .client
8380                .request_json_unresolved_with_timeout::<Value, Value>(
8381                    reqwest::Method::GET,
8382                    "/cluster/info",
8383                    RequestProtocol::DefaultWorker,
8384                    None,
8385                    Duration::from_secs(5),
8386                )
8387                .await;
8388        }
8389        let response = self
8390            .client
8391            .register_worker_with_definition_fingerprints(
8392                &self.worker_id,
8393                &self.task_queue,
8394                self.workflows.keys().cloned().collect(),
8395                self.activities.keys().cloned().collect(),
8396                self.max_concurrent_workflow_tasks,
8397                self.max_concurrent_activity_tasks,
8398                [
8399                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
8400                    Some("workflow_entry_arguments_validation".to_string()),
8401                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
8402                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
8403                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
8404                    self.client
8405                        .local_activities_enabled
8406                        .then(|| "local_activities".to_string()),
8407                    self.client
8408                        .worker_sessions_enabled
8409                        .then(|| "worker_sessions".to_string()),
8410                    self.client
8411                        .sticky_cache
8412                        .is_some()
8413                        .then(|| "sticky_execution".to_string()),
8414                    self.cooperative_cancellation_enabled
8415                        .then(|| "cooperative_cancellation".to_string()),
8416                    self.nexus_cooperative_cancellation_enabled
8417                        .then(|| "nexus_cooperative_cancellation".to_string()),
8418                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
8419                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
8420                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
8421                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
8422                ]
8423                .into_iter()
8424                .flatten()
8425                .chain(self.resource_capabilities.iter().cloned())
8426                .collect(),
8427                Value::Object(command_contracts),
8428                Some(
8429                    self.workflows
8430                        .iter()
8431                        .filter_map(|(workflow_type, workflow)| {
8432                            workflow
8433                                .definition_fingerprint
8434                                .as_ref()
8435                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
8436                        })
8437                        .collect(),
8438                ),
8439            )
8440            .await?;
8441        if self.cooperative_cancellation_enabled && response.registered {
8442            self.cooperative_registration_confirmed
8443                .store(true, Ordering::SeqCst);
8444        }
8445        if self.nexus_cooperative_cancellation_enabled && response.registered {
8446            self.nexus_registration_confirmed
8447                .store(true, Ordering::SeqCst);
8448        }
8449        if self.client.local_activities_enabled && response.registered {
8450            self.local_registration_confirmed
8451                .store(true, Ordering::SeqCst);
8452        }
8453        if self.client.worker_sessions_enabled && response.registered {
8454            self.session_registration_confirmed
8455                .store(true, Ordering::SeqCst);
8456        }
8457        if self.client.sticky_cache.is_some() && response.registered {
8458            self.sticky_registration_confirmed
8459                .store(true, Ordering::SeqCst);
8460        }
8461        self.query_authority_confirmed.store(
8462            response.registered
8463                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
8464                && response
8465                    .server_capabilities
8466                    .as_ref()
8467                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
8468            Ordering::SeqCst,
8469        );
8470        Ok(response)
8471    }
8472
8473    /// Run until shutdown or a terminal worker error occurs.
8474    ///
8475    /// Empty long-poll expirations do not stop the worker. Retryable poll and
8476    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
8477    /// authentication, protocol, and other non-retryable failures are returned.
8478    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
8479    /// poll and heartbeat outages beyond the ordinary retry budget.
8480    pub async fn run(&self) -> Result<()> {
8481        self.run_until(std::future::pending::<()>()).await
8482    }
8483
8484    /// Run until `shutdown` resolves or a terminal worker error occurs.
8485    ///
8486    /// This has the same liveness and terminal-error contract as [`Worker::run`].
8487    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
8488    where
8489        F: Future<Output = ()>,
8490    {
8491        let _clear_cache_on_drop =
8492            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
8493        let stop = Arc::new(AtomicBool::new(false));
8494        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
8495        let mut worker = self.with_storage_admission(Arc::clone(&stop));
8496        worker.run_stop = Some(Arc::clone(&stop));
8497        let run = worker.run_with_storage_admission(Arc::clone(&stop));
8498        tokio::pin!(run);
8499        tokio::pin!(shutdown);
8500        tokio::select! {
8501            result = &mut run => result,
8502            _ = &mut shutdown => {
8503                stop.store(true, Ordering::SeqCst);
8504                run.await
8505            }
8506        }
8507    }
8508
8509    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
8510        let mut worker = self.clone();
8511        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
8512            policy: self.retry_policy,
8513            stop,
8514            workflow_completion_retry_deadline: None,
8515        });
8516        worker
8517    }
8518
8519    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8520        let registration = self.register().await?;
8521        if !registration.registered {
8522            return Err(Error::WorkerLoop(format!(
8523                "worker registration for {:?} was not accepted",
8524                self.worker_id
8525            )));
8526        }
8527        let registered_worker_id = registration.worker_id.clone();
8528        let primary = self.run_registered_until(stop, registration).await;
8529        let primary = match (primary, self.close_worker_sessions().await) {
8530            (Ok(()), result) => result,
8531            (Err(error), Ok(())) => Err(error),
8532            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8533                primary: Box::new(primary),
8534                deregistration: Box::new(close),
8535            }),
8536        };
8537        self.session_registration_confirmed
8538            .store(false, Ordering::SeqCst);
8539        self.cooperative_registration_confirmed
8540            .store(false, Ordering::SeqCst);
8541        self.local_registration_confirmed
8542            .store(false, Ordering::SeqCst);
8543        let deregistration = self
8544            .client
8545            .deregister_worker_registration(&registered_worker_id)
8546            .await;
8547        self.sticky_registration_confirmed
8548            .store(false, Ordering::SeqCst);
8549        self.client.clear_sticky_cache()?;
8550
8551        match (primary, deregistration) {
8552            (Ok(()), Ok(_)) => Ok(()),
8553            (Ok(()), Err(deregistration)) => Err(deregistration),
8554            (Err(primary), Ok(_)) => Err(primary),
8555            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8556                primary: Box::new(primary),
8557                deregistration: Box::new(deregistration),
8558            }),
8559        }
8560    }
8561
8562    async fn run_registered_until(
8563        &self,
8564        stop: Arc<AtomicBool>,
8565        registration: RegisterWorkerResponse,
8566    ) -> Result<()> {
8567        if self.require_query_task_authority
8568            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8569        {
8570            return Err(Error::WorkerLoop(
8571                "registration did not confirm query_task_authority".into(),
8572            ));
8573        }
8574        let heartbeat_interval = Duration::from_secs(
8575            registration
8576                .heartbeat_interval_seconds
8577                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8578        );
8579        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8580        // from the completion of the preceding attempt, including its bounded
8581        // retries. A fixed-epoch interval can leave an already-due tick queued
8582        // while an acknowledgement is slow, producing a catch-up heartbeat as
8583        // soon as that request completes.
8584        let heartbeat = tokio::time::sleep(Duration::ZERO);
8585        tokio::pin!(heartbeat);
8586        // Poll responses may already have leased server-side work by the time
8587        // they become ready, so each poller owns its responses through
8588        // completion or failure instead of racing raw polls in this select.
8589        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
8590            let worker = self.clone();
8591            let stop = Arc::clone(&stop);
8592            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
8593        });
8594        let mut activity_poller = (!self.activities.is_empty()).then(|| {
8595            let worker = self.clone();
8596            let stop = Arc::clone(&stop);
8597            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
8598        });
8599        let mut query_poller = (!self.queries.is_empty()).then(|| {
8600            let worker = self.clone();
8601            let stop = Arc::clone(&stop);
8602            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
8603        });
8604
8605        loop {
8606            tokio::select! {
8607                _ = wait_for_worker_stop(&stop) => {
8608                    stop.store(true, Ordering::SeqCst);
8609                    break;
8610                }
8611                _ = &mut heartbeat => {
8612                    let result = self.retry_worker_operation(|| {
8613                        self.client.heartbeat_worker_with_sessions(
8614                            &self.worker_id,
8615                            self.workflow_capacity.available(),
8616                            self.activity_capacity.available(),
8617                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8618                        )
8619                    }).await;
8620                    heartbeat
8621                        .as_mut()
8622                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8623                    match result {
8624                        Ok(Some(acknowledgement)) => {
8625                            if let Some(observer) = &self.heartbeat_observer {
8626                                observer(&WorkerHeartbeatObservation {
8627                                    worker_id: self.worker_id.clone(),
8628                                    task_queue: self.task_queue.clone(),
8629                                    acknowledged_at_unix_millis: SystemTime::now()
8630                                        .duration_since(UNIX_EPOCH)
8631                                        .unwrap_or_default()
8632                                        .as_millis()
8633                                        .min(u64::MAX as u128)
8634                                        as u64,
8635                                    acknowledgement,
8636                                });
8637                            }
8638                        }
8639                        Ok(None) => break,
8640                        Err(error) => {
8641                            stop.store(true, Ordering::SeqCst);
8642                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8643                            return Err(error);
8644                        }
8645                    }
8646                }
8647                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8648                    workflow_poller = None;
8649                    let stopped_by_server = stop.load(Ordering::SeqCst);
8650                    stop.store(true, Ordering::SeqCst);
8651                    let poller_result = optional_poller_result("workflow", result);
8652                    let join_result =
8653                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8654                    poller_result?;
8655                    join_result?;
8656                    if stopped_by_server {
8657                        return Ok(());
8658                    }
8659                    return Err(Error::WorkerLoop(
8660                        "workflow poller stopped unexpectedly".to_string(),
8661                    ));
8662                }
8663                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8664                    activity_poller = None;
8665                    let stopped_by_server = stop.load(Ordering::SeqCst);
8666                    stop.store(true, Ordering::SeqCst);
8667                    let poller_result = optional_poller_result("activity", result);
8668                    let join_result =
8669                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8670                    poller_result?;
8671                    join_result?;
8672                    if stopped_by_server {
8673                        return Ok(());
8674                    }
8675                    return Err(Error::WorkerLoop(
8676                        "activity poller stopped unexpectedly".to_string(),
8677                    ));
8678                }
8679                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8680                    query_poller = None;
8681                    let stopped_by_server = stop.load(Ordering::SeqCst);
8682                    stop.store(true, Ordering::SeqCst);
8683                    let poller_result = optional_poller_result("query", result);
8684                    let join_result =
8685                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8686                    poller_result?;
8687                    join_result?;
8688                    if stopped_by_server {
8689                        return Ok(());
8690                    }
8691                    return Err(Error::WorkerLoop(
8692                        "query poller stopped unexpectedly".to_string(),
8693                    ));
8694                }
8695            }
8696        }
8697
8698        join_pollers(
8699            workflow_poller.take(),
8700            activity_poller.take(),
8701            query_poller.take(),
8702        )
8703        .await
8704    }
8705
8706    /// Poll and settle at most one task from each enabled task family.
8707    ///
8708    /// A workflow may reach its server-enforced run deadline while this worker
8709    /// holds a task. When the completion endpoint authoritatively rejects that
8710    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8711    /// terminal `run_status=failed`, the workflow tick is considered settled:
8712    /// the late command was not recorded and cannot replace the terminal run.
8713    /// Every other completion rejection remains an error. This worker-level
8714    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8715    /// only bounds how long a client waits for a result.
8716    ///
8717    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8718    /// the original [`Error::Http`] status and response body.
8719    pub async fn run_once(&self) -> Result<usize> {
8720        self.validate_registration()?;
8721        if self.client.worker_sessions_enabled {
8722            self.require_session_registration()?;
8723        }
8724        if self.cooperative_cancellation_enabled
8725            && !self
8726                .cooperative_registration_confirmed
8727                .load(Ordering::SeqCst)
8728        {
8729            return Err(Error::CooperativeCancellationUnavailable(
8730                "register this cooperative worker before polling tasks".into(),
8731            ));
8732        }
8733        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8734        let mut handled = 0;
8735        match worker.poll_workflow_once().await? {
8736            ManagedPollOutcome::Handled => handled += 1,
8737            ManagedPollOutcome::Stop => return Ok(handled),
8738            ManagedPollOutcome::Idle => {}
8739        }
8740        match worker.poll_activity_once().await? {
8741            ManagedPollOutcome::Handled => handled += 1,
8742            ManagedPollOutcome::Stop => return Ok(handled),
8743            ManagedPollOutcome::Idle => {}
8744        }
8745        if !self.queries.is_empty() {
8746            match worker.poll_query_once().await? {
8747                ManagedPollOutcome::Handled => handled += 1,
8748                ManagedPollOutcome::Stop => return Ok(handled),
8749                ManagedPollOutcome::Idle => {}
8750            }
8751        }
8752        Ok(handled)
8753    }
8754
8755    async fn poll_workflow_once_reserved(&self) -> Result<ManagedPollOutcome> {
8756        if self.client.sticky_cache.is_some()
8757            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8758        {
8759            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8760        }
8761        if self.client.local_activities_enabled
8762            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8763        {
8764            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8765        }
8766        if self.cooperative_cancellation_enabled {
8767            return self.poll_cooperative_workflow_once().await;
8768        }
8769        let poll_request_id = unique_request_id("rust-workflow-poll");
8770        let response = self
8771            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8772            .await;
8773        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8774            return Ok(ManagedPollOutcome::Idle);
8775        };
8776        if response.outcome().should_stop() {
8777            return Ok(ManagedPollOutcome::Stop);
8778        }
8779        let memo_updates_supported =
8780            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8781        let Some(task) = response.task else {
8782            return Ok(ManagedPollOutcome::Idle);
8783        };
8784
8785        let task_id = task.task_id.clone();
8786        let attempt = task.workflow_task_attempt;
8787        let run_id = task.run_id.clone();
8788        let lease_owner = task
8789            .lease_owner
8790            .clone()
8791            .unwrap_or_else(|| self.worker_id.clone());
8792
8793        let decision = match self.execute_workflow_with_local_activities(task).await {
8794            Ok(Some(decision)) => Ok(decision),
8795            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8796            Err(error) => Err(error),
8797        };
8798        self.settle_workflow_task_decision(
8799            &task_id,
8800            &lease_owner,
8801            attempt,
8802            run_id.as_deref(),
8803            decision,
8804            memo_updates_supported,
8805            snapshot,
8806        )
8807        .await
8808    }
8809
8810    #[allow(clippy::too_many_arguments)]
8811    async fn settle_workflow_task_decision(
8812        &self,
8813        task_id: &str,
8814        lease_owner: &str,
8815        attempt: u64,
8816        run_id: Option<&str>,
8817        decision: Result<WorkflowTaskDecision>,
8818        memo_updates_supported: bool,
8819        snapshot: Option<sticky_worker::StickySnapshot>,
8820    ) -> Result<ManagedPollOutcome> {
8821        match decision {
8822            Ok(decision)
8823                if decision.cancellation_delivery.is_some()
8824                    || decision.cancellation_scope_delivery.is_some()
8825                    || decision.cancellation_scope_opening.is_some() =>
8826            {
8827                return Err(Error::CooperativeCancellationUnavailable(
8828                    "worker cancellation delivery has not been negotiated".into(),
8829                ));
8830            }
8831            Ok(decision)
8832                if commands_use_workflow_memo_updates(&decision.commands)
8833                    && !memo_updates_supported =>
8834            {
8835                self.client
8836                    .fail_workflow_task(
8837                        task_id,
8838                        lease_owner,
8839                        attempt,
8840                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8841                    )
8842                    .await?;
8843            }
8844            Ok(decision) if decision.commands.is_empty() => {
8845                // A replay can consume a recorded pending durable command
8846                // without producing a new command. The standalone protocol
8847                // acknowledges that state through the typed waiting outcome;
8848                // an empty completion is rejected by servers that require at
8849                // least one executable command.
8850                self.client
8851                    .fail_workflow_task_with_type(
8852                        task_id,
8853                        lease_owner,
8854                        attempt,
8855                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8856                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8857                    )
8858                    .await?;
8859            }
8860            Ok(decision) => {
8861                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8862                let completion = self
8863                    .client
8864                    .complete_workflow_task_with_message_streams(
8865                        task_id,
8866                        lease_owner,
8867                        attempt,
8868                        decision.commands,
8869                        decision.message_stream_cursors,
8870                        decision.message_stream_waits,
8871                        sticky_claim,
8872                    )
8873                    .await;
8874                if let Err(error) = completion {
8875                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8876                    if !workflow_task_completion_is_terminal_timeout(
8877                        &error, task_id, attempt, run_id,
8878                    ) {
8879                        return Err(error);
8880                    }
8881                }
8882            }
8883            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8884            Err(error) => {
8885                self.discard_sticky_snapshot(snapshot.as_ref())?;
8886                if matches!(
8887                    error,
8888                    Error::HandlerType {
8889                        handler_kind: HandlerKind::Workflow,
8890                        value_kind: HandlerValueKind::Input,
8891                        ..
8892                    }
8893                ) {
8894                    self.client
8895                        .fail_workflow_task_with_failure(
8896                            task_id,
8897                            lease_owner,
8898                            attempt,
8899                            json!({
8900                                "message": error.to_string(),
8901                                "type": "WorkflowEntryArgumentsMismatch",
8902                                "reason": "workflow_entry_arguments_mismatch",
8903                            }),
8904                        )
8905                        .await?;
8906                } else {
8907                    self.client
8908                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8909                        .await?;
8910                }
8911            }
8912        }
8913
8914        Ok(ManagedPollOutcome::Handled)
8915    }
8916
8917    async fn poll_activity_once_reserved(&self) -> Result<ManagedPollOutcome> {
8918        if self.client.worker_sessions_enabled {
8919            self.require_session_registration()?;
8920        }
8921        let poll_request_id = unique_request_id("rust-activity-poll");
8922        let response = self
8923            .retry_worker_operation(|| {
8924                self.client.poll_activity_task_response_with_request_id(
8925                    &self.worker_id,
8926                    &self.task_queue,
8927                    self.poll_timeout,
8928                    &poll_request_id,
8929                    0,
8930                )
8931            })
8932            .await;
8933        let response = match response {
8934            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8935            response => response,
8936        };
8937        let Some(response) = self.settle_worker_poll_response(response).await? else {
8938            return Ok(ManagedPollOutcome::Idle);
8939        };
8940        if response.outcome().should_stop() {
8941            return Ok(ManagedPollOutcome::Stop);
8942        }
8943        let Some(task) = response.task else {
8944            return Ok(ManagedPollOutcome::Idle);
8945        };
8946
8947        self.settle_polled_activity(task).await
8948    }
8949
8950    async fn settle_polled_activity(
8951        &self,
8952        task: worker_session::SessionActivityTask,
8953    ) -> Result<ManagedPollOutcome> {
8954        let lease = task.activity_lease.clone();
8955        let mut worker = self.clone();
8956        worker.client = self.client.with_activity_lease_authority(
8957            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
8958        );
8959        let operation = worker.execute_polled_activity(task);
8960        let result = match lease.as_ref() {
8961            Some(lease) => lease.authority.protect(operation).await,
8962            None => operation.await,
8963        };
8964        match result {
8965            Err(Error::ActivityExecutionAbandoned(_)) => Ok(ManagedPollOutcome::Handled),
8966            result => result,
8967        }
8968    }
8969
8970    async fn execute_polled_activity(
8971        &self,
8972        task: worker_session::SessionActivityTask,
8973    ) -> Result<ManagedPollOutcome> {
8974        if self.cooperative_cancellation_enabled {
8975            return self.settle_cooperative_activity(task).await;
8976        }
8977        let session = self.track_session_task(task.worker_session.as_ref())?;
8978        let hydration_claim = task.hydration_claim;
8979        let task = task.task;
8980
8981        let task_id = task.task_id.clone();
8982        let attempt_id = task
8983            .activity_attempt_id
8984            .clone()
8985            .or(task.attempt_id.clone())
8986            .unwrap_or_default();
8987        let lease_owner = task
8988            .lease_owner
8989            .clone()
8990            .unwrap_or_else(|| self.worker_id.clone());
8991        let codec = task.payload_codec.clone();
8992        let result = self
8993            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8994            .await;
8995        match result {
8996            Err(Error::ActivityExecutionAbandoned(_)) => {}
8997            Err(error) if activity_hydration::stopped(&error) => {}
8998            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8999            Ok(value) => {
9000                let completion = self
9001                    .client
9002                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
9003                    .await;
9004                if let Err(error) = completion {
9005                    if !activity_task_rejection_is_final(&error) {
9006                        return Err(error);
9007                    }
9008                }
9009            }
9010            Err(error) => {
9011                let failure = self
9012                    .client
9013                    .fail_activity_task_with_error(
9014                        &task_id,
9015                        &attempt_id,
9016                        &lease_owner,
9017                        &ActivityError::from_error(&error, "RustActivityFailure"),
9018                    )
9019                    .await;
9020                if let Err(error) = failure {
9021                    if !activity_task_rejection_is_final(&error) {
9022                        return Err(error);
9023                    }
9024                }
9025            }
9026        }
9027
9028        Ok(ManagedPollOutcome::Handled)
9029    }
9030
9031    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
9032        let poll_request_id = unique_request_id("rust-query-poll");
9033        let response = self
9034            .retry_worker_operation(|| {
9035                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
9036                    "poll_request_id":poll_request_id,
9037                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
9038                async move {
9039                    self.client
9040                        .poll_request_json_unresolved::<Value, Value>(
9041                            "/worker/query-tasks/poll",
9042                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
9043                            &body,
9044                            self.poll_timeout + Duration::from_secs(5),
9045                            0,
9046                        )
9047                        .await
9048                }
9049            })
9050            .await;
9051        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
9052            return Ok(ManagedPollOutcome::Idle);
9053        };
9054        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
9055            match query_authority::Authority::capture(&wire["task"], self) {
9056                Ok(authority) => authority,
9057                Err(_) => return Ok(ManagedPollOutcome::Handled),
9058            }
9059        } else {
9060            None
9061        };
9062        let loading = self.client.resolve_runtime_payloads(
9063            &mut wire,
9064            "/worker/query-tasks/poll",
9065            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
9066        );
9067        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
9068            Err(_) => return Ok(ManagedPollOutcome::Handled),
9069            Ok(result) => result?,
9070        }
9071        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
9072        if response.outcome().should_stop() {
9073            return Ok(ManagedPollOutcome::Stop);
9074        }
9075        let Some(task) = response.task else {
9076            return Ok(ManagedPollOutcome::Idle);
9077        };
9078
9079        let query_task_id = task.query_task_id.clone();
9080        let attempt = task.query_task_attempt;
9081        let lease_owner = task
9082            .lease_owner
9083            .clone()
9084            .unwrap_or_else(|| self.worker_id.clone());
9085        let codec = task.payload_codec.clone();
9086
9087        let execution = query_authority::Authority::protect(
9088            authority.as_ref(),
9089            self,
9090            self.execute_query_task_with_authority(task, authority.as_ref()),
9091        )
9092        .await;
9093        let execution = match execution {
9094            Err(_) => return Ok(ManagedPollOutcome::Handled),
9095            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
9096                return Ok(ManagedPollOutcome::Handled)
9097            }
9098            Ok(result) => result,
9099        };
9100        match execution {
9101            Ok(value) => {
9102                let result_envelope = match encode_typed_envelope(&value, &codec) {
9103                    Ok(result_envelope) => result_envelope,
9104                    Err(error) => {
9105                        let failure = query_authority::Authority::protect(
9106                            authority.as_ref(),
9107                            self,
9108                            self.client.fail_query_task(
9109                                &query_task_id,
9110                                &lease_owner,
9111                                attempt,
9112                                error.to_string(),
9113                                "query_result_encode_failed",
9114                                "QueryResultEncodeFailed",
9115                            ),
9116                        )
9117                        .await;
9118                        let Ok(failure) = failure else {
9119                            return Ok(ManagedPollOutcome::Handled);
9120                        };
9121                        if let Err(error) = failure {
9122                            if !query_task_rejection_is_final(&error) {
9123                                return Err(error);
9124                            }
9125                        }
9126                        return Ok(ManagedPollOutcome::Handled);
9127                    }
9128                };
9129
9130                let completion = query_authority::Authority::protect(
9131                    authority.as_ref(),
9132                    self,
9133                    self.client.complete_query_task_with_envelope(
9134                        &query_task_id,
9135                        &lease_owner,
9136                        attempt,
9137                        value.clone().into_json()?,
9138                        result_envelope,
9139                    ),
9140                )
9141                .await;
9142                let Ok(completion) = completion else {
9143                    return Ok(ManagedPollOutcome::Handled);
9144                };
9145                if let Err(error) = completion {
9146                    if !query_task_rejection_is_final(&error) {
9147                        return Err(error);
9148                    }
9149                }
9150            }
9151            Err(failure) => {
9152                let result = query_authority::Authority::protect(
9153                    authority.as_ref(),
9154                    self,
9155                    self.client.fail_query_task(
9156                        &query_task_id,
9157                        &lease_owner,
9158                        attempt,
9159                        failure.message,
9160                        failure.reason,
9161                        failure.failure_type,
9162                    ),
9163                )
9164                .await;
9165                let Ok(result) = result else {
9166                    return Ok(ManagedPollOutcome::Handled);
9167                };
9168                if let Err(error) = result {
9169                    if !query_task_rejection_is_final(&error) {
9170                        return Err(error);
9171                    }
9172                }
9173            }
9174        }
9175
9176        Ok(ManagedPollOutcome::Handled)
9177    }
9178
9179    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
9180        while !stop.load(Ordering::SeqCst) {
9181            match self.poll_query_once().await {
9182                Ok(ManagedPollOutcome::Stop) => {
9183                    stop.store(true, Ordering::SeqCst);
9184                    break;
9185                }
9186                Err(error) => {
9187                    stop.store(true, Ordering::SeqCst);
9188                    return Err(error);
9189                }
9190                _ => {}
9191            }
9192        }
9193
9194        Ok(())
9195    }
9196
9197    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
9198    where
9199        F: FnMut() -> Fut,
9200        Fut: Future<Output = Result<T>>,
9201    {
9202        let mut retries = 0;
9203
9204        loop {
9205            if self
9206                .run_stop
9207                .as_ref()
9208                .is_some_and(|stop| stop.load(Ordering::SeqCst))
9209            {
9210                return Ok(None);
9211            }
9212            match operation().await {
9213                Err(error)
9214                    if (workflow_hydration::stopped(&error)
9215                        || activity_hydration::stopped(&error))
9216                        && self
9217                            .run_stop
9218                            .as_ref()
9219                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
9220                {
9221                    return Ok(None);
9222                }
9223                Err(error)
9224                    if worker_operation_is_retryable(&error)
9225                        && (retries < self.retry_policy.max_retries
9226                            || (self.recover_transient_outages
9227                                && self.run_stop.is_some()
9228                                && self.retry_policy.max_retries > 0)) =>
9229                {
9230                    retries = retries.saturating_add(1);
9231                    let delay = worker_retry_delay(self.retry_policy, retries)
9232                        .max(Duration::from_millis(1));
9233                    if let Some(stop) = &self.run_stop {
9234                        tokio::select! {
9235                            _ = tokio::time::sleep(delay) => {}
9236                            _ = wait_for_worker_stop(stop) => return Ok(None),
9237                        }
9238                    } else {
9239                        tokio::time::sleep(delay).await;
9240                    }
9241                }
9242                result => return result.map(Some),
9243            }
9244        }
9245    }
9246
9247    async fn settle_worker_poll_response<T>(
9248        &self,
9249        response: Result<Option<T>>,
9250    ) -> Result<Option<T>> {
9251        match response {
9252            Ok(response) => Ok(response),
9253            Err(error) => {
9254                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
9255                    return Err(error);
9256                };
9257                let minimum_delay = self
9258                    .retry_policy
9259                    .initial_backoff
9260                    .max(Duration::from_millis(1));
9261                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
9262                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
9263                Ok(None)
9264            }
9265        }
9266    }
9267
9268    #[cfg(test)]
9269    async fn execute_query_task(
9270        &self,
9271        task: QueryTask,
9272    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9273        self.execute_query_task_with_authority(task, None).await
9274    }
9275
9276    async fn execute_query_task_with_authority(
9277        &self,
9278        task: QueryTask,
9279        authority: Option<&query_authority::Authority>,
9280    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9281        #[cfg(feature = "telemetry")]
9282        if let Some(telemetry) = &self.telemetry {
9283            return telemetry
9284                .run_observed(
9285                    "durable.query.task",
9286                    self.query_telemetry_fields(&task),
9287                    false,
9288                    authority.and_then(|_| self.query_observations(&task)),
9289                    self.execute_query_task_inner(task, authority),
9290                )
9291                .await;
9292        }
9293        self.execute_query_task_inner(task, authority).await
9294    }
9295
9296    async fn execute_query_task_inner(
9297        &self,
9298        mut task: QueryTask,
9299        authority: Option<&query_authority::Authority>,
9300    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9301        validate_query_task_payloads(&task).map_err(|error| {
9302            QueryTaskExecutionFailure::new(
9303                "query_payload_decode_failed",
9304                error.to_string(),
9305                "QueryPayloadDecodeFailed",
9306            )
9307        })?;
9308
9309        if !self.workflows.contains_key(&task.workflow_type) {
9310            return Err(QueryTaskExecutionFailure::new(
9311                "query_workflow_type_not_registered",
9312                format!("no workflow registered for type {:?}", task.workflow_type),
9313                "WorkflowTypeNotRegistered",
9314            ));
9315        }
9316
9317        let Some(handlers) = self.queries.get(&task.workflow_type) else {
9318            return Err(QueryTaskExecutionFailure::new(
9319                "query_handler_unavailable",
9320                format!(
9321                    "query handlers are unavailable for workflow type {:?}",
9322                    task.workflow_type
9323                ),
9324                "QueryHandlerUnavailable",
9325            ));
9326        };
9327        let Some(query) = handlers.get(&task.query_name) else {
9328            return Err(QueryTaskExecutionFailure::new(
9329                "rejected_unknown_query",
9330                format!("unknown query {:?}", task.query_name),
9331                "QueryFailed",
9332            ));
9333        };
9334
9335        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
9336            .map_err(|error| {
9337            QueryTaskExecutionFailure::new(
9338                "query_payload_decode_failed",
9339                format!("cannot decode query arguments: {error}"),
9340                "QueryPayloadDecodeFailed",
9341            )
9342        })?;
9343        let workflow_input_typed =
9344            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
9345                .map_err(|error| {
9346                    QueryTaskExecutionFailure::new(
9347                        "query_workflow_state_unavailable",
9348                        format!("cannot decode workflow start input: {error}"),
9349                        "QueryWorkflowStateUnavailable",
9350                    )
9351                })?;
9352        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
9353            QueryTaskExecutionFailure::new(
9354                "query_workflow_state_unavailable",
9355                format!("cannot project workflow start input: {error}"),
9356                "QueryWorkflowStateUnavailable",
9357            )
9358        })?;
9359        hydrate_query_history_from_export(&mut task).map_err(|error| {
9360            QueryTaskExecutionFailure::new(
9361                "query_workflow_state_unavailable",
9362                format!("cannot restore query history snapshot: {error}"),
9363                "QueryWorkflowStateUnavailable",
9364            )
9365        })?;
9366        enrich_query_history_from_export(&mut task).map_err(|error| {
9367            QueryTaskExecutionFailure::new(
9368                "query_workflow_state_unavailable",
9369                format!("cannot restore compact query history payloads: {error}"),
9370                "QueryWorkflowStateUnavailable",
9371            )
9372        })?;
9373        let signal_events = query_signal_events(&task).map_err(|error| {
9374            QueryTaskExecutionFailure::new(
9375                "query_workflow_state_unavailable",
9376                format!("cannot decode committed workflow signals: {error}"),
9377                "QueryWorkflowStateUnavailable",
9378            )
9379        })?;
9380        let history_events = Arc::new(std::mem::take(&mut task.history_events));
9381        let context = QueryContext {
9382            workflow_id: task.workflow_id,
9383            run_id: task.run_id,
9384            workflow_type: task.workflow_type.clone(),
9385            run_status: task.run_status,
9386            workflow_input,
9387            workflow_input_avro_value: workflow_input_typed.clone(),
9388            history_events: Arc::clone(&history_events),
9389            signal_events: Arc::new(signal_events),
9390        };
9391
9392        let future = match query {
9393            RegisteredQuery::Snapshot(handler) => {
9394                query_authority::before_handler(authority, &self.client).await?;
9395                handler(context, args)
9396            }
9397            RegisteredQuery::Replayed {
9398                state_type,
9399                handler,
9400            } => {
9401                let workflow = self
9402                    .workflows
9403                    .get(&task.workflow_type)
9404                    .expect("workflow registration was checked above");
9405                if workflow.state_type != Some(*state_type) {
9406                    return Err(QueryTaskExecutionFailure::new(
9407                        "query_workflow_state_unavailable",
9408                        "replayed query state type does not match its workflow registration",
9409                        "QueryWorkflowStateUnavailable",
9410                    ));
9411                }
9412                let replay = workflow.replay.as_ref().ok_or_else(|| {
9413                    QueryTaskExecutionFailure::new(
9414                        "query_workflow_state_unavailable",
9415                        format!(
9416                            "workflow type {:?} is not registered for instance-state replay",
9417                            task.workflow_type
9418                        ),
9419                        "QueryWorkflowStateUnavailable",
9420                    )
9421                })?;
9422                let workflow_state = Arc::new(Mutex::new(
9423                    WorkflowState::new_with_identity(
9424                        history_events.as_ref().clone(),
9425                        context.workflow_id.clone(),
9426                        context.run_id.clone(),
9427                        self.task_queue.clone(),
9428                        task.payload_codec,
9429                        None,
9430                    )
9431                    .map_err(|error| {
9432                        QueryTaskExecutionFailure::new(
9433                            "query_workflow_state_unavailable",
9434                            format!("workflow replay failed before query: {error}"),
9435                            "QueryWorkflowStateUnavailable",
9436                        )
9437                    })?,
9438                ));
9439                let workflow_context = WorkflowContext {
9440                    state: workflow_state,
9441                    cancellation_scope_id: "root".into(),
9442                };
9443                query_authority::before_handler(authority, &self.client).await?;
9444                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone())
9445                    .map_err(|error| {
9446                        QueryTaskExecutionFailure::new(
9447                            "query_workflow_state_unavailable",
9448                            error.to_string(),
9449                            "QueryWorkflowStateUnavailable",
9450                        )
9451                    })?;
9452                let outcome = {
9453                    let mut cx = TaskContext::from_waker(noop_waker_ref());
9454                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
9455                        .map_err(|error| {
9456                            QueryTaskExecutionFailure::new(
9457                                "query_workflow_state_unavailable",
9458                                error.to_string(),
9459                                "QueryWorkflowStateUnavailable",
9460                            )
9461                        })?;
9462                    invocation.future.as_mut().poll(&mut cx)
9463                };
9464                match outcome {
9465                    Poll::Ready(Ok(_)) => {
9466                        workflow_context
9467                            .ensure_history_consumed()
9468                            .map_err(|error| {
9469                                QueryTaskExecutionFailure::new(
9470                                    "query_workflow_state_unavailable",
9471                                    format!("workflow replay failed before query: {error}"),
9472                                    "QueryWorkflowStateUnavailable",
9473                                )
9474                            })?;
9475                    }
9476                    Poll::Ready(Err(error)) => {
9477                        return Err(QueryTaskExecutionFailure::new(
9478                            "query_workflow_state_unavailable",
9479                            format!("workflow replay failed before query: {error}"),
9480                            "QueryWorkflowStateUnavailable",
9481                        ));
9482                    }
9483                    Poll::Pending => {
9484                        let commands = workflow_context.take_commands().map_err(|error| {
9485                            QueryTaskExecutionFailure::new(
9486                                "query_workflow_state_unavailable",
9487                                format!("workflow replay failed before query: {error}"),
9488                                "QueryWorkflowStateUnavailable",
9489                            )
9490                        })?;
9491                        if commands.is_empty()
9492                            && !workflow_context
9493                                .matched_recorded_pending()
9494                                .map_err(|error| {
9495                                    QueryTaskExecutionFailure::new(
9496                                        "query_workflow_state_unavailable",
9497                                        format!("workflow replay failed before query: {error}"),
9498                                        "QueryWorkflowStateUnavailable",
9499                                    )
9500                                })?
9501                        {
9502                            return Err(QueryTaskExecutionFailure::new(
9503                                "query_workflow_state_unavailable",
9504                                "workflow replay yielded without a durable command",
9505                                "QueryWorkflowStateUnavailable",
9506                            ));
9507                        }
9508                    }
9509                }
9510                let state = (invocation.snapshot)().map_err(|error| {
9511                    QueryTaskExecutionFailure::new(
9512                        "query_workflow_state_unavailable",
9513                        format!("cannot snapshot replayed workflow state: {error}"),
9514                        "QueryWorkflowStateUnavailable",
9515                    )
9516                })?;
9517                query_authority::before_handler(authority, &self.client).await?;
9518                handler(context, state, args).map_err(|message| {
9519                    QueryTaskExecutionFailure::new(
9520                        "query_workflow_state_unavailable",
9521                        message,
9522                        "QueryWorkflowStateUnavailable",
9523                    )
9524                })?
9525            }
9526        };
9527
9528        future.await.map_err(|error| {
9529            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
9530        })
9531    }
9532
9533    #[cfg(test)]
9534    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
9535        Ok(self.execute_workflow_task_decision(task)?.commands)
9536    }
9537
9538    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
9539        self.execute_workflow_task_decision_with_cancellation(task, None)
9540    }
9541
9542    fn execute_workflow_task_decision_with_cancellation(
9543        &self,
9544        task: WorkflowTask,
9545        observation: Option<&CancellationRequest>,
9546    ) -> Result<WorkflowTaskDecision> {
9547        #[cfg(feature = "telemetry")]
9548        if let Some(telemetry) = &self.telemetry {
9549            return telemetry.run_sync_observed(
9550                "durable.workflow.task",
9551                self.workflow_telemetry_fields(&task),
9552                self.workflow_observations(&task),
9553                || {
9554                    let mut decision =
9555                        self.execute_workflow_task_decision_inner(task, observation)?;
9556                    self.stamp_observability_commands(&mut decision.commands);
9557                    Ok(decision)
9558                },
9559            );
9560        }
9561        self.execute_workflow_task_decision_inner(task, observation)
9562    }
9563
9564    fn execute_workflow_task_decision_inner(
9565        &self,
9566        task: WorkflowTask,
9567        observation: Option<&CancellationRequest>,
9568    ) -> Result<WorkflowTaskDecision> {
9569        match self.prepare_workflow_task_execution(task, observation)? {
9570            PreparedWorkflowTask::Decision(decision) => Ok(decision),
9571            PreparedWorkflowTask::Execution {
9572                task,
9573                context,
9574                mut future,
9575            } => {
9576                let outcome = Self::poll_workflow_future(&context, &mut future)?;
9577                self.finish_workflow_task_execution(&task, &context, outcome)
9578            }
9579        }
9580    }
9581
9582    fn prepare_workflow_task_execution(
9583        &self,
9584        task: WorkflowTask,
9585        observation: Option<&CancellationRequest>,
9586    ) -> Result<PreparedWorkflowTask> {
9587        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
9588            && !self.cooperative_cancellation_enabled
9589        {
9590            return Err(Error::CancellationScopeExecutionUnavailable);
9591        }
9592        validate_workflow_task_payloads(&task)?;
9593        cooperative_cancellation::assert_cancellation_scope_replay_supported(
9594            &task.history_events,
9595            self.allow_cancellation_scope_authoring,
9596            self.allow_cancellation_scope_delivery,
9597        )?;
9598        let cancellation_history = if let Some(observation) = observation {
9599            observation.validate_observation()?;
9600            cooperative_cancellation::cancellation_claim(&task)?;
9601            let canonical = CancellationHistory::from_events(
9602                &task.history_events,
9603                task.run_id.as_deref().unwrap_or_default(),
9604                Some(observation),
9605            )?;
9606            if canonical.request_index >= task.history_events.len() {
9607                return Err(Error::InvalidCooperativeCancellation(
9608                    "workflow replay requires the observed canonical request".into(),
9609                ));
9610            }
9611            Some(canonical)
9612        } else {
9613            None
9614        };
9615        if let Some(update_id) = task
9616            .workflow_update_id
9617            .as_deref()
9618            .filter(|update_id| !update_id.is_empty())
9619        {
9620            if self.allow_cancellation_scope_delivery {
9621                return Err(Error::CancellationScopeExecutionUnavailable);
9622            }
9623            CancellationHistory::from_events(
9624                &task.history_events,
9625                task.run_id.as_deref().unwrap_or_default(),
9626                None,
9627            )?;
9628            return self
9629                .execute_update_task(&task, update_id)
9630                .map(WorkflowTaskDecision::without_message_streams)
9631                .map(PreparedWorkflowTask::Decision);
9632        }
9633
9634        let workflow = self
9635            .workflows
9636            .get(&task.workflow_type)
9637            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
9638        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9639        let resume_signal = decode_resume_signal(&task)?;
9640        let history_budget = WorkflowHistoryBudget {
9641            event_count: task
9642                .total_history_events
9643                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
9644            size_bytes: task.history_size_bytes,
9645            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
9646            pressure: task.history_budget_pressure.clone(),
9647        };
9648        let workflow_command_identity = task
9649            .workflow_command_id
9650            .clone()
9651            .filter(|identity| !identity.is_empty())
9652            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
9653            .unwrap_or_default();
9654        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
9655            task.history_events.clone(),
9656            task.workflow_id.clone(),
9657            task.run_id.clone(),
9658            self.task_queue.clone(),
9659            task.payload_codec.clone(),
9660            resume_signal,
9661            self.allow_cancellation_scope_authoring,
9662            self.allow_cancellation_scope_delivery,
9663        )?;
9664        workflow_state.history_budget = history_budget;
9665        workflow_state.workflow_command_identity = workflow_command_identity;
9666        if let Some(canonical) = cancellation_history {
9667            workflow_state.cancellation_history = canonical;
9668            workflow_state.cancellation_delivery_enabled = true;
9669        }
9670        if workflow_state.cancellation_history.request.is_none() {
9671            workflow_state.cancel_requested = task.cancel_requested;
9672        }
9673        let state = Arc::new(Mutex::new(workflow_state));
9674        let ctx = WorkflowContext {
9675            state,
9676            cancellation_scope_id: "root".into(),
9677        };
9678        let future = (workflow.execute)(ctx.clone(), input)?;
9679        Ok(PreparedWorkflowTask::Execution {
9680            task,
9681            context: ctx,
9682            future,
9683        })
9684    }
9685
9686    fn poll_workflow_future(
9687        ctx: &WorkflowContext,
9688        future: &mut WorkflowFuture,
9689    ) -> Result<Poll<Result<AvroValue>>> {
9690        let mut cx = TaskContext::from_waker(noop_waker_ref());
9691        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9692        Ok(future.as_mut().poll(&mut cx))
9693    }
9694
9695    fn finish_workflow_task_execution(
9696        &self,
9697        task: &WorkflowTask,
9698        ctx: &WorkflowContext,
9699        outcome: Poll<Result<AvroValue>>,
9700    ) -> Result<WorkflowTaskDecision> {
9701        if !ctx
9702            .state
9703            .lock()
9704            .map_err(|_| Error::WorkflowStatePoisoned)?
9705            .local_activity_requests
9706            .is_empty()
9707        {
9708            return Err(Error::CooperativeCancellationUnavailable(
9709                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9710            ));
9711        }
9712        let awaiting_canonical_boundary = {
9713            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9714            state.cancellation_delivery_intent.is_some()
9715                || state.cancellation_scope_opening.is_some()
9716                || state
9717                    .scope_delivery
9718                    .as_ref()
9719                    .is_some_and(|replay| replay.intent.is_some())
9720        };
9721        if awaiting_canonical_boundary {
9722            // A private delivery intent never becomes an application error.
9723            // Even a custom future which ignores a pending durable call cannot
9724            // publish terminal commands before canonical delivery and replay.
9725            if let Poll::Ready(Err(error)) = outcome {
9726                if workflow_task_integrity_error(&error) {
9727                    return Err(error);
9728                }
9729            }
9730            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9731        }
9732
9733        match outcome {
9734            Poll::Ready(Ok(result)) => {
9735                ctx.ensure_history_consumed()?;
9736                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9737                let mut commands = ctx.take_commands()?;
9738                commands.push(json!({
9739                    "type": "complete_workflow",
9740                    "result": result
9741                }));
9742                self.message_stream_decision(&ctx, commands)
9743            }
9744            Poll::Ready(Err(error)) => {
9745                if let Error::ContinueAsNew(request) = error {
9746                    let mut commands = ctx.take_commands()?;
9747                    if let Some(command) = ctx.continue_as_new_command(request)? {
9748                        commands.push(command);
9749                    }
9750                    ctx.ensure_history_consumed()?;
9751                    return self.message_stream_decision(&ctx, commands);
9752                }
9753                if workflow_task_integrity_error(&error) {
9754                    // Replay and protocol failures describe the workflow-task
9755                    // decision itself. Preserve their specific failure reason
9756                    // instead of replacing it with the derivative fact that
9757                    // recorded commands remain unconsumed.
9758                    return Err(error);
9759                }
9760                // A handler error must not hide a committed durable command that
9761                // upgraded workflow code no longer consumes.
9762                ctx.ensure_history_consumed()?;
9763                let mut commands = ctx.take_commands()?;
9764                commands.push(workflow_failure_command(
9765                    &error,
9766                    recorded_activity_failure_boundary(&ctx, &error),
9767                ));
9768                self.message_stream_decision(&ctx, commands)
9769            }
9770            Poll::Pending => {
9771                let commands = ctx.take_commands()?;
9772                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9773                    Err(Error::WorkflowYieldedWithoutCommand)
9774                } else {
9775                    self.message_stream_decision(&ctx, commands)
9776                }
9777            }
9778        }
9779    }
9780
9781    fn message_stream_decision(
9782        &self,
9783        ctx: &WorkflowContext,
9784        commands: Vec<Value>,
9785    ) -> Result<WorkflowTaskDecision> {
9786        if !self.cooperative_cancellation_enabled
9787            && commands.iter().any(|command| {
9788                command["type"] == "schedule_activity"
9789                    && command.get("cancellation_policy").is_some()
9790            })
9791        {
9792            return Err(Error::CooperativeCancellationUnavailable(format!(
9793                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9794                self.worker_id,
9795            )));
9796        }
9797        if !self.cooperative_cancellation_enabled
9798            && commands.iter().any(|command| {
9799                command["type"] == "start_child_workflow"
9800                    && (command["parent_close_policy"] == "request_cancellation"
9801                        || matches!(
9802                            command["cancellation_policy"].as_str(),
9803                            Some("try_cancel" | "wait_cancellation_completed")
9804                        ))
9805            })
9806        {
9807            return Err(Error::CooperativeCancellationUnavailable(format!(
9808                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9809                self.worker_id,
9810            )));
9811        }
9812        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9813        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9814        let scope_delivery = state
9815            .scope_delivery
9816            .as_ref()
9817            .and_then(|replay| replay.intent.clone());
9818        if scope_delivery
9819            .as_ref()
9820            .is_some_and(|intent| commands.len() != intent.command_count)
9821        {
9822            return Err(invalid_recorded_history(
9823                "cancellation_scope_pending_call_escaped",
9824                scope_delivery.as_ref().unwrap().boundary.sequence,
9825                "commands preceding the pending scoped call",
9826                "commands after suspension",
9827                "workflow cannot publish beyond an uncommitted scope delivery",
9828            ));
9829        }
9830        if let Some(opening) = &state.cancellation_scope_opening {
9831            if commands.len() != opening.command_count {
9832                return Err(invalid_recorded_history(
9833                    "cancellation_scope_pending_call_escaped",
9834                    opening.sequence,
9835                    "commands before original scope opening",
9836                    "commands after suspended opening",
9837                    "workflow cannot publish beyond an uncommitted scope opening",
9838                ));
9839            }
9840        }
9841        if state.cancellation_delivery_intent.is_some()
9842            && commands.len() != state.cancellation_delivery_command_count
9843        {
9844            return Err(invalid_recorded_history(
9845                "cooperative_cancellation_pending_call_escaped",
9846                state
9847                    .cancellation_delivery_intent
9848                    .as_ref()
9849                    .expect("pending delivery")
9850                    .sequence,
9851                "only commands preceding the pending cancellation call",
9852                "commands authored after a suspended call",
9853                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9854            ));
9855        }
9856        Ok(WorkflowTaskDecision {
9857            commands,
9858            message_stream_cursors,
9859            message_stream_waits,
9860            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9861            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9862            cancellation_scope_delivery: scope_delivery,
9863        })
9864    }
9865
9866    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9867        if !self.workflows.contains_key(&task.workflow_type) {
9868            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9869        }
9870
9871        let accepted = task.history_events.iter().rev().find_map(|event| {
9872            (event.event_type == "UpdateAccepted"
9873                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9874            .then_some(&event.payload)
9875        });
9876        let update_name = accepted
9877            .and_then(|payload| payload.get("update_name"))
9878            .and_then(Value::as_str)
9879            .or(task.update_name.as_deref())
9880            .unwrap_or_default();
9881        let Some(handler) = self
9882            .updates
9883            .get(&task.workflow_type)
9884            .and_then(|handlers| handlers.get(update_name))
9885        else {
9886            return Ok(vec![json!({
9887                "type": "fail_update",
9888                "update_id": update_id,
9889                "message": format!(
9890                    "no update handler is registered for {}.{update_name}",
9891                    task.workflow_type
9892                ),
9893                "exception_type": "UnknownUpdate",
9894                "non_retryable": true,
9895            })]);
9896        };
9897        let arguments = accepted
9898            .and_then(|payload| payload.get("arguments"))
9899            .or(task.arguments.as_ref());
9900        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9901        let workflow_input_avro_value =
9902            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9903        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9904        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9905        let context = QueryContext {
9906            workflow_id: task.workflow_id.clone(),
9907            run_id: task.run_id.clone(),
9908            workflow_type: task.workflow_type.clone(),
9909            run_status: Some("running".to_string()),
9910            workflow_input,
9911            workflow_input_avro_value,
9912            history_events: Arc::new(task.history_events.clone()),
9913            signal_events: Arc::new(signal_events),
9914        };
9915        let mut future = handler(context, arguments);
9916        let mut cx = TaskContext::from_waker(noop_waker_ref());
9917
9918        match future.as_mut().poll(&mut cx) {
9919            Poll::Ready(Ok(result)) => Ok(vec![json!({
9920                "type": "complete_update",
9921                "update_id": update_id,
9922                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9923            })]),
9924            Poll::Ready(Err(error)) => Ok(vec![json!({
9925                "type": "fail_update",
9926                "update_id": update_id,
9927                "message": error.to_string(),
9928                "exception_type": "UpdateFailed",
9929                "non_retryable": true,
9930            })]),
9931            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9932        }
9933    }
9934
9935    #[cfg(test)]
9936    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9937        self.execute_session_activity_task(task, None, None).await
9938    }
9939
9940    async fn execute_session_activity_task(
9941        &self,
9942        task: ActivityTask,
9943        worker_session: Option<WorkerSession>,
9944        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9945    ) -> Result<AvroValue> {
9946        #[cfg(feature = "telemetry")]
9947        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
9948            !self
9949                .client
9950                .observability_context_supported
9951                .load(Ordering::SeqCst)
9952        }) {
9953            return telemetry
9954                .run(
9955                    "durable.activity.task",
9956                    self.activity_telemetry_fields(&task),
9957                    false,
9958                    self.execute_session_activity_task_inner(task, worker_session, hydration_claim),
9959                )
9960                .await;
9961        }
9962        self.execute_session_activity_task_inner(task, worker_session, hydration_claim)
9963            .await
9964    }
9965
9966    async fn execute_session_activity_task_inner(
9967        &self,
9968        task: ActivityTask,
9969        worker_session: Option<WorkerSession>,
9970        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9971    ) -> Result<AvroValue> {
9972        validate_activity_task_payloads(&task)?;
9973        if worker_session.is_some() {
9974            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9975                || task
9976                    .activity_attempt_id
9977                    .as_deref()
9978                    .or(task.attempt_id.as_deref())
9979                    .is_none_or(str::is_empty)
9980                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9981            {
9982                return Err(Error::ActivityExecutionAbandoned(
9983                    "session activity requires this worker's exact immutable claim".into(),
9984                ));
9985            }
9986        }
9987
9988        let handler = self
9989            .activities
9990            .get(&task.activity_type)
9991            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9992        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9993        let attempt_id = task
9994            .activity_attempt_id
9995            .clone()
9996            .or(task.attempt_id.clone())
9997            .unwrap_or_default();
9998        let lease_owner = task
9999            .lease_owner
10000            .clone()
10001            .unwrap_or_else(|| self.worker_id.clone());
10002        let session = worker_session.clone();
10003        if let Some(claim) = hydration_claim {
10004            claim.confirm(&self.client).await?;
10005        }
10006        #[cfg(feature = "telemetry")]
10007        let observations = self.activity_observations(&task);
10008        #[cfg(feature = "telemetry")]
10009        let fields = self.activity_telemetry_fields(&task);
10010        let ctx = ActivityContext {
10011            client: self.client.clone(),
10012            task_id: task.task_id,
10013            activity_attempt_id: attempt_id,
10014            lease_owner,
10015            activity_type: task.activity_type,
10016            attempt_number: task.attempt_number,
10017            task_queue: self.task_queue.clone(),
10018            worker_id: self.worker_id.clone(),
10019            claim_guard: None,
10020            local_heartbeats: None,
10021            worker_session,
10022        };
10023
10024        let operation = async {
10025            let callback = self.activity_callback(handler, ctx, args, false);
10026            if let Some(session) = session {
10027                tokio::select! {
10028                    biased;
10029                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10030                    result = callback => if session.active() { result } else {
10031                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10032                    },
10033                }
10034            } else {
10035                callback.await
10036            }
10037        };
10038        #[cfg(feature = "telemetry")]
10039        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10040            self.client
10041                .observability_context_supported
10042                .load(Ordering::SeqCst)
10043        }) {
10044            return telemetry
10045                .run_observed(
10046                    "durable.activity.task",
10047                    fields,
10048                    false,
10049                    observations,
10050                    operation,
10051                )
10052                .await;
10053        }
10054        operation.await
10055    }
10056
10057    fn activity_callback(
10058        &self,
10059        handler: &ActivityHandler,
10060        context: ActivityContext,
10061        args: AvroValue,
10062        local: bool,
10063    ) -> ActivityFuture {
10064        #[cfg(feature = "telemetry")]
10065        if let Some(telemetry) = &self.telemetry {
10066            let telemetry = telemetry.clone();
10067            let fields = self.callback_telemetry_fields(&context, local);
10068            let handler = handler.clone();
10069            let name = if local {
10070                "durable.local_activity.attempt"
10071            } else {
10072                "durable.activity.attempt"
10073            };
10074            return Box::pin(async move {
10075                telemetry
10076                    .run(
10077                        name,
10078                        fields,
10079                        true,
10080                        async move { handler(context, args).await },
10081                    )
10082                    .await
10083            });
10084        }
10085        #[cfg(not(feature = "telemetry"))]
10086        let _ = local;
10087        handler(context, args)
10088    }
10089}
10090
10091fn poller_result(
10092    kind: &str,
10093    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10094) -> Result<()> {
10095    match result {
10096        Ok(result) => result,
10097        Err(error) => Err(Error::WorkerLoop(format!(
10098            "{kind} poller join error: {error}"
10099        ))),
10100    }
10101}
10102
10103fn optional_poller_result(
10104    kind: &str,
10105    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10106) -> Result<()> {
10107    match result {
10108        Some(result) => poller_result(kind, result),
10109        None => Ok(()),
10110    }
10111}
10112
10113async fn join_pollers(
10114    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10115    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10116    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10117) -> Result<()> {
10118    let mut first_error = None;
10119
10120    if let Some(handle) = workflow_poller {
10121        if let Err(error) = poller_result("workflow", handle.await) {
10122            first_error.get_or_insert(error);
10123        }
10124    }
10125
10126    if let Some(handle) = activity_poller {
10127        if let Err(error) = poller_result("activity", handle.await) {
10128            first_error.get_or_insert(error);
10129        }
10130    }
10131
10132    if let Some(handle) = query_poller {
10133        if let Err(error) = poller_result("query", handle.await) {
10134            first_error.get_or_insert(error);
10135        }
10136    }
10137
10138    if let Some(error) = first_error {
10139        Err(error)
10140    } else {
10141        Ok(())
10142    }
10143}
10144
10145fn default_worker_id() -> String {
10146    let millis = SystemTime::now()
10147        .duration_since(UNIX_EPOCH)
10148        .unwrap_or_default()
10149        .as_millis();
10150    format!("rust-worker-{}-{millis}", std::process::id())
10151}
10152
10153fn percent_encode_path_segment(segment: &str) -> String {
10154    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10155    let mut encoded = String::with_capacity(segment.len());
10156
10157    for byte in segment.bytes() {
10158        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10159            encoded.push(char::from(byte));
10160        } else {
10161            encoded.push('%');
10162            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10163            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10164        }
10165    }
10166
10167    encoded
10168}
10169
10170fn unique_request_id(prefix: &str) -> String {
10171    let nanos = SystemTime::now()
10172        .duration_since(UNIX_EPOCH)
10173        .unwrap_or_default()
10174        .as_nanos();
10175    format!("{prefix}-{}-{nanos}", std::process::id())
10176}
10177
10178#[derive(Debug)]
10179struct QueryTaskExecutionFailure {
10180    reason: String,
10181    message: String,
10182    failure_type: String,
10183}
10184
10185impl QueryTaskExecutionFailure {
10186    fn new(
10187        reason: impl Into<String>,
10188        message: impl Into<String>,
10189        failure_type: impl Into<String>,
10190    ) -> Self {
10191        Self {
10192            reason: reason.into(),
10193            message: message.into(),
10194            failure_type: failure_type.into(),
10195        }
10196    }
10197}
10198
10199/// Typed local state owned by one deterministic workflow invocation.
10200///
10201/// Use [`WorkflowInstance::update`] for the same state transitions during
10202/// ordinary execution and replay. A replayed query receives a detached
10203/// immutable `Arc<S>` rather than this mutation-capable handle.
10204#[derive(Clone, Debug)]
10205pub struct WorkflowInstance<S> {
10206    state: Arc<Mutex<S>>,
10207}
10208
10209impl<S> WorkflowInstance<S> {
10210    fn new(state: S) -> Self {
10211        Self {
10212            state: Arc::new(Mutex::new(state)),
10213        }
10214    }
10215
10216    /// Read the current workflow-instance state without changing it.
10217    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10218        let state = self
10219            .state
10220            .lock()
10221            .map_err(|_| Error::WorkflowStatePoisoned)?;
10222        Ok(reader(&state))
10223    }
10224
10225    /// Apply one deterministic workflow-instance state transition.
10226    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10227        let mut state = self
10228            .state
10229            .lock()
10230            .map_err(|_| Error::WorkflowStatePoisoned)?;
10231        Ok(transition(&mut state))
10232    }
10233}
10234
10235impl<S: Clone> WorkflowInstance<S> {
10236    fn snapshot(&self) -> Result<S> {
10237        self.read(Clone::clone)
10238    }
10239}
10240
10241#[derive(Clone, Debug, PartialEq)]
10242pub struct MessageStreamMessage {
10243    pub stream_name: String,
10244    pub message_id: String,
10245    pub position: u64,
10246    pub arguments: Vec<AvroValue>,
10247}
10248
10249#[derive(Clone, Debug)]
10250pub struct MessageStream {
10251    ctx: WorkflowContext,
10252    name: String,
10253}
10254
10255impl MessageStream {
10256    /// Wait for one message, then return a bounded currently-available batch.
10257    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10258        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10259            return Err(Error::Codec(format!(
10260                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10261            )));
10262        }
10263        loop {
10264            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10265                return Ok(batch);
10266            }
10267
10268            self.ctx.record_message_stream_wait(&self.name)?;
10269            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10270            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10271            self.ctx.buffer_message_stream_delivery(arguments)?;
10272            if let Some(sequence) = replay_wait_sequence {
10273                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10274            }
10275        }
10276    }
10277
10278    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10279        self.receive(1)
10280            .await?
10281            .into_iter()
10282            .next()
10283            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10284    }
10285}
10286
10287#[derive(Clone, Debug)]
10288pub struct WorkflowContext {
10289    state: Arc<Mutex<WorkflowState>>,
10290    cancellation_scope_id: String,
10291}
10292
10293fn valid_memo_key(key: &str) -> bool {
10294    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10295
10296    !key.is_empty()
10297        && key.len() <= 64
10298        && (numeric_candidate.is_empty()
10299            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10300        && key
10301            .bytes()
10302            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10303}
10304
10305fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10306    BASE64
10307        .decode(encode_avro_value(value)?.blob)
10308        .map(|bytes| bytes.len())
10309        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10310}
10311
10312fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10313    let AvroValue::Map(entries) = value else {
10314        return Err(Error::InvalidMemoUpdate(
10315            "entries must serialize to an Avro string-keyed map".to_string(),
10316        ));
10317    };
10318    if require_entries && entries.is_empty() {
10319        return Err(Error::InvalidMemoUpdate(
10320            "at least one entry is required".to_string(),
10321        ));
10322    }
10323    if entries.len() > MAX_MEMO_ENTRIES {
10324        return Err(Error::InvalidMemoUpdate(format!(
10325            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10326        )));
10327    }
10328
10329    for (key, value) in &entries {
10330        if !valid_memo_key(&key) {
10331            return Err(Error::InvalidMemoUpdate(
10332                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10333            ));
10334        }
10335        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10336            return Err(Error::InvalidMemoUpdate(format!(
10337                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10338            )));
10339        }
10340    }
10341
10342    let value = AvroValue::Map(entries);
10343    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10344        return Err(Error::InvalidMemoUpdate(format!(
10345            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10346        )));
10347    }
10348    Ok(value)
10349}
10350
10351fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10352    let object = envelope.as_object().ok_or_else(|| {
10353        Error::InvalidMemoUpdate(
10354            "history field must use the public {codec, blob} payload envelope".to_string(),
10355        )
10356    })?;
10357    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10358        return Err(Error::InvalidMemoUpdate(
10359            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10360        ));
10361    }
10362
10363    canonical_memo_entries(
10364        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10365        require_entries,
10366    )
10367}
10368
10369impl WorkflowContext {
10370    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10371        let name = name.into();
10372        if name.is_empty()
10373            || name.len() > 128
10374            || !name.bytes().all(|byte| {
10375                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10376            })
10377        {
10378            return Err(Error::Codec(
10379                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10380                    .to_string(),
10381            ));
10382        }
10383        Ok(MessageStream {
10384            ctx: self.clone(),
10385            name,
10386        })
10387    }
10388
10389    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10390        let mut state = self
10391            .state
10392            .lock()
10393            .map_err(|_| Error::WorkflowStatePoisoned)?;
10394        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10395        state
10396            .message_stream_waits
10397            .insert(name.to_string(), position);
10398        Ok(())
10399    }
10400
10401    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
10402        let mut state = self
10403            .state
10404            .lock()
10405            .map_err(|_| Error::WorkflowStatePoisoned)?;
10406        let cursor = state
10407            .message_stream_cursors
10408            .get(&message.stream_name)
10409            .copied()
10410            .unwrap_or(0);
10411        if message.position <= cursor {
10412            return Ok(());
10413        }
10414        let pending = state
10415            .message_stream_messages
10416            .entry(message.stream_name.clone())
10417            .or_default();
10418        if pending.iter().any(|candidate| {
10419            candidate.position == message.position || candidate.message_id == message.message_id
10420        }) {
10421            return Ok(());
10422        }
10423        pending.push(message);
10424        pending.sort_by_key(|candidate| candidate.position);
10425        Ok(())
10426    }
10427
10428    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
10429        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
10430            match delivery {
10431                MessageStreamDelivery::Message(message) => {
10432                    let stream_name = message.stream_name.clone();
10433                    self.buffer_message_stream(message)?;
10434                    return Ok(Some(stream_name));
10435                }
10436                MessageStreamDelivery::Cursor {
10437                    stream_name,
10438                    through_position,
10439                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
10440            }
10441        }
10442        Ok(None)
10443    }
10444
10445    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
10446        let state = self
10447            .state
10448            .lock()
10449            .map_err(|_| Error::WorkflowStatePoisoned)?;
10450        Ok(match state.recorded_commands.get(state.command_cursor) {
10451            Some(RecordedCommand::SignalWait {
10452                sequence,
10453                signal_name,
10454                ..
10455            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
10456            _ => None,
10457        })
10458    }
10459
10460    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
10461        let (history, payload_codec) = {
10462            let state = self
10463                .state
10464                .lock()
10465                .map_err(|_| Error::WorkflowStatePoisoned)?;
10466            (
10467                Arc::clone(&state.history_events),
10468                state.payload_codec.clone(),
10469            )
10470        };
10471
10472        let Some(opened_index) = history.iter().position(|event| {
10473            event.event_type == "SignalWaitOpened"
10474                && durable_event_sequence(event) == Some(wait_sequence)
10475                && event.payload.get("signal_name").and_then(Value::as_str)
10476                    == Some(MESSAGE_STREAM_SIGNAL)
10477        }) else {
10478            return Ok(());
10479        };
10480        let boundary_index = history
10481            .iter()
10482            .enumerate()
10483            .skip(opened_index + 1)
10484            .find_map(|(index, event)| {
10485                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
10486                    && is_authored_command_open_event(event))
10487                .then_some(index)
10488            })
10489            .unwrap_or(history.len());
10490
10491        for event in history[opened_index + 1..boundary_index]
10492            .iter()
10493            .filter(|event| {
10494                event.event_type == "SignalReceived"
10495                    && event.payload.get("signal_name").and_then(Value::as_str)
10496                        == Some(MESSAGE_STREAM_SIGNAL)
10497            })
10498        {
10499            let arguments = decode_signal_event_arguments(event, &payload_codec)?
10500                .into_iter()
10501                .map(AvroValue::into_json)
10502                .collect::<Result<Vec<_>>>()?;
10503            self.buffer_message_stream_delivery(arguments)?;
10504        }
10505        Ok(())
10506    }
10507
10508    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
10509        let mut state = self
10510            .state
10511            .lock()
10512            .map_err(|_| Error::WorkflowStatePoisoned)?;
10513        let cursor = state
10514            .message_stream_cursors
10515            .entry(name.to_string())
10516            .or_default();
10517        *cursor = (*cursor).max(through_position);
10518        if let Some(pending) = state.message_stream_messages.get_mut(name) {
10519            pending.retain(|message| message.position > through_position);
10520        }
10521        Ok(())
10522    }
10523
10524    fn take_message_stream_batch(
10525        &self,
10526        name: &str,
10527        max_items: usize,
10528    ) -> Result<Option<Vec<MessageStreamMessage>>> {
10529        let mut state = self
10530            .state
10531            .lock()
10532            .map_err(|_| Error::WorkflowStatePoisoned)?;
10533        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10534        let pending = state
10535            .message_stream_messages
10536            .entry(name.to_string())
10537            .or_default();
10538        let count = contiguous_message_stream_count(pending, cursor, max_items);
10539        if count == 0 {
10540            return Ok(None);
10541        }
10542        let batch = pending.drain(..count).collect::<Vec<_>>();
10543        let position = batch.last().map(|message| message.position).unwrap_or(0);
10544        state
10545            .message_stream_cursors
10546            .insert(name.to_string(), position);
10547        state.message_stream_waits.remove(name);
10548        Ok(Some(batch))
10549    }
10550
10551    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
10552        let state = self
10553            .state
10554            .lock()
10555            .map_err(|_| Error::WorkflowStatePoisoned)?;
10556        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
10557        cursors.sort_by_key(|(name, _)| *name);
10558        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
10559        waits.sort_by_key(|(name, _)| *name);
10560        Ok((
10561            cursors
10562                .into_iter()
10563                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
10564                .collect(),
10565            waits
10566                .into_iter()
10567                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
10568                .collect(),
10569        ))
10570    }
10571    /// Identity of the parent workflow currently being replayed.
10572    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
10573        let state = self
10574            .state
10575            .lock()
10576            .map_err(|_| Error::WorkflowStatePoisoned)?;
10577        Ok(WorkflowIdentity {
10578            workflow_id: state.workflow_id.clone(),
10579            run_id: state.run_id.clone(),
10580        })
10581    }
10582
10583    /// Return the server-published history budget for this workflow task.
10584    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
10585        let state = self
10586            .state
10587            .lock()
10588            .map_err(|_| Error::WorkflowStatePoisoned)?;
10589        Ok(state.history_budget.clone())
10590    }
10591
10592    /// Continue this workflow instance as a fresh run with replacement arguments.
10593    ///
10594    /// Return this value directly from the workflow handler. The worker converts
10595    /// it to the terminal protocol command only after replay has consumed every
10596    /// recorded durable command.
10597    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
10598        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
10599    }
10600
10601    /// Continue as new with optional workflow-type and task-queue overrides.
10602    pub fn continue_as_new_with_options<T: Serialize>(
10603        &self,
10604        options: ContinueAsNewOptions,
10605        args: T,
10606    ) -> Result<Value> {
10607        options.validate()?;
10608        Err(Error::ContinueAsNew(ContinueAsNewRequest {
10609            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
10610            options,
10611        }))
10612    }
10613
10614    pub fn activity<T: Serialize>(
10615        &self,
10616        activity_type: impl Into<String>,
10617        args: T,
10618    ) -> ActivityCall {
10619        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10620    }
10621
10622    pub fn activity_on_queue<T, Q>(
10623        &self,
10624        activity_type: impl Into<String>,
10625        task_queue: Option<Q>,
10626        args: T,
10627    ) -> ActivityCall
10628    where
10629        T: Serialize,
10630        Q: Into<String>,
10631    {
10632        let mut options = ActivityOptions::new();
10633        options.task_queue = task_queue.map(Into::into);
10634        self.activity_with_options(activity_type, options, args)
10635    }
10636
10637    /// Schedule one durable activity with retry, routing, and timeout options.
10638    ///
10639    /// Options are validated before the command is emitted. Once the command is
10640    /// recorded, replay consumes the same activity lifecycle at this command
10641    /// position and never emits a duplicate schedule.
10642    ///
10643    /// ```no_run
10644    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10645    /// # use std::time::Duration;
10646    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10647    /// let result = ctx
10648    ///     .activity_with_options(
10649    ///         "charge-card",
10650    ///         ActivityOptions::new()
10651    ///             .task_queue("payments")
10652    ///             .retry_policy(
10653    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10654    ///                     Duration::from_secs(1),
10655    ///                     2,
10656    ///                     Some(Duration::from_secs(30)),
10657    ///                 ),
10658    ///             )
10659    ///             .start_to_close_timeout(Duration::from_secs(60))
10660    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10661    ///             .heartbeat_timeout(Duration::from_secs(15)),
10662    ///         json!([{"order_id": "order-42"}]),
10663    ///     )
10664    ///     .await;
10665    /// match result {
10666    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10667    ///         "reason": failure.reason,
10668    ///         "timeout_kind": failure.timeout_kind,
10669    ///     })),
10670    ///     other => other,
10671    /// }
10672    /// # }
10673    /// ```
10674    pub fn activity_with_options<T: Serialize>(
10675        &self,
10676        activity_type: impl Into<String>,
10677        options: ActivityOptions,
10678        args: T,
10679    ) -> ActivityCall {
10680        ActivityCall {
10681            ctx: self.clone(),
10682            activity_type: activity_type.into(),
10683            options,
10684            worker_session: None,
10685            args: Some(AvroValue::from_serialize(&args)),
10686            scheduled: false,
10687            local: false,
10688            local_result: None,
10689            parallel_group_path: Vec::new(),
10690        }
10691    }
10692
10693    pub async fn activity_avro_value<T: Serialize>(
10694        &self,
10695        activity_type: impl Into<String>,
10696        args: T,
10697    ) -> Result<AvroValue> {
10698        let mut call = self.activity(activity_type, args);
10699        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10700    }
10701
10702    pub async fn activity_avro_value_with_options<T: Serialize>(
10703        &self,
10704        activity_type: impl Into<String>,
10705        options: ActivityOptions,
10706        args: T,
10707    ) -> Result<AvroValue> {
10708        let mut call = self.activity_with_options(activity_type, options, args);
10709        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10710    }
10711
10712    /// Schedule an activity with a Serde request and decode its Serde result.
10713    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10714    where
10715        I: Serialize,
10716        O: DeserializeOwned,
10717    {
10718        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10719            .await
10720    }
10721
10722    /// Schedule an activity with options and decode its result into `O`.
10723    ///
10724    /// Both directions use the fixed Avro Value codec. In particular, this
10725    /// method does not deserialize the JSON-safe inspection projection returned
10726    /// by the dynamic [`ActivityCall`] future.
10727    pub async fn activity_typed_with_options<I, O>(
10728        &self,
10729        activity_type: impl Into<String>,
10730        options: ActivityOptions,
10731        args: I,
10732    ) -> Result<O>
10733    where
10734        I: Serialize,
10735        O: DeserializeOwned,
10736    {
10737        let activity_type = activity_type.into();
10738        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10739            handler_type_error::<I>(
10740                HandlerKind::Activity,
10741                &activity_type,
10742                HandlerValueKind::Input,
10743                error.to_string(),
10744            )
10745        });
10746        let mut call = ActivityCall {
10747            ctx: self.clone(),
10748            activity_type: activity_type.clone(),
10749            options,
10750            worker_session: None,
10751            args: Some(encoded),
10752            scheduled: false,
10753            local: false,
10754            local_result: None,
10755            parallel_group_path: Vec::new(),
10756        };
10757        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10758        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10759    }
10760
10761    /// Schedule and join a deterministic activity/child/timer group.
10762    ///
10763    /// Nested groups retain their input shape. Every durable leaf is scheduled
10764    /// before this future yields, results are assembled by declaration order,
10765    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10766    /// declaration path, stable group metadata, and completed siblings.
10767    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10768        ParallelCall::new(self.clone(), operations)
10769    }
10770
10771    /// Alias for [`WorkflowContext::parallel`].
10772    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10773        self.parallel(operations)
10774    }
10775
10776    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10777    pub async fn parallel_avro_value(
10778        &self,
10779        operations: Vec<ParallelOperation>,
10780    ) -> Result<Vec<ParallelAvroResult>> {
10781        let mut call = self.parallel(operations);
10782        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10783    }
10784
10785    /// Start every durable operation and resume from the one winner persisted
10786    /// by Server. Non-winning operations continue and remain addressable.
10787    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10788        let operations = operations
10789            .into_iter()
10790            .enumerate()
10791            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10792            .collect();
10793        SelectCall::new(self.clone(), operations)
10794    }
10795
10796    /// Named-key variant of [`WorkflowContext::select`].
10797    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10798    where
10799        K: Into<SelectionKey>,
10800    {
10801        SelectCall::new(
10802            self.clone(),
10803            operations
10804                .into_iter()
10805                .map(|(key, operation)| (key.into(), operation))
10806                .collect(),
10807        )
10808    }
10809
10810    /// Create a workflow-local deterministic compensation registry.
10811    pub fn saga(&self) -> Saga {
10812        Saga::new(self.clone())
10813    }
10814
10815    /// Whether cancellation has reached this replay's authored boundary.
10816    ///
10817    /// Server's current `/cancel` route is terminal and does not set this flag.
10818    /// A canonical service request remains pending until its committed delivery
10819    /// is consumed. Request observation alone does not authorize an exception.
10820    pub fn is_cancellation_requested(&self) -> Result<bool> {
10821        let state = self
10822            .state
10823            .lock()
10824            .map_err(|_| Error::WorkflowStatePoisoned)?;
10825        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10826            return Ok(state
10827                .scope_delivery
10828                .as_ref()
10829                .unwrap()
10830                .contexts
10831                .contains_key(&self.cancellation_scope_id));
10832        }
10833        Ok(state.cancel_requested
10834            || state
10835                .scope_delivery
10836                .as_ref()
10837                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10838    }
10839
10840    /// Raise a typed cooperative cancellation at an author-controlled point.
10841    ///
10842    /// Passing this result to [`Saga::finish`] compensates already registered
10843    /// forward steps before the cancellation remains the initiating outcome.
10844    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10845        let mut state = self
10846            .state
10847            .lock()
10848            .map_err(|_| Error::WorkflowStatePoisoned)?;
10849        if state.cancellation_shield_depth == 0 {
10850            if let Some(replay) = &state.scope_delivery {
10851                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10852                    let delivered = replay
10853                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10854                        .ok_or_else(|| {
10855                            Error::InvalidCooperativeCancellation(
10856                                "scoped request lacks its consumed original delivery".into(),
10857                            )
10858                        })?;
10859                    return Err(Error::CancellationScopeRequested(
10860                        CancellationScopeRequested {
10861                            context: context
10862                                .clone()
10863                                .with_replay(Some(Arc::downgrade(&self.state))),
10864                            delivery: delivered.boundary.clone(),
10865                        },
10866                    ));
10867                }
10868            }
10869        }
10870        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10871            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10872                return Ok(());
10873            }
10874            return Err(state.cancellation_error());
10875        }
10876        Ok(())
10877    }
10878
10879    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10880        SignalCall {
10881            ctx: self.clone(),
10882            signal_name: signal_name.into(),
10883            runtime_reserved_allowed: false,
10884            opened_wait: false,
10885            matched_pending: false,
10886            parallel_group_path: Vec::new(),
10887        }
10888    }
10889
10890    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10891        SignalCall {
10892            ctx: self.clone(),
10893            signal_name: signal_name.into(),
10894            runtime_reserved_allowed: true,
10895            opened_wait: false,
10896            matched_pending: false,
10897            parallel_group_path: Vec::new(),
10898        }
10899    }
10900
10901    pub async fn wait_signal_avro_value(
10902        &self,
10903        signal_name: impl Into<String>,
10904    ) -> Result<Vec<AvroValue>> {
10905        let mut call = self.wait_signal(signal_name);
10906        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10907    }
10908
10909    /// Return every committed signal argument list with the given name.
10910    ///
10911    /// This history-backed view is deterministic and is intended for
10912    /// condition predicates that must be re-evaluated after a signal while the
10913    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10914    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10915        self.signals_avro_value(signal_name)?
10916            .into_iter()
10917            .map(|arguments| {
10918                arguments
10919                    .into_iter()
10920                    .map(AvroValue::into_json)
10921                    .collect::<Result<Vec<_>>>()
10922            })
10923            .collect()
10924    }
10925
10926    /// Lossless fixed Avro Value view of committed signals with the given name.
10927    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10928        let state = self
10929            .state
10930            .lock()
10931            .map_err(|_| Error::WorkflowStatePoisoned)?;
10932        state
10933            .history_events
10934            .iter()
10935            .filter(|event| {
10936                event.event_type == "SignalReceived"
10937                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10938            })
10939            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10940            .collect()
10941    }
10942
10943    /// Return every committed update argument list with the given name.
10944    ///
10945    /// Accepted and applied records for the same update ID are de-duplicated.
10946    /// A Server task created after an update therefore replays the workflow and
10947    /// re-evaluates an open condition without application polling.
10948    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10949        self.updates_avro_value(update_name)?
10950            .into_iter()
10951            .map(|arguments| {
10952                arguments
10953                    .into_iter()
10954                    .map(AvroValue::into_json)
10955                    .collect::<Result<Vec<_>>>()
10956            })
10957            .collect()
10958    }
10959
10960    /// Lossless fixed Avro Value view of committed updates with the given name.
10961    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10962        let state = self
10963            .state
10964            .lock()
10965            .map_err(|_| Error::WorkflowStatePoisoned)?;
10966        let mut seen = Vec::new();
10967        let mut updates = Vec::new();
10968        for event in state.history_events.iter() {
10969            if !matches!(
10970                event.event_type.as_str(),
10971                "UpdateAccepted" | "UpdateApplied"
10972            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10973                || event.payload.get("arguments").is_none()
10974            {
10975                continue;
10976            }
10977            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10978                if seen.iter().any(|recorded| recorded == update_id) {
10979                    continue;
10980                }
10981                seen.push(update_id.to_string());
10982            }
10983            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10984        }
10985        Ok(updates)
10986    }
10987
10988    /// Wait for a deterministic predicate to become true or for its durable
10989    /// timeout to elapse.
10990    ///
10991    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10992    /// predicate tokens automatically change the recorded definition
10993    /// fingerprint. Direct callers must provide an equally stable identity in
10994    /// [`ConditionWaitOptions`].
10995    pub fn wait_condition<F>(
10996        &self,
10997        options: ConditionWaitOptions,
10998        predicate: F,
10999    ) -> ConditionWaitCall
11000    where
11001        F: Fn() -> Result<bool> + Send + 'static,
11002    {
11003        ConditionWaitCall {
11004            ctx: self.clone(),
11005            options,
11006            predicate: Box::new(predicate),
11007            occurrence_id: None,
11008            opened_wait: false,
11009            parallel_group_path: Vec::new(),
11010        }
11011    }
11012
11013    /// Wait for server-backed durable time without blocking the worker executor.
11014    ///
11015    /// Polling this future emits one `start_timer` command and yields. The
11016    /// server records the deadline, so neither worker nor server restarts reset
11017    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11018    /// `TimerFired` pair at the same position in the shared durable-command
11019    /// stream, with matching sequence, timer identity, and delay. Sub-second
11020    /// durations round up because protocol deadlines use whole seconds.
11021    ///
11022    /// ```no_run
11023    /// # use durable_workflow::{json, Client, Worker};
11024    /// # use std::time::Duration;
11025    /// # fn configure(client: Client) {
11026    /// let mut worker = Worker::new(client, "rust-workers");
11027    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11028    ///     ctx.sleep(Duration::from_secs(5)).await?;
11029    ///     Ok(json!({"status": "timer fired"}))
11030    /// });
11031    /// # }
11032    /// ```
11033    pub fn sleep(&self, duration: Duration) -> TimerCall {
11034        let delay_seconds = duration
11035            .as_secs()
11036            .checked_add(u64::from(duration.subsec_nanos() > 0));
11037        TimerCall {
11038            ctx: self.clone(),
11039            delay_seconds,
11040            scheduled: false,
11041            matched_pending: false,
11042            parallel_group_path: Vec::new(),
11043        }
11044    }
11045
11046    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11047    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11048        self.sleep(duration)
11049    }
11050
11051    /// Evaluate a non-deterministic callback once and durably record its typed value.
11052    ///
11053    /// On replay the callback is not invoked: the value is decoded from the
11054    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11055    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11056    /// small values that must remain fixed for the lifetime of a workflow run.
11057    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11058    where
11059        T: Serialize + DeserializeOwned,
11060        F: FnOnce() -> T,
11061    {
11062        {
11063            let mut state = self
11064                .state
11065                .lock()
11066                .map_err(|_| Error::WorkflowStatePoisoned)?;
11067            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11068                return match recorded {
11069                    RecordedCommand::SideEffect { sequence, value } => {
11070                        state.command_cursor += 1;
11071                        value.deserialize().map_err(|error| {
11072                            Error::NonDeterministicReplay(ReplayFailure::new(
11073                                "side_effect_type_mismatch",
11074                                Some(sequence),
11075                                Some(std::any::type_name::<T>().to_string()),
11076                                Some(error.to_string()),
11077                                "recorded side-effect value is incompatible with the requested Rust type",
11078                            ))
11079                        })
11080                    }
11081                    other => Err(command_mismatch(&other, "side effect")),
11082                };
11083            }
11084        }
11085
11086        let value = callback();
11087        let avro_value = AvroValue::from_serialize(&value)?;
11088        let mut state = self
11089            .state
11090            .lock()
11091            .map_err(|_| Error::WorkflowStatePoisoned)?;
11092        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11093        state.commands.push(json!({
11094            "type": "record_side_effect",
11095            "result": result,
11096        }));
11097        Ok(value)
11098    }
11099
11100    /// Record or replay a lossless fixed Avro Value side effect.
11101    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11102    where
11103        F: FnOnce() -> AvroValue,
11104    {
11105        {
11106            let mut state = self
11107                .state
11108                .lock()
11109                .map_err(|_| Error::WorkflowStatePoisoned)?;
11110            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11111                return match recorded {
11112                    RecordedCommand::SideEffect { value, .. } => {
11113                        state.command_cursor += 1;
11114                        Ok(value)
11115                    }
11116                    other => Err(command_mismatch(&other, "side effect")),
11117                };
11118            }
11119        }
11120
11121        let value = callback();
11122        let mut state = self
11123            .state
11124            .lock()
11125            .map_err(|_| Error::WorkflowStatePoisoned)?;
11126        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11127        state.commands.push(json!({
11128            "type": "record_side_effect",
11129            "result": result,
11130        }));
11131        Ok(value)
11132    }
11133
11134    /// Append output items at a deterministic workflow command boundary.
11135    ///
11136    /// Stable idempotency keys are derived from the server-provided durable
11137    /// workflow command identity, command ordinal, and item index. Replay
11138    /// consumes the recorded side effect and never emits another append.
11139    pub fn append_workflow_stream(
11140        &self,
11141        stream_name: impl Into<String>,
11142        items: &[WorkflowStreamAppendItem],
11143        max_pending_items: Option<u64>,
11144    ) -> Result<()> {
11145        if items.is_empty() {
11146            return Err(Error::Codec(
11147                "workflow_stream_items_empty: append requires at least one item".to_string(),
11148            ));
11149        }
11150        if max_pending_items == Some(0) {
11151            return Err(Error::Codec(
11152                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11153                    .to_string(),
11154            ));
11155        }
11156        let stream_name = stream_name.into();
11157        if stream_name.is_empty() {
11158            return Err(Error::Codec(
11159                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11160            ));
11161        }
11162
11163        let mut state = self
11164            .state
11165            .lock()
11166            .map_err(|_| Error::WorkflowStatePoisoned)?;
11167        let command_ordinal = state.workflow_stream_command_counter;
11168        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11169            state.workflow_stream_command_counter += 1;
11170            return match recorded {
11171                RecordedCommand::SideEffect { .. } => {
11172                    state.command_cursor += 1;
11173                    Ok(())
11174                }
11175                other => Err(command_mismatch(&other, "workflow stream append")),
11176            };
11177        }
11178
11179        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11180        state.workflow_stream_command_counter += 1;
11181        let wire_items = items
11182            .iter()
11183            .enumerate()
11184            .map(|(item_index, item)| {
11185                item.wire_value(Some(format!(
11186                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11187                )))
11188            })
11189            .collect::<Vec<_>>();
11190        let mut directive = json!({
11191            "operation": "append",
11192            "stream_name": stream_name,
11193            "command_identity": identity,
11194            "command_ordinal": command_ordinal,
11195            "items": wire_items,
11196        });
11197        if let Some(max_pending_items) = max_pending_items {
11198            directive["max_pending_items"] = json!(max_pending_items);
11199        }
11200        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11201        state.commands.push(json!({
11202            "type": "record_side_effect",
11203            "result": result,
11204            "workflow_stream": directive,
11205        }));
11206        Ok(())
11207    }
11208
11209    /// Close a run-scoped output stream at a deterministic command boundary.
11210    pub fn close_workflow_stream(
11211        &self,
11212        stream_name: impl Into<String>,
11213        retention_seconds: Option<u64>,
11214    ) -> Result<()> {
11215        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11216    }
11217
11218    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11219    pub fn error_workflow_stream(
11220        &self,
11221        stream_name: impl Into<String>,
11222        error_reason: impl Into<String>,
11223        retention_seconds: Option<u64>,
11224    ) -> Result<()> {
11225        let error_reason = error_reason.into();
11226        if error_reason.is_empty() {
11227            return Err(Error::Codec(
11228                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11229            ));
11230        }
11231        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11232    }
11233
11234    fn finish_workflow_stream(
11235        &self,
11236        stream_name: String,
11237        error_reason: Option<String>,
11238        retention_seconds: Option<u64>,
11239    ) -> Result<()> {
11240        if stream_name.is_empty() {
11241            return Err(Error::Codec(
11242                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11243            ));
11244        }
11245        if retention_seconds == Some(0) {
11246            return Err(Error::Codec(
11247                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11248            ));
11249        }
11250        let mut state = self
11251            .state
11252            .lock()
11253            .map_err(|_| Error::WorkflowStatePoisoned)?;
11254        let command_ordinal = state.workflow_stream_command_counter;
11255        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11256            state.workflow_stream_command_counter += 1;
11257            return match recorded {
11258                RecordedCommand::SideEffect { .. } => {
11259                    state.command_cursor += 1;
11260                    Ok(())
11261                }
11262                other => Err(command_mismatch(&other, "workflow stream close")),
11263            };
11264        }
11265        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11266        state.workflow_stream_command_counter += 1;
11267        let mut directive = json!({
11268            "operation": if error_reason.is_some() { "error" } else { "close" },
11269            "stream_name": stream_name,
11270            "command_identity": identity,
11271            "command_ordinal": command_ordinal,
11272        });
11273        if let Some(error_reason) = error_reason {
11274            directive["error_reason"] = json!(error_reason);
11275        }
11276        if let Some(retention_seconds) = retention_seconds {
11277            directive["retention_seconds"] = json!(retention_seconds);
11278        }
11279        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11280        state.commands.push(json!({
11281            "type": "record_side_effect",
11282            "result": result,
11283            "workflow_stream": directive,
11284        }));
11285        Ok(())
11286    }
11287
11288    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11289        let identity = state.workflow_command_identity.as_str();
11290        if identity.is_empty() {
11291            return Err(Error::MissingWorkflowCommandIdentity);
11292        }
11293        Ok(identity)
11294    }
11295
11296    /// Validate, emit, or replay a typed workflow search-attribute update.
11297    ///
11298    /// The command is non-blocking within a workflow decision, but its
11299    /// `SearchAttributesUpserted` event occupies the same deterministic command
11300    /// stream as activities, timers, conditions, and other durable operations.
11301    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11302        update.validate()?;
11303        let (attributes, attribute_types) = update.into_wire_parts();
11304        let mut state = self
11305            .state
11306            .lock()
11307            .map_err(|_| Error::WorkflowStatePoisoned)?;
11308
11309        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11310            return match recorded {
11311                RecordedCommand::SearchAttributes {
11312                    sequence,
11313                    attributes: recorded_attributes,
11314                    attribute_types: recorded_attribute_types,
11315                } => {
11316                    if recorded_attributes != attributes {
11317                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11318                            "search_attribute_value_mismatch",
11319                            Some(sequence),
11320                            Some(recorded_attributes.to_string()),
11321                            Some(attributes.to_string()),
11322                            "search-attribute values differ from the recorded durable command",
11323                        )));
11324                    }
11325                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11326                        if recorded_types != attribute_types {
11327                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11328                                "search_attribute_type_mismatch",
11329                                Some(sequence),
11330                                Some(json!(recorded_types).to_string()),
11331                                Some(json!(attribute_types).to_string()),
11332                                "search-attribute declared types differ from the recorded durable command",
11333                            )));
11334                        }
11335                    }
11336                    state.command_cursor += 1;
11337                    Ok(())
11338                }
11339                other => Err(command_mismatch(&other, "search-attribute update")),
11340            };
11341        }
11342
11343        let mut command = serde_json::Map::from_iter([
11344            ("type".to_string(), json!("upsert_search_attributes")),
11345            ("attributes".to_string(), attributes),
11346        ]);
11347        if !attribute_types.is_empty() {
11348            command.insert("attribute_types".to_string(), json!(attribute_types));
11349        }
11350        state.commands.push(Value::Object(command));
11351        Ok(())
11352    }
11353
11354    /// Record a UUIDv4 once and return the same UUID on every replay.
11355    pub fn uuid_v4(&self) -> Result<Uuid> {
11356        self.side_effect(Uuid::new_v4)
11357    }
11358
11359    /// Select the newest supported version for a change, or replay the version
11360    /// already committed for that stable change ID.
11361    ///
11362    /// An unmarked old history that reached its next durable operation, or
11363    /// already completed, selects `-1` when that version is supported. This
11364    /// leaves the original operation available and writes no additional marker.
11365    /// Consistent markers written by older workers retain their original ordered
11366    /// positions. Repeated calls consume a matching marker at the current cursor.
11367    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11368    pub fn get_version(
11369        &self,
11370        change_id: impl Into<String>,
11371        min_supported: i32,
11372        max_supported: i32,
11373    ) -> Result<i32> {
11374        let change_id = change_id.into();
11375        if change_id.trim().is_empty() {
11376            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11377                "version_change_id_invalid",
11378                None,
11379                Some("non-empty change ID".to_string()),
11380                Some(change_id),
11381                "version markers require a stable non-empty change ID",
11382            )));
11383        }
11384        if min_supported > max_supported {
11385            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11386                "version_range_invalid",
11387                None,
11388                Some("min_supported <= max_supported".to_string()),
11389                Some(format!("{min_supported}..={max_supported}")),
11390                "version marker supported range is invalid",
11391            )));
11392        }
11393
11394        let mut state = self
11395            .state
11396            .lock()
11397            .map_err(|_| Error::WorkflowStatePoisoned)?;
11398        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
11399            if let Some(RecordedCommand::VersionMarker {
11400                sequence: alias_sequence,
11401                change_id: alias_change_id,
11402                version: alias_version,
11403            }) = state.recorded_commands.get(state.command_cursor)
11404            {
11405                if alias_change_id == &change_id {
11406                    if *alias_version != version {
11407                        return Err(invalid_recorded_history(
11408                            "version_marker_conflict",
11409                            *alias_sequence,
11410                            &format!("selected version {version} for change ID {change_id:?}"),
11411                            &format!("recorded version {alias_version}"),
11412                            "recorded marker conflicts with the decision already selected during replay",
11413                        ));
11414                    }
11415                    ensure_version_supported(
11416                        &change_id,
11417                        version,
11418                        min_supported,
11419                        max_supported,
11420                        *alias_sequence,
11421                    )?;
11422                    // Older workers could record the same decision again. Keep
11423                    // each physical boundary without skipping intervening work.
11424                    state.command_cursor += 1;
11425                    return Ok(version);
11426                }
11427            }
11428            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
11429            return Ok(version);
11430        }
11431
11432        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11433            return match recorded {
11434                RecordedCommand::VersionMarker {
11435                    sequence,
11436                    change_id: recorded_change_id,
11437                    version,
11438                    ..
11439                } => {
11440                    if recorded_change_id != change_id {
11441                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11442                            "version_change_id_mismatch",
11443                            Some(sequence),
11444                            Some(recorded_change_id),
11445                            Some(change_id),
11446                            "recorded version marker change ID differs from current workflow code",
11447                        )));
11448                    }
11449                    ensure_version_supported(
11450                        &change_id,
11451                        version,
11452                        min_supported,
11453                        max_supported,
11454                        sequence,
11455                    )?;
11456                    state.command_cursor += 1;
11457                    state.version_markers.insert(change_id, (version, sequence));
11458                    Ok(version)
11459                }
11460                other => {
11461                    let version = -1;
11462                    let sequence = other.sequence();
11463                    ensure_version_supported(
11464                        &change_id,
11465                        version,
11466                        min_supported,
11467                        max_supported,
11468                        sequence,
11469                    )?;
11470                    // The existing operation proves this patch site was reached
11471                    // before its marker existed. Keep its original cursor.
11472                    state.version_markers.insert(change_id, (version, sequence));
11473                    Ok(version)
11474                }
11475            };
11476        }
11477
11478        if state
11479            .history_events
11480            .iter()
11481            .any(|event| event.event_type == "WorkflowCompleted")
11482        {
11483            let version = -1;
11484            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
11485            state.version_markers.insert(change_id, (version, 0));
11486            return Ok(version);
11487        }
11488
11489        let version = max_supported;
11490        state.commands.push(json!({
11491            "type": "record_version_marker",
11492            "change_id": change_id,
11493            "version": version,
11494            "min_supported": min_supported,
11495            "max_supported": max_supported,
11496        }));
11497        // Sequence numbers are assigned by the server. Zero identifies a marker
11498        // selected in this uncommitted decision batch for duplicate-call checks.
11499        state.version_markers.insert(change_id, (version, 0));
11500        Ok(version)
11501    }
11502
11503    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
11504    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
11505        Ok(self.get_version(change_id, -1, 1)? == 1)
11506    }
11507
11508    /// Keep a patch marker in history after the legacy branch has been removed.
11509    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
11510        self.get_version(change_id, -1, 1).map(|_| ())
11511    }
11512
11513    /// Merge non-indexed workflow memo metadata through durable history.
11514    ///
11515    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
11516    /// public Avro payload envelope consumed by Server and Cloud runtimes.
11517    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
11518        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
11519        let mut state = self
11520            .state
11521            .lock()
11522            .map_err(|_| Error::WorkflowStatePoisoned)?;
11523
11524        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11525            return match recorded {
11526                RecordedCommand::Memo {
11527                    sequence,
11528                    entries: recorded_entries,
11529                } => {
11530                    if recorded_entries != entries {
11531                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11532                            "memo_update_mismatch",
11533                            Some(sequence),
11534                            Some(format!("{recorded_entries:?}")),
11535                            Some(format!("{entries:?}")),
11536                            "recorded memo entries differ from the current workflow update",
11537                        )));
11538                    }
11539                    state.command_cursor += 1;
11540                    Ok(())
11541                }
11542                other => Err(command_mismatch(&other, "memo upsert")),
11543            };
11544        }
11545
11546        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
11547        state.commands.push(json!({
11548            "type": "upsert_memo",
11549            "entries": entries_envelope,
11550        }));
11551        Ok(())
11552    }
11553
11554    /// Start a named durable child on an explicit queue and await its result.
11555    ///
11556    /// The command is recorded in the parent's sequence-ordered durable command
11557    /// stream. Replay keeps a scheduled child pending without emitting another
11558    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
11559    /// values preserve the history payload codec and include both sides of the
11560    /// durable relationship; failures are returned as
11561    /// [`Error::ChildWorkflowFailed`].
11562    ///
11563    /// ```no_run
11564    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
11565    /// # fn configure(client: Client) {
11566    /// let mut worker = Worker::new(client, "parent-workers");
11567    /// worker.register_workflow("order-parent", |ctx, _input| async move {
11568    ///     let child = ctx
11569    ///         .start_child_workflow(
11570    ///             "fulfil-order",
11571    ///             ChildWorkflowOptions::new("fulfilment-workers")
11572    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
11573    ///             json!([{"order_id": "order-42"}]),
11574    ///         )
11575    ///         .await?;
11576    ///     Ok(child.result)
11577    /// });
11578    /// # }
11579    /// ```
11580    pub fn start_child_workflow<T: Serialize>(
11581        &self,
11582        workflow_type: impl Into<String>,
11583        options: ChildWorkflowOptions,
11584        args: T,
11585    ) -> ChildWorkflowCall {
11586        ChildWorkflowCall {
11587            ctx: self.clone(),
11588            workflow_type: workflow_type.into(),
11589            options,
11590            args: Some(AvroValue::from_serialize(&args)),
11591            scheduled: false,
11592            matched_pending: false,
11593            parallel_group_path: Vec::new(),
11594        }
11595    }
11596
11597    pub async fn start_child_workflow_avro_value<T: Serialize>(
11598        &self,
11599        workflow_type: impl Into<String>,
11600        options: ChildWorkflowOptions,
11601        args: T,
11602    ) -> Result<ChildWorkflowAvroResult> {
11603        let mut call = self.start_child_workflow(workflow_type, options, args);
11604        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11605    }
11606
11607    fn take_commands(&self) -> Result<Vec<Value>> {
11608        let mut state = self
11609            .state
11610            .lock()
11611            .map_err(|_| Error::WorkflowStatePoisoned)?;
11612        Ok(std::mem::take(&mut state.commands))
11613    }
11614
11615    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11616        let mut state = self
11617            .state
11618            .lock()
11619            .map_err(|_| Error::WorkflowStatePoisoned)?;
11620
11621        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11622            return Err(command_mismatch(&recorded, "continue as new"));
11623        }
11624        if state.recorded_continue_as_new_sequence.is_some() {
11625            state.continue_as_new_consumed = true;
11626            return Ok(None);
11627        }
11628
11629        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11630        let mut command = serde_json::Map::from_iter([
11631            ("type".to_string(), json!("continue_as_new")),
11632            ("arguments".to_string(), arguments),
11633            ("queue".to_string(), json!(state.task_queue.clone())),
11634        ]);
11635        if let Some(workflow_type) = request.options.workflow_type {
11636            command.insert("workflow_type".to_string(), json!(workflow_type));
11637        }
11638        if let Some(task_queue) = request.options.task_queue {
11639            command.insert("queue".to_string(), json!(task_queue));
11640        }
11641        Ok(Some(Value::Object(command)))
11642    }
11643
11644    fn matched_recorded_pending(&self) -> Result<bool> {
11645        let state = self
11646            .state
11647            .lock()
11648            .map_err(|_| Error::WorkflowStatePoisoned)?;
11649        Ok(state.matched_recorded_pending)
11650    }
11651
11652    fn ensure_history_consumed(&self) -> Result<()> {
11653        let state = self
11654            .state
11655            .lock()
11656            .map_err(|_| Error::WorkflowStatePoisoned)?;
11657        if let Some(replay) = &state.scope_delivery {
11658            if let Some((&sequence, _)) = replay
11659                .canonical
11660                .deliveries
11661                .iter()
11662                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11663            {
11664                return Err(invalid_recorded_history(
11665                    "cancellation_scope_delivery_unconsumed",
11666                    sequence,
11667                    "original scoped delivery",
11668                    "workflow completion",
11669                    "workflow completed without consuming its committed scope delivery",
11670                ));
11671            }
11672        }
11673        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11674            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11675                "recorded_commands_unconsumed",
11676                Some(command.sequence()),
11677                Some(command.shape().to_string()),
11678                Some("workflow completion".to_string()),
11679                "workflow completed before consuming all recorded durable commands",
11680            )));
11681        }
11682        if let Some(delivery) = state
11683            .cancellation_history
11684            .delivery
11685            .as_ref()
11686            .filter(|_| !state.cancellation_consumed)
11687        {
11688            return Err(invalid_recorded_history(
11689                "cooperative_cancellation_unconsumed",
11690                delivery.sequence,
11691                "committed cancellation call",
11692                "workflow completion",
11693                "workflow completed without reaching its committed cancellation boundary",
11694            ));
11695        }
11696        if let Some(sequence) = state
11697            .recorded_continue_as_new_sequence
11698            .filter(|_| !state.continue_as_new_consumed)
11699        {
11700            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11701                "recorded_continue_as_new_unconsumed",
11702                Some(sequence),
11703                Some("continue as new".to_string()),
11704                Some("workflow completion".to_string()),
11705                "workflow completed without consuming its recorded continue-as-new transition",
11706            )));
11707        }
11708        Ok(())
11709    }
11710}
11711
11712fn contiguous_message_stream_count(
11713    pending: &[MessageStreamMessage],
11714    cursor: u64,
11715    max_items: usize,
11716) -> usize {
11717    pending
11718        .iter()
11719        .take(max_items)
11720        .enumerate()
11721        .take_while(|(offset, message)| {
11722            u64::try_from(*offset)
11723                .ok()
11724                .and_then(|offset| cursor.checked_add(offset + 1))
11725                == Some(message.position)
11726        })
11727        .count()
11728}
11729
11730fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11731    matches!(
11732        event.event_type.as_str(),
11733        "ActivityScheduled"
11734            | "TimerScheduled"
11735            | "ChildWorkflowScheduled"
11736            | "SignalWaitOpened"
11737            | "ConditionWaitOpened"
11738            | "SearchAttributesUpserted"
11739            | "SideEffectRecorded"
11740            | "VersionMarkerRecorded"
11741            | "MemoUpserted"
11742            | "WorkflowContinuedAsNew"
11743    )
11744}
11745
11746#[derive(Debug)]
11747struct WorkflowState {
11748    workflow_id: Option<String>,
11749    run_id: Option<String>,
11750    task_queue: String,
11751    payload_codec: String,
11752    history_events: Arc<Vec<HistoryEvent>>,
11753    history_budget: WorkflowHistoryBudget,
11754    cancel_requested: bool,
11755    cancellation_history: CancellationHistory,
11756    cancellation_consumed: bool,
11757    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11758    cancellation_shield_depth: u64,
11759    cancellation_delivery_enabled: bool,
11760    cancellation_delivery_intent: Option<CancellationDelivery>,
11761    cancellation_delivery_command_count: usize,
11762    allow_cancellation_scope_authoring: bool,
11763    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11764    cancellation_scope_memberships: BTreeMap<u64, String>,
11765    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11766    resume_signal: Option<ResumeSignal>,
11767    recorded_commands: Vec<RecordedCommand>,
11768    selection_markers: Vec<SelectionMarker>,
11769    selection_marker_cursor: usize,
11770    cancelled_selection_members: Vec<SelectionCancellation>,
11771    recorded_continue_as_new_sequence: Option<u64>,
11772    continue_as_new_consumed: bool,
11773    command_cursor: usize,
11774    condition_wait_occurrence_counter: u64,
11775    matched_recorded_pending: bool,
11776    version_markers: HashMap<String, (i32, u64)>,
11777    workflow_command_identity: String,
11778    workflow_stream_command_counter: u64,
11779    commands: Vec<Value>,
11780    local_activity_requests: Vec<local_activity::Request>,
11781    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11782    message_stream_cursors: HashMap<String, u64>,
11783    message_stream_waits: HashMap<String, u64>,
11784}
11785
11786impl WorkflowState {
11787    #[cfg(test)]
11788    fn new(
11789        history: Vec<HistoryEvent>,
11790        task_queue: String,
11791        payload_codec: String,
11792        resume_signal: Option<ResumeSignal>,
11793    ) -> Result<Self> {
11794        Self::new_with_identity(
11795            history,
11796            None,
11797            None,
11798            task_queue,
11799            payload_codec,
11800            resume_signal,
11801        )
11802    }
11803
11804    fn new_with_identity(
11805        history: Vec<HistoryEvent>,
11806        workflow_id: Option<String>,
11807        run_id: Option<String>,
11808        task_queue: String,
11809        payload_codec: String,
11810        resume_signal: Option<ResumeSignal>,
11811    ) -> Result<Self> {
11812        Self::new_with_identity_and_scopes(
11813            history,
11814            workflow_id,
11815            run_id,
11816            task_queue,
11817            payload_codec,
11818            resume_signal,
11819            false,
11820        )
11821    }
11822
11823    fn new_with_identity_and_scopes(
11824        history: Vec<HistoryEvent>,
11825        workflow_id: Option<String>,
11826        run_id: Option<String>,
11827        task_queue: String,
11828        payload_codec: String,
11829        resume_signal: Option<ResumeSignal>,
11830        allow_cancellation_scope_authoring: bool,
11831    ) -> Result<Self> {
11832        Self::new_with_identity_and_scope_delivery(
11833            history,
11834            workflow_id,
11835            run_id,
11836            task_queue,
11837            payload_codec,
11838            resume_signal,
11839            allow_cancellation_scope_authoring,
11840            false,
11841        )
11842    }
11843
11844    fn new_with_identity_and_scope_delivery(
11845        history: Vec<HistoryEvent>,
11846        workflow_id: Option<String>,
11847        run_id: Option<String>,
11848        task_queue: String,
11849        payload_codec: String,
11850        resume_signal: Option<ResumeSignal>,
11851        allow_cancellation_scope_authoring: bool,
11852        allow_cancellation_scope_delivery: bool,
11853    ) -> Result<Self> {
11854        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11855            &history,
11856            allow_cancellation_scope_authoring,
11857            allow_cancellation_scope_delivery,
11858        )?;
11859        let scopes = if allow_cancellation_scope_authoring {
11860            cancellation_scope::CancellationScopeHistory::read(
11861                &history,
11862                run_id.as_deref().unwrap_or_default(),
11863            )?
11864        } else {
11865            cancellation_scope::CancellationScopeHistory::default()
11866        };
11867        let cancellation_history = CancellationHistory::from_events(
11868            &history,
11869            run_id.as_deref().unwrap_or_default(),
11870            None,
11871        )?;
11872        if allow_cancellation_scope_authoring
11873            && cancellation_history.request.is_some()
11874            && !allow_cancellation_scope_delivery
11875        {
11876            return Err(Error::CancellationScopeExecutionUnavailable);
11877        }
11878        let scope_delivery = if allow_cancellation_scope_delivery {
11879            Some(cancellation_scope_replay::ScopeReplay::read(
11880                &history,
11881                &scopes,
11882                run_id.as_deref().unwrap_or_default(),
11883                workflow_id.as_deref().unwrap_or_default(),
11884            )?)
11885        } else {
11886            None
11887        };
11888        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11889            &history,
11890            &payload_codec,
11891            WorkflowIdentity {
11892                workflow_id: workflow_id.clone(),
11893                run_id: run_id.clone(),
11894            },
11895        )?)?;
11896        for (sequence, opening) in &scopes.openings {
11897            if recorded_commands
11898                .iter()
11899                .any(|command| command.sequence() == *sequence)
11900            {
11901                return Err(invalid_recorded_history(
11902                    "invalid_cancellation_scope_history",
11903                    *sequence,
11904                    "distinct authored scope opening",
11905                    "operation collision",
11906                    "scope opening collides with a command",
11907                ));
11908            }
11909            recorded_commands.push(RecordedCommand::CancellationScope {
11910                sequence: *sequence,
11911                scope_id: opening.scope_id.clone(),
11912                parent_scope_id: opening.parent_scope_id.clone(),
11913                shield_parent: opening.shield_parent,
11914            });
11915        }
11916        recorded_commands.sort_by_key(RecordedCommand::sequence);
11917        if let Some(replay) = &scope_delivery {
11918            replay.bind_commands(&mut recorded_commands)?;
11919        }
11920        let selection_markers = recorded_selection_markers(&history)?;
11921        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11922        let recorded_continue_as_new = history
11923            .iter()
11924            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11925            .collect::<Vec<_>>();
11926        if recorded_continue_as_new.len() > 1 {
11927            return Err(invalid_recorded_history(
11928                "duplicate_continue_as_new_transition",
11929                recorded_continue_as_new
11930                    .last()
11931                    .and_then(|event| durable_event_sequence(event))
11932                    .unwrap_or(0),
11933                "one WorkflowContinuedAsNew event",
11934                &format!(
11935                    "{} WorkflowContinuedAsNew events",
11936                    recorded_continue_as_new.len()
11937                ),
11938                "workflow history records one continue-as-new transition more than once",
11939            ));
11940        }
11941        let recorded_continue_as_new_sequence = recorded_continue_as_new
11942            .first()
11943            .map(|event| {
11944                durable_event_sequence(event).ok_or_else(|| {
11945                    Error::NonDeterministicReplay(ReplayFailure::new(
11946                        "continue_as_new_sequence_missing",
11947                        None,
11948                        Some("recorded transition sequence".to_string()),
11949                        Some("missing sequence".to_string()),
11950                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11951                    ))
11952                })
11953            })
11954            .transpose()?;
11955        let mut message_stream_cursors = HashMap::new();
11956        for event in &history {
11957            if !matches!(
11958                event.event_type.as_str(),
11959                "SignalReceived" | "SignalApplied"
11960            ) || event.payload.get("signal_name").and_then(Value::as_str)
11961                != Some(MESSAGE_STREAM_SIGNAL)
11962            {
11963                continue;
11964            }
11965            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11966            if arguments.len() != 1 {
11967                continue;
11968            }
11969            let envelope = arguments[0].clone().into_json()?;
11970            let Some(envelope) = envelope.as_object() else {
11971                continue;
11972            };
11973            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11974            {
11975                continue;
11976            }
11977            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11978                continue;
11979            };
11980            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11981            else {
11982                continue;
11983            };
11984            let cursor = message_stream_cursors
11985                .entry(stream_name.to_string())
11986                .or_insert(0);
11987            *cursor = (*cursor).max(through_position);
11988        }
11989        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11990        let cancel_requested = history.iter().any(|event| {
11991            matches!(
11992                event.event_type.as_str(),
11993                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11994            )
11995        });
11996        let cancellation_clock = cancellation_history
11997            .request
11998            .as_ref()
11999            .and_then(|request| request.context.as_ref())
12000            .map(|_| {
12001                cancellation_replay_clock::ReplayClock::new(
12002                    &history,
12003                    &recorded_commands,
12004                    cancellation_history.delivery_index,
12005                )
12006            })
12007            .or_else(|| {
12008                scope_delivery.as_ref().map(|_| {
12009                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12010                })
12011            });
12012        Ok(Self {
12013            workflow_command_identity: String::new(),
12014            workflow_stream_command_counter: 0,
12015            workflow_id,
12016            run_id,
12017            task_queue,
12018            payload_codec,
12019            history_events: Arc::new(history),
12020            history_budget: WorkflowHistoryBudget {
12021                event_count,
12022                ..WorkflowHistoryBudget::default()
12023            },
12024            cancel_requested,
12025            cancellation_history,
12026            cancellation_consumed: false,
12027            cancellation_clock,
12028            cancellation_shield_depth: 0,
12029            cancellation_delivery_enabled: false,
12030            cancellation_delivery_intent: None,
12031            cancellation_delivery_command_count: 0,
12032            allow_cancellation_scope_authoring,
12033            cancellation_scope_opening: None,
12034            cancellation_scope_memberships: scopes.memberships,
12035            scope_delivery,
12036            resume_signal,
12037            recorded_commands,
12038            selection_markers,
12039            selection_marker_cursor: 0,
12040            cancelled_selection_members,
12041            recorded_continue_as_new_sequence,
12042            continue_as_new_consumed: false,
12043            command_cursor: 0,
12044            condition_wait_occurrence_counter: 0,
12045            matched_recorded_pending: false,
12046            version_markers: HashMap::new(),
12047            commands: Vec::new(),
12048            local_activity_requests: Vec::new(),
12049            message_stream_messages: HashMap::new(),
12050            message_stream_cursors,
12051            message_stream_waits: HashMap::new(),
12052        })
12053    }
12054}
12055
12056enum MessageStreamDelivery {
12057    Message(MessageStreamMessage),
12058    Cursor {
12059        stream_name: String,
12060        through_position: u64,
12061    },
12062}
12063
12064fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12065    if arguments.len() != 1 {
12066        return Ok(None);
12067    }
12068    let envelope = arguments
12069        .into_iter()
12070        .next()
12071        .expect("one argument was checked");
12072    let Some(envelope) = envelope.as_object() else {
12073        return Ok(None);
12074    };
12075    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12076        return Ok(None);
12077    };
12078    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12079        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12080        else {
12081            return Ok(None);
12082        };
12083        return Ok(Some(MessageStreamDelivery::Cursor {
12084            stream_name: stream_name.to_string(),
12085            through_position,
12086        }));
12087    }
12088    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12089        return Ok(None);
12090    }
12091    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12092        return Ok(None);
12093    };
12094    let Some(position) = envelope
12095        .get("position")
12096        .and_then(Value::as_u64)
12097        .filter(|value| *value > 0)
12098    else {
12099        return Ok(None);
12100    };
12101    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12102        return Ok(None);
12103    };
12104    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12105    else {
12106        return Ok(None);
12107    };
12108    let decoded = decode_avro_value(&payload_envelope)?;
12109    let AvroValue::Array(values) = decoded else {
12110        return Ok(None);
12111    };
12112    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12113        stream_name: stream_name.to_string(),
12114        message_id: message_id.to_string(),
12115        position,
12116        arguments: values,
12117    })))
12118}
12119
12120#[derive(Clone, Debug)]
12121enum RecordedCommand {
12122    ServiceOperation {
12123        sequence: u64,
12124        call: nexus::RecordedServiceCall,
12125    },
12126    CancellationScope {
12127        sequence: u64,
12128        scope_id: String,
12129        parent_scope_id: String,
12130        shield_parent: bool,
12131    },
12132    CancellationGroup {
12133        sequence: u64,
12134        span: u64,
12135        original: Vec<RecordedCommand>,
12136    },
12137    CancellationBoundary {
12138        sequence: u64,
12139        call_kind: CancellationCallKind,
12140        original: Option<Box<RecordedCommand>>,
12141    },
12142    Activity {
12143        sequence: u64,
12144        activity_type: Option<String>,
12145        cancellation_policy: String,
12146        options: Option<RecordedActivityOptions>,
12147        outcome: Option<ActivityOutcome>,
12148        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12149    },
12150    Timer {
12151        sequence: u64,
12152        delay_seconds: u64,
12153        fired: bool,
12154        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12155    },
12156    ChildWorkflow {
12157        sequence: u64,
12158        workflow_type: Option<String>,
12159        policies: RecordedChildPolicies,
12160        outcome: Option<ChildWorkflowOutcome>,
12161        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12162    },
12163    SignalWait {
12164        sequence: u64,
12165        signal_name: String,
12166        value: Option<Vec<AvroValue>>,
12167        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12168    },
12169    ConditionWait {
12170        sequence: u64,
12171        occurrence_id: String,
12172        condition_key: Option<String>,
12173        predicate_identity: String,
12174        timeout_seconds: Option<u64>,
12175        result: Option<ConditionWaitResult>,
12176        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12177    },
12178    SearchAttributes {
12179        sequence: u64,
12180        attributes: Value,
12181        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12182    },
12183    SideEffect {
12184        sequence: u64,
12185        value: AvroValue,
12186    },
12187    VersionMarker {
12188        sequence: u64,
12189        change_id: String,
12190        version: i32,
12191    },
12192    Memo {
12193        sequence: u64,
12194        entries: AvroValue,
12195    },
12196}
12197
12198#[derive(Clone, Debug, PartialEq, Eq)]
12199struct SelectionMarker {
12200    selection_group_id: String,
12201    selection_group_base_sequence: u64,
12202    selection_group_size: usize,
12203    member_key: SelectionKey,
12204    member_index: usize,
12205    member_base_sequence: u64,
12206    member_size: usize,
12207    operation_kind: String,
12208    operation_identity: String,
12209    outcome: String,
12210    resolution_event_id: String,
12211    resolution_event_type: String,
12212}
12213
12214#[derive(Clone, Debug, PartialEq, Eq)]
12215struct SelectionCancellation {
12216    selection_group_id: String,
12217    member_key: SelectionKey,
12218    member_index: usize,
12219    member_base_sequence: u64,
12220    member_size: usize,
12221    operation_kind: String,
12222    operation_identity: String,
12223}
12224
12225fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12226    let mut markers: Vec<SelectionMarker> = Vec::new();
12227    for event in events
12228        .iter()
12229        .filter(|event| event.event_type == "SelectionResolved")
12230    {
12231        let payload = &event.payload;
12232        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12233        let group_size = required_selection_usize(payload, "selection_group_size")?;
12234        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12235        let member_size = required_selection_usize(payload, "member_size")?;
12236        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12237        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12238            invalid_recorded_history(
12239                "selection_marker_invalid",
12240                base_sequence,
12241                "non-empty selection_group_id",
12242                &payload.to_string(),
12243                "selection winner history is missing its durable group identity",
12244            )
12245        })?;
12246        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12247        if group_id != expected_group_id {
12248            return Err(invalid_recorded_history(
12249                "selection_marker_invalid",
12250                base_sequence,
12251                &expected_group_id,
12252                &group_id,
12253                "selection winner history contains an incompatible group identity",
12254            ));
12255        }
12256        let group_end = base_sequence
12257            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12258            .unwrap_or(u64::MAX);
12259        let member_end = member_base_sequence
12260            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12261            .unwrap_or(u64::MAX);
12262        if member_index >= group_size
12263            || member_base_sequence < base_sequence
12264            || member_end > group_end
12265        {
12266            return Err(invalid_recorded_history(
12267                "selection_marker_invalid",
12268                base_sequence,
12269                "winner member within selection group bounds",
12270                &payload.to_string(),
12271                "selection winner history contains an invalid member range",
12272            ));
12273        }
12274        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12275            invalid_recorded_history(
12276                "selection_marker_invalid",
12277                base_sequence,
12278                "selection operation kind",
12279                &payload.to_string(),
12280                "selection winner history is missing its operation kind",
12281            )
12282        })?;
12283        if !matches!(
12284            operation_kind.as_str(),
12285            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12286        ) {
12287            return Err(invalid_recorded_history(
12288                "selection_marker_invalid",
12289                base_sequence,
12290                "activity, child, timer, signal, condition, or group",
12291                &operation_kind,
12292                "selection winner history contains an unsupported operation kind",
12293            ));
12294        }
12295        let operation_identity =
12296            payload_string(payload, "operation_identity").ok_or_else(|| {
12297                invalid_recorded_history(
12298                    "selection_marker_invalid",
12299                    base_sequence,
12300                    "non-empty operation identity",
12301                    &payload.to_string(),
12302                    "selection winner history is missing its durable operation identity",
12303                )
12304            })?;
12305        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12306            invalid_recorded_history(
12307                "selection_marker_invalid",
12308                base_sequence,
12309                "completed or failed selection outcome",
12310                &payload.to_string(),
12311                "selection winner history is missing its outcome",
12312            )
12313        })?;
12314        if !matches!(outcome.as_str(), "completed" | "failed") {
12315            return Err(invalid_recorded_history(
12316                "selection_marker_invalid",
12317                base_sequence,
12318                "completed or failed selection outcome",
12319                &outcome,
12320                "selection winner history contains an unsupported outcome",
12321            ));
12322        }
12323        let marker = SelectionMarker {
12324            selection_group_id: group_id,
12325            selection_group_base_sequence: base_sequence,
12326            selection_group_size: group_size,
12327            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
12328            member_index,
12329            member_base_sequence,
12330            member_size,
12331            operation_kind,
12332            operation_identity,
12333            outcome,
12334            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
12335                || {
12336                    invalid_recorded_history(
12337                        "selection_marker_invalid",
12338                        base_sequence,
12339                        "durable resolution_event_id",
12340                        &payload.to_string(),
12341                        "selection winner history is missing its terminal event identity",
12342                    )
12343                },
12344            )?,
12345            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
12346                || {
12347                    invalid_recorded_history(
12348                        "selection_marker_invalid",
12349                        base_sequence,
12350                        "durable resolution_event_type",
12351                        &payload.to_string(),
12352                        "selection winner history is missing its terminal event type",
12353                    )
12354                },
12355            )?,
12356        };
12357        if let Some(existing) = markers
12358            .iter()
12359            .find(|existing| existing.selection_group_id == marker.selection_group_id)
12360        {
12361            if existing != &marker {
12362                return Err(invalid_recorded_history(
12363                    "selection_marker_conflict",
12364                    base_sequence,
12365                    &format!("one winner for {}", marker.selection_group_id),
12366                    &payload.to_string(),
12367                    "selection history records conflicting winners for one durable group",
12368                ));
12369            }
12370            continue;
12371        }
12372        markers.push(marker);
12373    }
12374    Ok(markers)
12375}
12376
12377fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
12378    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
12379    for event in events
12380        .iter()
12381        .filter(|event| event.event_type == "SelectionOperationCancelled")
12382    {
12383        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
12384            invalid_recorded_history(
12385                "selection_cancellation_invalid",
12386                0,
12387                "non-empty selection_group_id",
12388                &event.payload.to_string(),
12389                "selection cancellation history is missing its group identity",
12390            )
12391        })?;
12392        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
12393        let marker = SelectionCancellation {
12394            selection_group_id: group_id,
12395            member_key: selection_key_from_value(
12396                event.payload.get("member_key"),
12397                member_base_sequence,
12398            )?,
12399            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
12400            member_base_sequence,
12401            member_size: required_selection_usize(&event.payload, "member_size")?,
12402            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
12403                invalid_recorded_history(
12404                    "selection_cancellation_invalid",
12405                    member_base_sequence,
12406                    "selection operation kind",
12407                    &event.payload.to_string(),
12408                    "selection cancellation is missing its operation kind",
12409                )
12410            })?,
12411            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
12412                || {
12413                    invalid_recorded_history(
12414                        "selection_cancellation_invalid",
12415                        member_base_sequence,
12416                        "selection operation identity",
12417                        &event.payload.to_string(),
12418                        "selection cancellation is missing its operation identity",
12419                    )
12420                },
12421            )?,
12422        };
12423        if let Some(existing) = cancelled.iter().find(|recorded| {
12424            recorded.selection_group_id == marker.selection_group_id
12425                && recorded.member_base_sequence == marker.member_base_sequence
12426        }) {
12427            if existing != &marker {
12428                return Err(invalid_recorded_history(
12429                    "selection_cancellation_conflict",
12430                    member_base_sequence,
12431                    "one stable SelectionOperationCancelled marker",
12432                    &event.payload.to_string(),
12433                    "selection cancellation history contains conflicting member metadata",
12434                ));
12435            }
12436        } else {
12437            cancelled.push(marker);
12438        }
12439    }
12440    Ok(cancelled)
12441}
12442
12443fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
12444    payload
12445        .get(field)
12446        .and_then(value_as_u64)
12447        .filter(|value| *value > 0)
12448        .ok_or_else(|| {
12449            invalid_recorded_history(
12450                "selection_marker_invalid",
12451                0,
12452                &format!("positive integer {field}"),
12453                &payload.to_string(),
12454                "selection history contains invalid durable identity metadata",
12455            )
12456        })
12457}
12458
12459fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
12460    required_selection_usize_allow_zero(payload, field).and_then(|value| {
12461        if value > 0 {
12462            Ok(value)
12463        } else {
12464            Err(invalid_recorded_history(
12465                "selection_marker_invalid",
12466                0,
12467                &format!("positive integer {field}"),
12468                &payload.to_string(),
12469                "selection history contains invalid durable identity metadata",
12470            ))
12471        }
12472    })
12473}
12474
12475fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
12476    payload
12477        .get(field)
12478        .and_then(value_as_u64)
12479        .and_then(|value| usize::try_from(value).ok())
12480        .ok_or_else(|| {
12481            invalid_recorded_history(
12482                "selection_marker_invalid",
12483                0,
12484                &format!("non-negative integer {field}"),
12485                &payload.to_string(),
12486                "selection history contains invalid durable identity metadata",
12487            )
12488        })
12489}
12490
12491#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12492struct RecordedActivityOptions {
12493    task_queue: RecordedSnapshotValue<Option<String>>,
12494    execution_mode: RecordedSnapshotValue<Option<String>>,
12495    retry_policy: ActivityRetrySnapshot,
12496    worker_session: Option<Value>,
12497}
12498
12499#[derive(Clone, Debug)]
12500struct RecordedChildPolicies {
12501    parent_close_policy: String,
12502    cancellation_policy: String,
12503}
12504
12505fn recorded_activity_cancellation_policy(
12506    events: &[&HistoryEvent],
12507    sequence: u64,
12508) -> Result<String> {
12509    let mut policy: Option<String> = None;
12510    for event in events.iter().filter(|event| {
12511        matches!(
12512            event.event_type.as_str(),
12513            "ActivityScheduled"
12514                | "ActivityStarted"
12515                | "ActivityCompleted"
12516                | "ActivityFailed"
12517                | "ActivityTimedOut"
12518                | "ActivityCancelled"
12519        )
12520    }) {
12521        for source in [Some(&event.payload), event.payload.get("activity")]
12522            .into_iter()
12523            .flatten()
12524        {
12525            let Some(value) = source.get("cancellation_policy") else {
12526                continue;
12527            };
12528            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
12529                value.as_str()
12530            else {
12531                return Err(invalid_recorded_history(
12532                    "invalid_activity_cancellation_policy_history",
12533                    sequence,
12534                    "supported Activity cancellation policy",
12535                    &value.to_string(),
12536                    "Activity history contains an invalid cancellation policy",
12537                ));
12538            };
12539            if let Some(previous) = policy.as_deref() {
12540                if previous != incoming {
12541                    return Err(invalid_recorded_history(
12542                        "activity_cancellation_policy_history_conflict",
12543                        sequence,
12544                        previous,
12545                        incoming,
12546                        "Activity cancellation policy changed between history events",
12547                    ));
12548                }
12549            }
12550            policy = Some(incoming.to_string());
12551        }
12552        policy.get_or_insert_with(|| "try_cancel".to_string());
12553    }
12554    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
12555}
12556
12557fn recorded_child_policy_value<'a>(
12558    payload: &'a Value,
12559    field: &str,
12560    sequence: u64,
12561) -> Result<Option<&'a str>> {
12562    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
12563        return Ok(None);
12564    };
12565    let valid = match (field, value.as_str()) {
12566        (
12567            "parent_close_policy",
12568            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
12569        ) => true,
12570        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
12571            true
12572        }
12573        _ => false,
12574    };
12575    if !valid {
12576        return Err(invalid_recorded_history(
12577            "invalid_child_workflow_policy_history",
12578            sequence,
12579            "supported child workflow policy",
12580            &value.to_string(),
12581            "child workflow history contains an invalid policy",
12582        ));
12583    }
12584    Ok(value.as_str())
12585}
12586
12587fn recorded_child_policies(
12588    events: &[&HistoryEvent],
12589    scheduled: &HistoryEvent,
12590    sequence: u64,
12591) -> Result<RecordedChildPolicies> {
12592    let parent_close_policy =
12593        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
12594            .unwrap_or("abandon")
12595            .to_string();
12596    let cancellation_policy =
12597        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
12598            .unwrap_or("abandon")
12599            .to_string();
12600    for event in events {
12601        for (field, expected) in [
12602            ("parent_close_policy", parent_close_policy.as_str()),
12603            ("cancellation_policy", cancellation_policy.as_str()),
12604        ] {
12605            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
12606                if actual != expected {
12607                    return Err(invalid_recorded_history(
12608                        "child_workflow_policy_history_conflict",
12609                        sequence,
12610                        expected,
12611                        actual,
12612                        "child workflow policy changed between history events",
12613                    ));
12614                }
12615            }
12616        }
12617    }
12618    Ok(RecordedChildPolicies {
12619        parent_close_policy,
12620        cancellation_policy,
12621    })
12622}
12623
12624fn ensure_child_policies_match(
12625    sequence: u64,
12626    recorded: &RecordedChildPolicies,
12627    current: &ChildWorkflowOptions,
12628) -> Result<()> {
12629    for (field, expected, actual) in [
12630        (
12631            "parent_close_policy",
12632            recorded.parent_close_policy.as_str(),
12633            current.parent_close_policy.as_str(),
12634        ),
12635        (
12636            "cancellation_policy",
12637            recorded.cancellation_policy.as_str(),
12638            current.cancellation_policy.as_str(),
12639        ),
12640    ] {
12641        if expected != actual {
12642            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12643                "child_workflow_policy_changed",
12644                Some(sequence),
12645                Some(expected.to_string()),
12646                Some(actual.to_string()),
12647                format!("child workflow {field} changed during replay"),
12648            )));
12649        }
12650    }
12651    Ok(())
12652}
12653
12654#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12655enum RecordedSnapshotValue<T> {
12656    /// Older history did not persist this field, so it cannot constrain replay.
12657    Unknown,
12658    Known(T),
12659}
12660
12661impl<T: PartialEq> RecordedSnapshotValue<T> {
12662    fn matches_current(&self, current: &Self) -> bool {
12663        match self {
12664            Self::Unknown => true,
12665            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12666        }
12667    }
12668}
12669
12670#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12671struct ActivityRetrySnapshot {
12672    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12673    max_attempts: RecordedSnapshotValue<Option<u64>>,
12674    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12675    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12676    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12677    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12678    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12679    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12680}
12681
12682impl ActivityRetrySnapshot {
12683    fn matches_current(&self, current: &Self) -> bool {
12684        self.snapshot_version
12685            .matches_current(&current.snapshot_version)
12686            && self.max_attempts.matches_current(&current.max_attempts)
12687            && self
12688                .backoff_seconds
12689                .matches_current(&current.backoff_seconds)
12690            && self
12691                .start_to_close_timeout
12692                .matches_current(&current.start_to_close_timeout)
12693            && self
12694                .schedule_to_start_timeout
12695                .matches_current(&current.schedule_to_start_timeout)
12696            && self
12697                .schedule_to_close_timeout
12698                .matches_current(&current.schedule_to_close_timeout)
12699            && self
12700                .heartbeat_timeout
12701                .matches_current(&current.heartbeat_timeout)
12702            && self
12703                .non_retryable_error_types
12704                .matches_current(&current.non_retryable_error_types)
12705    }
12706}
12707
12708fn recorded_optional_u64(
12709    object: Option<&serde_json::Map<String, Value>>,
12710    field: &str,
12711) -> RecordedSnapshotValue<Option<u64>> {
12712    match object.and_then(|object| object.get(field)) {
12713        None => RecordedSnapshotValue::Unknown,
12714        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12715        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12716    }
12717}
12718
12719fn recorded_optional_string(
12720    object: &serde_json::Map<String, Value>,
12721    field: &str,
12722) -> RecordedSnapshotValue<Option<String>> {
12723    match object.get(field) {
12724        None => RecordedSnapshotValue::Unknown,
12725        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12726        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12727    }
12728}
12729
12730fn recorded_activity_execution_mode(
12731    events: &[&HistoryEvent],
12732    sequence: u64,
12733) -> Result<RecordedSnapshotValue<Option<String>>> {
12734    let mut recorded = RecordedSnapshotValue::Unknown;
12735    for event in events {
12736        for object in [
12737            event.payload.as_object(),
12738            event.payload.get("activity").and_then(Value::as_object),
12739        ]
12740        .into_iter()
12741        .flatten()
12742        {
12743            let mode = match object.get("execution_mode") {
12744                None => None,
12745                Some(Value::Null) => Some(None),
12746                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12747                Some(_) => {
12748                    return Err(invalid_recorded_history(
12749                        "activity_execution_mode_invalid",
12750                        sequence,
12751                        "null or a non-empty execution mode",
12752                        "invalid execution_mode",
12753                        "activity history contains an invalid execution mode",
12754                    ))
12755                }
12756            };
12757            let legacy_mode = match object.get("local_activity") {
12758                None => None,
12759                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12760                Some(_) => {
12761                    return Err(invalid_recorded_history(
12762                        "activity_execution_mode_invalid",
12763                        sequence,
12764                        "boolean local_activity",
12765                        "invalid local_activity",
12766                        "activity history contains an invalid local-activity marker",
12767                    ))
12768                }
12769            };
12770            for mode in [mode, legacy_mode].into_iter().flatten() {
12771                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12772                {
12773                    return Err(invalid_recorded_history(
12774                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12775                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12776                    ));
12777                }
12778                recorded = RecordedSnapshotValue::Known(mode);
12779            }
12780        }
12781    }
12782    Ok(recorded)
12783}
12784
12785fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12786    let policy = policy.and_then(Value::as_object);
12787    let backoff_seconds = policy
12788        .and_then(|policy| policy.get("backoff_seconds"))
12789        .and_then(Value::as_array)
12790        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12791        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12792    let mut non_retryable_error_types = Vec::new();
12793    for error_type in policy
12794        .and_then(|policy| policy.get("non_retryable_error_types"))
12795        .and_then(Value::as_array)
12796        .into_iter()
12797        .flatten()
12798        .filter_map(Value::as_str)
12799        .map(str::trim)
12800        .filter(|error_type| !error_type.is_empty())
12801    {
12802        if !non_retryable_error_types
12803            .iter()
12804            .any(|recorded| recorded == error_type)
12805        {
12806            non_retryable_error_types.push(error_type.to_string());
12807        }
12808    }
12809
12810    ActivityRetrySnapshot {
12811        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12812        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12813        backoff_seconds,
12814        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12815        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12816        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12817        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12818        non_retryable_error_types: if policy
12819            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12820        {
12821            RecordedSnapshotValue::Known(non_retryable_error_types)
12822        } else {
12823            RecordedSnapshotValue::Unknown
12824        },
12825    }
12826}
12827
12828fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12829    let policy = options.retry_policy.as_ref();
12830    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12831        Some(Value::Null) => None,
12832        Some(value) => value_as_u64(value),
12833        None => Some(1),
12834    };
12835    let backoff_seconds = policy
12836        .and_then(|policy| policy.get("backoff_seconds"))
12837        .and_then(Value::as_array)
12838        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12839        .unwrap_or_default();
12840    let non_retryable_error_types = policy
12841        .and_then(|policy| policy.get("non_retryable_error_types"))
12842        .and_then(Value::as_array)
12843        .into_iter()
12844        .flatten()
12845        .filter_map(Value::as_str)
12846        .map(str::to_string)
12847        .collect();
12848
12849    ActivityRetrySnapshot {
12850        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12851        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12852        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12853        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12854        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12855        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12856        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12857        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12858    }
12859}
12860
12861fn activity_options_description(options: &RecordedActivityOptions) -> String {
12862    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12863}
12864
12865impl RecordedCommand {
12866    fn sequence(&self) -> u64 {
12867        match self {
12868            Self::CancellationGroup { sequence, .. }
12869            | Self::CancellationScope { sequence, .. }
12870            | Self::CancellationBoundary { sequence, .. }
12871            | Self::Activity { sequence, .. }
12872            | Self::Timer { sequence, .. }
12873            | Self::ChildWorkflow { sequence, .. }
12874            | Self::SignalWait { sequence, .. }
12875            | Self::ConditionWait { sequence, .. }
12876            | Self::SearchAttributes { sequence, .. }
12877            | Self::SideEffect { sequence, .. }
12878            | Self::VersionMarker { sequence, .. }
12879            | Self::Memo { sequence, .. } => *sequence,
12880            Self::ServiceOperation { sequence, .. } => *sequence,
12881        }
12882    }
12883
12884    fn shape(&self) -> &'static str {
12885        match self {
12886            Self::CancellationScope { .. } => "cancellation scope",
12887            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12888                "cooperative cancellation"
12889            }
12890            Self::Activity { .. } => "activity",
12891            Self::Timer { .. } => "timer",
12892            Self::ChildWorkflow { .. } => "child workflow",
12893            Self::SignalWait { .. } => "signal wait",
12894            Self::ConditionWait { .. } => "condition wait",
12895            Self::SearchAttributes { .. } => "search-attribute update",
12896            Self::SideEffect { .. } => "side effect",
12897            Self::VersionMarker { .. } => "version marker",
12898            Self::Memo { .. } => "memo upsert",
12899            Self::ServiceOperation { .. } => "service operation",
12900        }
12901    }
12902}
12903
12904fn ensure_version_supported(
12905    change_id: &str,
12906    version: i32,
12907    min_supported: i32,
12908    max_supported: i32,
12909    sequence: u64,
12910) -> Result<()> {
12911    if (min_supported..=max_supported).contains(&version) {
12912        return Ok(());
12913    }
12914    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12915        "version_marker_incompatible_range",
12916        (sequence != 0).then_some(sequence),
12917        Some(format!("{min_supported}..={max_supported}")),
12918        Some(format!("{change_id}:{version}")),
12919        "recorded workflow version is outside the range supported by current code",
12920    )))
12921}
12922
12923#[derive(Clone, Debug)]
12924struct ResumeSignal {
12925    signal_name: String,
12926    arguments: Vec<AvroValue>,
12927}
12928
12929const MAX_PARALLEL_OPERATIONS: usize = 1000;
12930
12931fn parallel_group_prefix(kind: &str) -> &'static str {
12932    match kind {
12933        "activity" => "parallel-activities",
12934        "child" => "parallel-children",
12935        "timer" => "parallel-timers",
12936        _ => "parallel-calls",
12937    }
12938}
12939
12940fn parallel_group_entry(
12941    base_sequence: u64,
12942    size: usize,
12943    index: usize,
12944    kind: &str,
12945) -> ParallelGroupMetadata {
12946    ParallelGroupMetadata {
12947        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12948        parallel_group_kind: kind.to_string(),
12949        parallel_group_base_sequence: base_sequence,
12950        parallel_group_size: size,
12951        parallel_group_index: index,
12952        parallel_group_mode: None,
12953        selection_member_key: None,
12954        selection_member_index: None,
12955        selection_member_base_sequence: None,
12956        selection_member_size: None,
12957        selection_member_kind: None,
12958    }
12959}
12960
12961struct SelectionMemberMetadata {
12962    key: SelectionKey,
12963    index: usize,
12964    base_sequence: u64,
12965    size: usize,
12966    kind: String,
12967}
12968
12969fn selection_group_entry(
12970    base_sequence: u64,
12971    size: usize,
12972    index: usize,
12973    kind: &str,
12974    member: &SelectionMemberMetadata,
12975) -> ParallelGroupMetadata {
12976    ParallelGroupMetadata {
12977        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
12978        parallel_group_kind: kind.to_string(),
12979        parallel_group_base_sequence: base_sequence,
12980        parallel_group_size: size,
12981        parallel_group_index: index,
12982        parallel_group_mode: Some("select".to_string()),
12983        selection_member_key: Some(member.key.clone()),
12984        selection_member_index: Some(member.index),
12985        selection_member_base_sequence: Some(member.base_sequence),
12986        selection_member_size: Some(member.size),
12987        selection_member_kind: Some(member.kind.clone()),
12988    }
12989}
12990
12991fn apply_parallel_group_path(
12992    command: &mut serde_json::Map<String, Value>,
12993    path: &[ParallelGroupMetadata],
12994) {
12995    let Some(inner) = path.last() else {
12996        return;
12997    };
12998    command.insert(
12999        "parallel_group_id".to_string(),
13000        json!(inner.parallel_group_id),
13001    );
13002    command.insert(
13003        "parallel_group_kind".to_string(),
13004        json!(inner.parallel_group_kind),
13005    );
13006    command.insert(
13007        "parallel_group_base_sequence".to_string(),
13008        json!(inner.parallel_group_base_sequence),
13009    );
13010    command.insert(
13011        "parallel_group_size".to_string(),
13012        json!(inner.parallel_group_size),
13013    );
13014    command.insert(
13015        "parallel_group_index".to_string(),
13016        json!(inner.parallel_group_index),
13017    );
13018    if let Some(mode) = &inner.parallel_group_mode {
13019        command.insert("parallel_group_mode".to_string(), json!(mode));
13020    }
13021    if let Some(key) = &inner.selection_member_key {
13022        command.insert("selection_member_key".to_string(), json!(key));
13023    }
13024    if let Some(index) = inner.selection_member_index {
13025        command.insert("selection_member_index".to_string(), json!(index));
13026    }
13027    if let Some(base_sequence) = inner.selection_member_base_sequence {
13028        command.insert(
13029            "selection_member_base_sequence".to_string(),
13030            json!(base_sequence),
13031        );
13032    }
13033    if let Some(size) = inner.selection_member_size {
13034        command.insert("selection_member_size".to_string(), json!(size));
13035    }
13036    if let Some(kind) = &inner.selection_member_kind {
13037        command.insert("selection_member_kind".to_string(), json!(kind));
13038    }
13039    command.insert("parallel_group_path".to_string(), json!(path));
13040}
13041
13042fn ensure_parallel_path_matches(
13043    sequence: u64,
13044    recorded: Option<&[ParallelGroupMetadata]>,
13045    expected: &[ParallelGroupMetadata],
13046) -> Result<()> {
13047    match (recorded, expected.is_empty()) {
13048        (None, true) => Ok(()),
13049        (Some(recorded), false) if recorded == expected => Ok(()),
13050        (None, false) => Err(invalid_recorded_history(
13051            "parallel_group_metadata_missing",
13052            sequence,
13053            &serde_json::to_string(expected).unwrap_or_default(),
13054            "<missing>",
13055            "recorded parallel member is missing its durable group path",
13056        )),
13057        (Some(recorded), true) => Err(invalid_recorded_history(
13058            "parallel_group_shape_mismatch",
13059            sequence,
13060            "sequential command",
13061            &serde_json::to_string(recorded).unwrap_or_default(),
13062            "recorded command belonged to a parallel group but current code schedules it sequentially",
13063        )),
13064        (Some(recorded), false) => Err(invalid_recorded_history(
13065            "parallel_group_shape_mismatch",
13066            sequence,
13067            &serde_json::to_string(recorded).unwrap_or_default(),
13068            &serde_json::to_string(expected).unwrap_or_default(),
13069            "recorded parallel-group identity or path changed during replay",
13070        )),
13071    }
13072}
13073
13074#[derive(Clone, Debug)]
13075enum ParallelShape {
13076    Leaf,
13077    Group(Vec<ParallelShape>),
13078}
13079
13080struct ParallelDescriptor {
13081    operation: ParallelOperation,
13082    offset: usize,
13083    member_path: Vec<usize>,
13084    group_path: Vec<ParallelGroupMetadata>,
13085}
13086
13087fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13088    operations
13089        .iter()
13090        .map(|operation| match operation {
13091            ParallelOperation::Group(children) => parallel_leaf_count(children),
13092            _ => 1,
13093        })
13094        .sum()
13095}
13096
13097fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13098    match operation {
13099        ParallelOperation::Activity { .. } => Some("activity"),
13100        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13101        ParallelOperation::Timer(_) => Some("timer"),
13102        ParallelOperation::Signal(_) => Some("signal"),
13103        ParallelOperation::Condition { .. } => Some("condition"),
13104        ParallelOperation::Group(children) => parallel_group_kind(children),
13105    }
13106}
13107
13108fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13109    let mut kind = None;
13110    for operation in operations {
13111        let Some(operation_kind) = parallel_operation_kind(operation) else {
13112            continue;
13113        };
13114        match kind {
13115            None => kind = Some(operation_kind),
13116            Some(current) if current == operation_kind => {}
13117            Some(_) => return Some("mixed"),
13118        }
13119    }
13120    kind
13121}
13122
13123fn validate_parallel_operations(
13124    operations: &[ParallelOperation],
13125    member_path: &mut Vec<usize>,
13126    root: bool,
13127) -> Result<()> {
13128    let leaves = parallel_leaf_count(operations);
13129    if leaves > MAX_PARALLEL_OPERATIONS {
13130        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13131            reason: "fan_out_limit_exceeded",
13132            member_path: member_path.clone(),
13133            message: format!(
13134                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13135            ),
13136        }));
13137    }
13138    if !root && operations.is_empty() {
13139        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13140            reason: "nested_group_empty",
13141            member_path: member_path.clone(),
13142            message: "a nested group must contain at least one durable leaf".to_string(),
13143        }));
13144    }
13145
13146    for (index, operation) in operations.iter().enumerate() {
13147        member_path.push(index);
13148        match operation {
13149            ParallelOperation::Activity {
13150                options, arguments, ..
13151            } => {
13152                options
13153                    .validate()
13154                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13155                if let Err(error) = arguments {
13156                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13157                        reason: "arguments_invalid",
13158                        member_path: member_path.clone(),
13159                        message: error.to_string(),
13160                    }));
13161                }
13162            }
13163            ParallelOperation::ChildWorkflow {
13164                options, arguments, ..
13165            } => {
13166                validate_parallel_child_options(options)?;
13167                if let Err(error) = arguments {
13168                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13169                        reason: "arguments_invalid",
13170                        member_path: member_path.clone(),
13171                        message: error.to_string(),
13172                    }));
13173                }
13174            }
13175            ParallelOperation::Timer(duration)
13176                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13177            {
13178                return Err(Error::TimerDurationOverflow);
13179            }
13180            ParallelOperation::Timer(_) => {}
13181            ParallelOperation::Signal(signal_name) => {
13182                validate_user_signal_name(signal_name)?;
13183                if signal_name.trim().is_empty() {
13184                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13185                        reason: "signal_name_empty",
13186                        member_path: member_path.clone(),
13187                        message: "signal wait name must not be empty".to_string(),
13188                    }));
13189                }
13190            }
13191            ParallelOperation::Condition { options, .. } => {
13192                options.validate()?;
13193            }
13194            ParallelOperation::Group(children) => {
13195                validate_parallel_operations(children, member_path, false)?;
13196            }
13197        }
13198        member_path.pop();
13199    }
13200    Ok(())
13201}
13202
13203fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13204    if options.task_queue.trim().is_empty() {
13205        return Err(Error::InvalidChildWorkflowOptions(
13206            "task_queue must not be empty".to_string(),
13207        ));
13208    }
13209    for (name, value) in [
13210        (
13211            "execution_timeout_seconds",
13212            options.execution_timeout_seconds,
13213        ),
13214        ("run_timeout_seconds", options.run_timeout_seconds),
13215    ] {
13216        if value == Some(0) {
13217            return Err(Error::InvalidChildWorkflowOptions(format!(
13218                "{name} must be at least 1"
13219            )));
13220        }
13221    }
13222    if options
13223        .retry_policy
13224        .as_ref()
13225        .is_some_and(|policy| policy.max_attempts == Some(0))
13226    {
13227        return Err(Error::InvalidChildWorkflowOptions(
13228            "retry_policy.max_attempts must be at least 1".to_string(),
13229        ));
13230    }
13231    Ok(())
13232}
13233
13234fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13235    ParallelShape::Group(
13236        operations
13237            .iter()
13238            .map(|operation| match operation {
13239                ParallelOperation::Group(children) => parallel_shape(children),
13240                _ => ParallelShape::Leaf,
13241            })
13242            .collect(),
13243    )
13244}
13245
13246fn parallel_descriptors(
13247    operations: Vec<ParallelOperation>,
13248    base_sequence: u64,
13249) -> Result<Vec<ParallelDescriptor>> {
13250    let size = parallel_leaf_count(&operations);
13251    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13252    let mut descriptors = Vec::with_capacity(size);
13253    let mut cursor = 0;
13254
13255    for (index, operation) in operations.into_iter().enumerate() {
13256        match operation {
13257            ParallelOperation::Group(children) => {
13258                let child_base = base_sequence
13259                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13260                    .ok_or(Error::TimerDurationOverflow)?;
13261                for mut descriptor in parallel_descriptors(children, child_base)? {
13262                    let outer_index = cursor + descriptor.offset;
13263                    descriptor.group_path.insert(
13264                        0,
13265                        parallel_group_entry(base_sequence, size, outer_index, kind),
13266                    );
13267                    descriptor.member_path.insert(0, index);
13268                    descriptor.offset = outer_index;
13269                    descriptors.push(descriptor);
13270                }
13271                cursor = descriptors.len();
13272            }
13273            operation => {
13274                descriptors.push(ParallelDescriptor {
13275                    operation,
13276                    offset: cursor,
13277                    member_path: vec![index],
13278                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13279                });
13280                cursor += 1;
13281            }
13282        }
13283    }
13284    Ok(descriptors)
13285}
13286
13287enum ParallelLeafCall {
13288    Activity(ActivityCall),
13289    ChildWorkflow(ChildWorkflowCall),
13290    Timer(TimerCall),
13291    Signal(SignalCall),
13292    Condition(ConditionWaitCall),
13293}
13294
13295fn parallel_leaf_call(
13296    ctx: &WorkflowContext,
13297    operation: ParallelOperation,
13298    parallel_group_path: Vec<ParallelGroupMetadata>,
13299) -> ParallelLeafCall {
13300    match operation {
13301        ParallelOperation::Activity {
13302            activity_type,
13303            options,
13304            arguments,
13305        } => ParallelLeafCall::Activity(ActivityCall {
13306            ctx: ctx.clone(),
13307            activity_type,
13308            options,
13309            worker_session: None,
13310            args: Some(arguments),
13311            scheduled: false,
13312            local: false,
13313            local_result: None,
13314            parallel_group_path,
13315        }),
13316        ParallelOperation::ChildWorkflow {
13317            workflow_type,
13318            options,
13319            arguments,
13320        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13321            ctx: ctx.clone(),
13322            workflow_type,
13323            options,
13324            args: Some(arguments),
13325            scheduled: false,
13326            matched_pending: false,
13327            parallel_group_path,
13328        }),
13329        ParallelOperation::Timer(duration) => {
13330            let delay_seconds = duration
13331                .as_secs()
13332                .checked_add(u64::from(duration.subsec_nanos() > 0));
13333            ParallelLeafCall::Timer(TimerCall {
13334                ctx: ctx.clone(),
13335                delay_seconds,
13336                scheduled: false,
13337                matched_pending: false,
13338                parallel_group_path,
13339            })
13340        }
13341        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
13342            ctx: ctx.clone(),
13343            signal_name,
13344            runtime_reserved_allowed: false,
13345            opened_wait: false,
13346            matched_pending: false,
13347            parallel_group_path,
13348        }),
13349        ParallelOperation::Condition { options, predicate } => {
13350            ParallelLeafCall::Condition(ConditionWaitCall {
13351                ctx: ctx.clone(),
13352                options,
13353                predicate,
13354                occurrence_id: None,
13355                opened_wait: false,
13356                parallel_group_path,
13357            })
13358        }
13359        ParallelOperation::Group(_) => {
13360            unreachable!("parallel descriptors contain only durable leaves")
13361        }
13362    }
13363}
13364
13365impl ParallelLeafCall {
13366    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
13367        match self {
13368            Self::Activity(call) => Pin::new(call)
13369                .poll_avro_value(cx)
13370                .map_ok(ParallelAvroResult::Activity),
13371            Self::ChildWorkflow(call) => Pin::new(call)
13372                .poll_avro_value(cx)
13373                .map_ok(ParallelAvroResult::ChildWorkflow),
13374            Self::Timer(call) => Pin::new(call)
13375                .poll(cx)
13376                .map_ok(|()| ParallelAvroResult::Timer),
13377            Self::Signal(call) => Pin::new(call)
13378                .poll_avro_value(cx)
13379                .map_ok(ParallelAvroResult::Signal),
13380            Self::Condition(call) => Pin::new(call)
13381                .poll(cx)
13382                .map_ok(ParallelAvroResult::Condition),
13383        }
13384    }
13385}
13386
13387struct ParallelLeaf {
13388    call: ParallelLeafCall,
13389    sequence: u64,
13390    member_path: Vec<usize>,
13391    group_path: Vec<ParallelGroupMetadata>,
13392    result: Option<ParallelAvroResult>,
13393}
13394
13395/// Future returned by [`WorkflowContext::parallel`].
13396pub struct ParallelCall {
13397    ctx: WorkflowContext,
13398    operations: Option<Vec<ParallelOperation>>,
13399    shape: Option<ParallelShape>,
13400    leaves: Vec<ParallelLeaf>,
13401    pending_scope_delivery: bool,
13402    worker_session: Option<WorkerSessionOptions>,
13403}
13404
13405impl ParallelCall {
13406    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
13407        Self {
13408            ctx,
13409            operations: Some(operations),
13410            shape: None,
13411            leaves: Vec::new(),
13412            pending_scope_delivery: false,
13413            worker_session: None,
13414        }
13415    }
13416
13417    fn initialize(&mut self) -> Result<()> {
13418        if let Some(session) = &self.worker_session {
13419            session.to_wire()?;
13420        }
13421        let operations = self.operations.take().unwrap_or_default();
13422        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
13423        self.shape = Some(parallel_shape(&operations));
13424        if operations.is_empty() {
13425            return Ok(());
13426        }
13427
13428        let base_sequence = {
13429            let state = self
13430                .ctx
13431                .state
13432                .lock()
13433                .map_err(|_| Error::WorkflowStatePoisoned)?;
13434            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13435                recorded.sequence()
13436            } else {
13437                let last = state
13438                    .recorded_commands
13439                    .last()
13440                    .map(RecordedCommand::sequence)
13441                    .unwrap_or(0);
13442                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13443                    .and_then(|sequence| sequence.checked_add(1))
13444                    .ok_or_else(|| {
13445                        Error::InvalidParallelGroup(ParallelGroupError {
13446                            reason: "sequence_overflow",
13447                            member_path: Vec::new(),
13448                            message: "parallel group sequence identity overflowed u64".to_string(),
13449                        })
13450                    })?
13451            }
13452        };
13453
13454        let descriptors = parallel_descriptors(operations, base_sequence)?;
13455        {
13456            let mut state = self
13457                .ctx
13458                .state
13459                .lock()
13460                .map_err(|_| Error::WorkflowStatePoisoned)?;
13461            let cursor = state.command_cursor;
13462            self.ctx.validate_scope_membership(&mut state, cursor)?;
13463            if state.prepare_parallel_scope_cancellation(&descriptors)? {
13464                self.pending_scope_delivery = true;
13465                return Ok(());
13466            }
13467            state.expand_cancellation_group(&descriptors)?;
13468            state.prepare_group_cancellation(&descriptors)?;
13469        }
13470        self.leaves = descriptors
13471            .into_iter()
13472            .map(|descriptor| {
13473                let mut call = parallel_leaf_call(
13474                    &self.ctx,
13475                    descriptor.operation,
13476                    descriptor.group_path.clone(),
13477                );
13478                if let (Some(session), ParallelLeafCall::Activity(activity)) =
13479                    (&self.worker_session, &mut call)
13480                {
13481                    activity.worker_session = Some(session.clone());
13482                }
13483                ParallelLeaf {
13484                    call,
13485                    sequence: base_sequence + descriptor.offset as u64,
13486                    member_path: descriptor.member_path,
13487                    group_path: descriptor.group_path,
13488                    result: None,
13489                }
13490            })
13491            .collect();
13492        Ok(())
13493    }
13494
13495    fn poll_avro_value(
13496        mut self: Pin<&mut Self>,
13497        cx: &mut TaskContext<'_>,
13498    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
13499        if self.operations.is_some() {
13500            if let Err(error) = self.initialize() {
13501                return Poll::Ready(Err(error));
13502            }
13503        }
13504        if self.pending_scope_delivery {
13505            return Poll::Pending;
13506        }
13507        if self.leaves.is_empty() {
13508            return Poll::Ready(Ok(Vec::new()));
13509        }
13510
13511        let mut failures = Vec::new();
13512        let mut pending = false;
13513        for (index, leaf) in self.leaves.iter_mut().enumerate() {
13514            if leaf.result.is_some() {
13515                continue;
13516            }
13517            match leaf.call.poll_avro_value(cx) {
13518                Poll::Ready(Ok(result)) => leaf.result = Some(result),
13519                Poll::Ready(Err(error)) => failures.push((index, error)),
13520                Poll::Pending => pending = true,
13521            }
13522        }
13523
13524        if !failures.is_empty() {
13525            if let Some(position) = failures
13526                .iter()
13527                .position(|(_, error)| workflow_task_integrity_error(error))
13528            {
13529                return Poll::Ready(Err(failures.remove(position).1));
13530            }
13531            if self
13532                .ctx
13533                .state
13534                .lock()
13535                .map_err(|_| Error::WorkflowStatePoisoned)?
13536                .cancellation_delivery_intent
13537                .is_some()
13538            {
13539                return Poll::Pending;
13540            }
13541            if let Some(position) = failures
13542                .iter()
13543                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
13544            {
13545                return Poll::Ready(Err(failures.remove(position).1));
13546            }
13547            failures.sort_by_key(|(index, _)| *index);
13548            let (failed_index, cause) = failures.remove(0);
13549            let failed = &self.leaves[failed_index];
13550            let completed = self
13551                .leaves
13552                .iter()
13553                .filter_map(|leaf| {
13554                    leaf.result
13555                        .clone()
13556                        .and_then(|result| result.into_json_result().ok())
13557                        .map(|result| ParallelCompletion {
13558                            member_path: leaf.member_path.clone(),
13559                            result,
13560                        })
13561                })
13562                .collect();
13563            let group_id = failed
13564                .group_path
13565                .first()
13566                .map(|entry| entry.parallel_group_id.clone())
13567                .unwrap_or_default();
13568            let sequences = self
13569                .leaves
13570                .iter()
13571                .map(|leaf| leaf.sequence)
13572                .collect::<Vec<_>>();
13573            self.ctx
13574                .state
13575                .lock()
13576                .map_err(|_| Error::WorkflowStatePoisoned)?
13577                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
13578            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
13579                group_id,
13580                member_path: failed.member_path.clone(),
13581                group_path: failed.group_path.clone(),
13582                completed,
13583                cause: Box::new(cause),
13584            })));
13585        }
13586        if pending
13587            || self
13588                .ctx
13589                .state
13590                .lock()
13591                .map_err(|_| Error::WorkflowStatePoisoned)?
13592                .cancellation_delivery_intent
13593                .is_some()
13594        {
13595            return Poll::Pending;
13596        }
13597
13598        let mut flat_results = self
13599            .leaves
13600            .iter_mut()
13601            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
13602            .collect::<Vec<_>>()
13603            .into_iter();
13604        let results = parallel_results_for_shape(
13605            self.shape.as_ref().expect("initialized parallel shape"),
13606            &mut flat_results,
13607        );
13608        let sequences = self
13609            .leaves
13610            .iter()
13611            .map(|leaf| leaf.sequence)
13612            .collect::<Vec<_>>();
13613        self.ctx
13614            .state
13615            .lock()
13616            .map_err(|_| Error::WorkflowStatePoisoned)?
13617            .advance_cancellation_sequences(&sequences, None);
13618        Poll::Ready(Ok(match results {
13619            ParallelAvroResult::Group(results) => results,
13620            ParallelAvroResult::Activity(_)
13621            | ParallelAvroResult::ChildWorkflow(_)
13622            | ParallelAvroResult::Timer
13623            | ParallelAvroResult::Signal(_)
13624            | ParallelAvroResult::Condition(_) => {
13625                unreachable!("root parallel shape is a group")
13626            }
13627        }))
13628    }
13629}
13630
13631fn parallel_results_for_shape(
13632    shape: &ParallelShape,
13633    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13634) -> ParallelAvroResult {
13635    match shape {
13636        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13637        ParallelShape::Group(children) => ParallelAvroResult::Group(
13638            children
13639                .iter()
13640                .map(|child| parallel_results_for_shape(child, flat_results))
13641                .collect(),
13642        ),
13643    }
13644}
13645
13646impl Future for ParallelCall {
13647    type Output = Result<Vec<ParallelResult>>;
13648
13649    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13650        self.poll_avro_value(cx)
13651            .map_ok(|results| {
13652                results
13653                    .into_iter()
13654                    .map(ParallelAvroResult::into_json_result)
13655                    .collect::<Result<Vec<_>>>()
13656            })
13657            .map_ok(|result| result)
13658            .flatten_result()
13659    }
13660}
13661
13662#[derive(Clone, Debug)]
13663struct SelectionMemberPlan {
13664    key: SelectionKey,
13665    index: usize,
13666    base_sequence: u64,
13667    size: usize,
13668    kind: String,
13669    shape: ParallelShape,
13670    leaf_start: usize,
13671}
13672
13673fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13674    match operation {
13675        ParallelOperation::Activity { .. } => "activity",
13676        ParallelOperation::ChildWorkflow { .. } => "child",
13677        ParallelOperation::Timer(_) => "timer",
13678        ParallelOperation::Signal(_) => "signal",
13679        ParallelOperation::Condition { .. } => "condition",
13680        ParallelOperation::Group(_) => "group",
13681    }
13682}
13683
13684fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13685    match operation {
13686        ParallelOperation::Group(children) => parallel_shape(children),
13687        _ => ParallelShape::Leaf,
13688    }
13689}
13690
13691fn selection_descriptors(
13692    operations: Vec<(SelectionKey, ParallelOperation)>,
13693    base_sequence: u64,
13694) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13695    if operations.is_empty() {
13696        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13697            reason: "selection_empty",
13698            member_path: Vec::new(),
13699            message: "durable selection requires at least one operation".to_string(),
13700        }));
13701    }
13702    let operation_refs = operations
13703        .iter()
13704        .map(|(_, operation)| operation)
13705        .collect::<Vec<_>>();
13706    let total_size = operation_refs
13707        .iter()
13708        .map(|operation| match operation {
13709            ParallelOperation::Group(children) => parallel_leaf_count(children),
13710            _ => 1,
13711        })
13712        .sum::<usize>();
13713    if total_size > MAX_PARALLEL_OPERATIONS {
13714        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13715            reason: "fan_out_limit_exceeded",
13716            member_path: Vec::new(),
13717            message: format!(
13718                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13719            ),
13720        }));
13721    }
13722    let group_kind = {
13723        let mut kind = None;
13724        for operation in &operation_refs {
13725            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13726            match kind {
13727                None => kind = Some(operation_kind),
13728                Some(current) if current == operation_kind => {}
13729                Some(_) => {
13730                    kind = Some("mixed");
13731                    break;
13732                }
13733            }
13734        }
13735        kind.unwrap_or("mixed")
13736    };
13737
13738    let mut descriptors = Vec::with_capacity(total_size);
13739    let mut members = Vec::with_capacity(operations.len());
13740    let mut cursor = 0usize;
13741    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13742    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13743        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13744            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13745                reason: "selection_key_invalid",
13746                member_path: vec![member_index],
13747                message: "selection member keys must be non-empty strings or non-negative integers"
13748                    .to_string(),
13749            }));
13750        }
13751        if seen_keys.contains(&key) {
13752            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13753                reason: "selection_key_duplicate",
13754                member_path: vec![member_index],
13755                message: format!("selection member key {key:?} is duplicated"),
13756            }));
13757        }
13758        seen_keys.push(key.clone());
13759        let member_size = match &operation {
13760            ParallelOperation::Group(children) => parallel_leaf_count(children),
13761            _ => 1,
13762        };
13763        if member_size == 0 {
13764            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13765                reason: "selection_member_empty",
13766                member_path: vec![member_index],
13767                message: "a selection member must contain at least one durable leaf".to_string(),
13768            }));
13769        }
13770        let member_base = base_sequence
13771            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13772            .ok_or(Error::TimerDurationOverflow)?;
13773        let member_kind = selection_operation_kind(&operation).to_string();
13774        let member_shape = selection_operation_shape(&operation);
13775        let leaf_start = descriptors.len();
13776        match operation {
13777            ParallelOperation::Group(children) => {
13778                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13779                for mut descriptor in parallel_descriptors(children, member_base)? {
13780                    let flat_index = cursor + descriptor.offset;
13781                    descriptor.group_path.insert(
13782                        0,
13783                        selection_group_entry(
13784                            base_sequence,
13785                            total_size,
13786                            flat_index,
13787                            group_kind,
13788                            &SelectionMemberMetadata {
13789                                key: key.clone(),
13790                                index: member_index,
13791                                base_sequence: member_base,
13792                                size: member_size,
13793                                kind: member_kind.clone(),
13794                            },
13795                        ),
13796                    );
13797                    descriptor.member_path.insert(0, member_index);
13798                    descriptor.offset = flat_index;
13799                    descriptors.push(descriptor);
13800                }
13801            }
13802            operation => {
13803                validate_parallel_operations(
13804                    std::slice::from_ref(&operation),
13805                    &mut Vec::new(),
13806                    true,
13807                )?;
13808                descriptors.push(ParallelDescriptor {
13809                    operation,
13810                    offset: cursor,
13811                    member_path: vec![member_index],
13812                    group_path: vec![selection_group_entry(
13813                        base_sequence,
13814                        total_size,
13815                        cursor,
13816                        group_kind,
13817                        &SelectionMemberMetadata {
13818                            key: key.clone(),
13819                            index: member_index,
13820                            base_sequence: member_base,
13821                            size: member_size,
13822                            kind: member_kind.clone(),
13823                        },
13824                    )],
13825                });
13826            }
13827        }
13828        members.push(SelectionMemberPlan {
13829            key,
13830            index: member_index,
13831            base_sequence: member_base,
13832            size: member_size,
13833            kind: member_kind,
13834            shape: member_shape,
13835            leaf_start,
13836        });
13837        cursor += member_size;
13838    }
13839    Ok((descriptors, members))
13840}
13841
13842struct SelectionLeaf {
13843    call: ParallelLeafCall,
13844    outcome: Option<Result<ParallelAvroResult>>,
13845}
13846
13847/// Stable reference to one member of a durable selection group.
13848#[derive(Clone)]
13849pub struct DurableOperationHandle {
13850    ctx: WorkflowContext,
13851    pub key: SelectionKey,
13852    pub index: usize,
13853    pub kind: String,
13854    pub identity: String,
13855    pub base_sequence: u64,
13856    pub size: usize,
13857    pub selection_group_id: String,
13858    shape: ParallelShape,
13859}
13860
13861impl std::fmt::Debug for DurableOperationHandle {
13862    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13863        formatter
13864            .debug_struct("DurableOperationHandle")
13865            .field("key", &self.key)
13866            .field("index", &self.index)
13867            .field("kind", &self.kind)
13868            .field("identity", &self.identity)
13869            .field("base_sequence", &self.base_sequence)
13870            .field("size", &self.size)
13871            .field("selection_group_id", &self.selection_group_id)
13872            .finish()
13873    }
13874}
13875
13876impl DurableOperationHandle {
13877    /// Await this member after another member has already won the selection.
13878    pub fn await_result(&self) -> DurableOperationAwaitCall {
13879        DurableOperationAwaitCall {
13880            handle: self.clone(),
13881        }
13882    }
13883
13884    /// Request cancellation without affecting siblings. The future resolves
13885    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13886    /// beat a concurrently committed terminal result.
13887    pub fn cancel(&self) -> CancelDurableOperationCall {
13888        CancelDurableOperationCall {
13889            handle: self.clone(),
13890            emitted: false,
13891        }
13892    }
13893}
13894
13895/// The one winner committed for a durable selection group.
13896#[derive(Debug)]
13897pub struct SelectionResult {
13898    pub key: SelectionKey,
13899    pub index: usize,
13900    pub kind: String,
13901    pub identity: String,
13902    pub value: Option<ParallelResult>,
13903    pub failure: Option<Error>,
13904    pub winner: DurableOperationHandle,
13905    pub handles: Vec<DurableOperationHandle>,
13906}
13907
13908impl SelectionResult {
13909    pub fn succeeded(&self) -> bool {
13910        self.failure.is_none()
13911    }
13912
13913    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13914        self.handles.iter().find(|handle| &handle.key == key)
13915    }
13916
13917    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13918        self.handles
13919            .iter()
13920            .filter(|handle| handle.index != self.index)
13921            .collect()
13922    }
13923
13924    pub fn into_result(self) -> Result<ParallelResult> {
13925        match (self.value, self.failure) {
13926            (Some(value), None) => Ok(value),
13927            (_, Some(error)) => Err(error),
13928            _ => Err(Error::WorkerLoop(
13929                "selection result contained neither a value nor a failure".to_string(),
13930            )),
13931        }
13932    }
13933}
13934
13935/// Future returned by [`WorkflowContext::select`].
13936pub struct SelectCall {
13937    ctx: WorkflowContext,
13938    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13939    members: Vec<SelectionMemberPlan>,
13940    leaves: Vec<SelectionLeaf>,
13941    group_id: Option<String>,
13942}
13943
13944impl SelectCall {
13945    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13946        Self {
13947            ctx,
13948            operations: Some(operations),
13949            members: Vec::new(),
13950            leaves: Vec::new(),
13951            group_id: None,
13952        }
13953    }
13954
13955    fn initialize(&mut self) -> Result<()> {
13956        let operations = self.operations.take().unwrap_or_default();
13957        let base_sequence = {
13958            let state = self
13959                .ctx
13960                .state
13961                .lock()
13962                .map_err(|_| Error::WorkflowStatePoisoned)?;
13963            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13964                state.recorded_commands.get(state.command_cursor)
13965            {
13966                *sequence
13967            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13968            {
13969                marker.selection_group_base_sequence
13970            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13971                recorded.sequence()
13972            } else {
13973                let last = state
13974                    .recorded_commands
13975                    .last()
13976                    .map(RecordedCommand::sequence)
13977                    .unwrap_or(0);
13978                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13979                    .and_then(|sequence| sequence.checked_add(1))
13980                    .ok_or(Error::TimerDurationOverflow)?
13981            }
13982        };
13983        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13984        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13985        {
13986            let mut state = self
13987                .ctx
13988                .state
13989                .lock()
13990                .map_err(|_| Error::WorkflowStatePoisoned)?;
13991            state.expand_cancellation_group(&descriptors)?;
13992            state.prepare_group_cancellation(&descriptors)?;
13993        }
13994        self.leaves = descriptors
13995            .into_iter()
13996            .map(|descriptor| SelectionLeaf {
13997                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13998                outcome: None,
13999            })
14000            .collect();
14001        self.members = members;
14002        self.group_id = Some(group_id);
14003        Ok(())
14004    }
14005}
14006
14007impl Future for SelectCall {
14008    type Output = Result<SelectionResult>;
14009
14010    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14011        if self.operations.is_some() {
14012            if let Err(error) = self.initialize() {
14013                return Poll::Ready(Err(error));
14014            }
14015        }
14016
14017        for leaf in &mut self.leaves {
14018            if leaf.outcome.is_some() {
14019                continue;
14020            }
14021            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14022                if outcome
14023                    .as_ref()
14024                    .err()
14025                    .is_some_and(workflow_task_integrity_error)
14026                {
14027                    return Poll::Ready(outcome.map(|_| unreachable!()));
14028                }
14029                leaf.outcome = Some(outcome);
14030            }
14031        }
14032
14033        if self
14034            .ctx
14035            .state
14036            .lock()
14037            .map_err(|_| Error::WorkflowStatePoisoned)?
14038            .cancellation_delivery_intent
14039            .is_some()
14040        {
14041            return Poll::Pending;
14042        }
14043
14044        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14045            matches!(
14046                leaf.outcome,
14047                Some(Err(Error::CooperativeCancellationRequested(_)))
14048            )
14049        }) {
14050            return Poll::Ready(
14051                leaf.outcome
14052                    .take()
14053                    .expect("matched cancellation")
14054                    .map(|_| unreachable!()),
14055            );
14056        }
14057
14058        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14059        let selection_member_range = self
14060            .members
14061            .first()
14062            .map(|member| member.base_sequence)
14063            .zip(self.leaves.len().try_into().ok())
14064            .map(|(base_sequence, size): (u64, u64)| {
14065                base_sequence..base_sequence.saturating_add(size)
14066            });
14067        let marker = {
14068            let mut state = match self.ctx.state.lock() {
14069                Ok(state) => state,
14070                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14071            };
14072            let marker = state
14073                .selection_markers
14074                .get(state.selection_marker_cursor)
14075                .cloned();
14076            if marker.is_none()
14077                && all_members_terminal
14078                && selection_member_range.as_ref().is_some_and(|member_range| {
14079                    state
14080                        .recorded_commands
14081                        .iter()
14082                        .any(|command| member_range.contains(&command.sequence()))
14083                })
14084            {
14085                // Terminal member history can be committed before the server's
14086                // SelectionResolved marker becomes visible to this task. That
14087                // marker is the durable barrier the selection is still waiting
14088                // on, so an otherwise commandless replay remains legitimately
14089                // pending instead of failing as an untracked yield.
14090                state.matched_recorded_pending = true;
14091            }
14092            marker
14093        };
14094        let Some(marker) = marker else {
14095            return Poll::Pending;
14096        };
14097        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14098            || marker.selection_group_size != self.leaves.len()
14099            || self.members.first().map(|member| member.base_sequence)
14100                != Some(marker.selection_group_base_sequence)
14101        {
14102            return Poll::Ready(Err(invalid_recorded_history(
14103                "selection_group_shape_mismatch",
14104                marker.selection_group_base_sequence,
14105                self.group_id
14106                    .as_deref()
14107                    .unwrap_or("initialized selection group"),
14108                &marker.selection_group_id,
14109                "recorded selection group differs from current workflow code",
14110            )));
14111        }
14112        let Some(member_position) = self.members.iter().position(|member| {
14113            member.key == marker.member_key
14114                && member.index == marker.member_index
14115                && member.base_sequence == marker.member_base_sequence
14116                && member.size == marker.member_size
14117                && member.kind == marker.operation_kind
14118        }) else {
14119            return Poll::Ready(Err(invalid_recorded_history(
14120                "selection_member_shape_mismatch",
14121                marker.member_base_sequence,
14122                "winner member matching current workflow code",
14123                &format!("{:?}", marker.member_key),
14124                "recorded selection winner differs from the authored member identity",
14125            )));
14126        };
14127        let member = self.members[member_position].clone();
14128        let (handles, resolution_sequence) = {
14129            let mut state = match self.ctx.state.lock() {
14130                Ok(state) => state,
14131                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14132            };
14133            let identities = self
14134                .members
14135                .iter()
14136                .map(|candidate| {
14137                    selection_operation_identity(
14138                        &state,
14139                        &candidate.kind,
14140                        candidate.base_sequence,
14141                        candidate.size,
14142                    )
14143                })
14144                .collect::<Vec<_>>();
14145            if let Some((position, missing)) = identities
14146                .iter()
14147                .enumerate()
14148                .find(|(_, identity)| identity.is_empty())
14149                .map(|(position, identity)| (position, identity.clone()))
14150            {
14151                let candidate = &self.members[position];
14152                return Poll::Ready(Err(invalid_recorded_history(
14153                    "selection_operation_identity_missing",
14154                    candidate.base_sequence,
14155                    &format!(
14156                        "durable {} resource identity from scheduled/open history",
14157                        candidate.kind
14158                    ),
14159                    &missing,
14160                    "selection member history is missing its canonical durable identity",
14161                )));
14162            }
14163            let expected_winner_identity = &identities[member_position];
14164            let resolution_sequence = match validated_selection_resolution_sequence(
14165                &state,
14166                &marker,
14167                &member,
14168                expected_winner_identity,
14169            ) {
14170                Ok(sequence) => sequence,
14171                Err(error) => return Poll::Ready(Err(error)),
14172            };
14173            let handles = self
14174                .members
14175                .iter()
14176                .zip(identities)
14177                .map(|(member, identity)| DurableOperationHandle {
14178                    ctx: self.ctx.clone(),
14179                    key: member.key.clone(),
14180                    index: member.index,
14181                    kind: member.kind.clone(),
14182                    identity,
14183                    base_sequence: member.base_sequence,
14184                    size: member.size,
14185                    selection_group_id: marker.selection_group_id.clone(),
14186                    shape: member.shape.clone(),
14187                })
14188                .collect::<Vec<_>>();
14189            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14190                return Poll::Ready(Err(error));
14191            }
14192            state.selection_marker_cursor += 1;
14193            (handles, resolution_sequence)
14194        };
14195
14196        let mut winner_failure = None;
14197        let mut flat_results = Vec::with_capacity(member.size);
14198        if marker.outcome == "failed" {
14199            let resolution_offset = match resolution_sequence
14200                .checked_sub(member.base_sequence)
14201                .and_then(|offset| usize::try_from(offset).ok())
14202            {
14203                Some(offset) if offset < member.size => offset,
14204                _ => {
14205                    return Poll::Ready(Err(invalid_recorded_history(
14206                        "selection_resolution_event_mismatch",
14207                        member.base_sequence,
14208                        "failure event within selected member bounds",
14209                        &resolution_sequence.to_string(),
14210                        "selection failure event is outside the authored member",
14211                    )))
14212                }
14213            };
14214            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14215            match leaf.outcome.take() {
14216                Some(Err(error)) => winner_failure = Some(error),
14217                _ => {
14218                    return Poll::Ready(Err(invalid_recorded_history(
14219                        "selection_winner_outcome_mismatch",
14220                        member.base_sequence,
14221                        "exact failed terminal history referenced by SelectionResolved",
14222                        "missing or successful resolution event",
14223                        "selection winner marker disagrees with terminal operation history",
14224                    )))
14225                }
14226            }
14227        } else {
14228            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14229                match leaf.outcome.take() {
14230                    Some(Ok(result)) => flat_results.push(result),
14231                    Some(Err(_)) => {
14232                        return Poll::Ready(Err(invalid_recorded_history(
14233                            "selection_winner_outcome_mismatch",
14234                            member.base_sequence,
14235                            "fully completed nested selection member",
14236                            "failed durable leaf",
14237                            "completed selection winner contains a failed leaf",
14238                        )))
14239                    }
14240                    None => {
14241                        return Poll::Ready(Err(invalid_recorded_history(
14242                            "selection_winner_unresolved",
14243                            member.base_sequence,
14244                            "terminal history for every completed winner leaf",
14245                            "pending member history",
14246                            "completed SelectionResolved member has an unfinished durable barrier",
14247                        )))
14248                    }
14249                }
14250            }
14251        }
14252        let value = if winner_failure.is_none() {
14253            let mut flat_results = flat_results.into_iter();
14254            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14255            match value.into_json_result() {
14256                Ok(value) => Some(value),
14257                Err(error) => return Poll::Ready(Err(error)),
14258            }
14259        } else {
14260            None
14261        };
14262        let winner = handles[member_position].clone();
14263        self.ctx
14264            .state
14265            .lock()
14266            .map_err(|_| Error::WorkflowStatePoisoned)?
14267            .advance_cancellation_selection(&marker.selection_group_id);
14268        Poll::Ready(Ok(SelectionResult {
14269            key: winner.key.clone(),
14270            index: winner.index,
14271            kind: winner.kind.clone(),
14272            identity: winner.identity.clone(),
14273            value,
14274            failure: winner_failure,
14275            winner,
14276            handles,
14277        }))
14278    }
14279}
14280
14281fn selection_operation_identity(
14282    state: &WorkflowState,
14283    kind: &str,
14284    base_sequence: u64,
14285    size: usize,
14286) -> String {
14287    if kind == "group" {
14288        return format!("group:{base_sequence}:{size}");
14289    }
14290    let fields: &[&str] = match kind {
14291        "activity" => &["activity_execution_id"],
14292        "child" => &["child_workflow_run_id"],
14293        "timer" => &["timer_id"],
14294        "signal" => &["signal_wait_id"],
14295        "condition" => &["condition_wait_id"],
14296        _ => &[],
14297    };
14298    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14299        for event in state
14300            .history_events
14301            .iter()
14302            .filter(|event| durable_event_sequence(event) == Some(sequence))
14303        {
14304            for field in fields {
14305                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14306                    if !identity.is_empty() {
14307                        return identity.to_string();
14308                    }
14309                }
14310            }
14311        }
14312    }
14313    String::new()
14314}
14315
14316fn validated_selection_resolution_sequence(
14317    state: &WorkflowState,
14318    marker: &SelectionMarker,
14319    member: &SelectionMemberPlan,
14320    expected_identity: &str,
14321) -> Result<u64> {
14322    if expected_identity.is_empty() {
14323        return Err(invalid_recorded_history(
14324            "selection_operation_identity_missing",
14325            member.base_sequence,
14326            &format!(
14327                "durable {} resource identity from scheduled/open history",
14328                member.kind
14329            ),
14330            "missing operation identity",
14331            "selection member history is missing its canonical durable identity",
14332        ));
14333    }
14334    if marker.operation_identity != expected_identity {
14335        return Err(invalid_recorded_history(
14336            "selection_operation_identity_mismatch",
14337            member.base_sequence,
14338            expected_identity,
14339            &marker.operation_identity,
14340            "selection winner identity does not match durable scheduled/open history",
14341        ));
14342    }
14343
14344    let failure_types = [
14345        "ActivityFailed",
14346        "ActivityCancelled",
14347        "ActivityTimedOut",
14348        "ChildRunFailed",
14349        "ChildRunCancelled",
14350        "ChildRunTerminated",
14351    ];
14352    let success_types = [
14353        "ActivityCompleted",
14354        "ChildRunCompleted",
14355        "TimerFired",
14356        "SignalApplied",
14357        "ConditionWaitSatisfied",
14358        "ConditionWaitTimedOut",
14359    ];
14360    let terminal_types: &[&str] = if marker.outcome == "failed" {
14361        &failure_types
14362    } else {
14363        &success_types
14364    };
14365    let mut candidates = Vec::new();
14366    let member_commands = (member.base_sequence
14367        ..member.base_sequence.saturating_add(member.size as u64))
14368        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
14369        .map(|command| (command.sequence(), command))
14370        .collect::<BTreeMap<_, _>>();
14371    let mut resolved_conditions = BTreeSet::new();
14372    for event in state.history_events.iter() {
14373        let Some(sequence) = durable_event_sequence(event) else {
14374            continue;
14375        };
14376        let Some(command) = member_commands.get(&sequence) else {
14377            continue;
14378        };
14379        if !terminal_types.contains(&event.event_type.as_str()) {
14380            continue;
14381        }
14382        if matches!(command, RecordedCommand::ConditionWait { .. }) {
14383            if !matches!(
14384                event.event_type.as_str(),
14385                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
14386            ) && !(event.event_type == "TimerFired"
14387                && event.payload.get("timer_kind").and_then(Value::as_str)
14388                    == Some("condition_timeout"))
14389            {
14390                continue;
14391            }
14392            if !resolved_conditions.insert(sequence) {
14393                continue;
14394            }
14395        }
14396        let event_id = event
14397            .raw
14398            .get("id")
14399            .or_else(|| event.raw.get("event_id"))
14400            .and_then(Value::as_str)
14401            .filter(|value| !value.is_empty())
14402            .ok_or_else(|| {
14403                invalid_recorded_history(
14404                    "selection_resolution_event_id_missing",
14405                    member.base_sequence,
14406                    "terminal selection history with a durable event id",
14407                    &event.payload.to_string(),
14408                    "selection terminal history cannot be bound to its winner marker",
14409                )
14410            })?;
14411        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
14412    }
14413    let resolution = if marker.outcome == "failed" {
14414        candidates.first()
14415    } else {
14416        candidates.last()
14417    };
14418    let Some((event_id, event_type, sequence)) = resolution else {
14419        return Err(invalid_recorded_history(
14420            "selection_resolution_event_missing",
14421            member.base_sequence,
14422            "terminal history for the selected member",
14423            &format!("{:?}", marker.member_key),
14424            "selection winner marker has no matching durable terminal event",
14425        ));
14426    };
14427    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
14428        return Err(invalid_recorded_history(
14429            "selection_resolution_event_mismatch",
14430            member.base_sequence,
14431            &format!("{event_type}:{event_id}"),
14432            &format!(
14433                "{}:{}",
14434                marker.resolution_event_type, marker.resolution_event_id
14435            ),
14436            "selection winner marker does not reference the event that made its member terminal",
14437        ));
14438    }
14439    Ok(*sequence)
14440}
14441
14442fn selection_member_recorded_command(
14443    state: &WorkflowState,
14444    authored_sequence: u64,
14445) -> Option<&RecordedCommand> {
14446    let original = state
14447        .recorded_commands
14448        .iter()
14449        .find(|command| command.sequence() == authored_sequence)?;
14450    let RecordedCommand::ConditionWait {
14451        occurrence_id,
14452        parallel_group_path: Some(_),
14453        ..
14454    } = original
14455    else {
14456        return Some(original);
14457    };
14458    // Decoding proves each physical reopen has the same authored identity and
14459    // group path after a satisfied predecessor. Only its latest wait can make
14460    // this logical member terminal.
14461    state
14462        .recorded_commands
14463        .iter()
14464        .filter(|command| {
14465            matches!(command, RecordedCommand::ConditionWait {
14466                occurrence_id: candidate, ..
14467            } if candidate == occurrence_id)
14468        })
14469        .max_by_key(|command| command.sequence())
14470}
14471
14472fn recorded_selection_member_outcome(
14473    state: &WorkflowState,
14474    handle: &DurableOperationHandle,
14475) -> Result<Option<ParallelResult>> {
14476    for event in state.history_events.iter() {
14477        let Some(sequence) = durable_event_sequence(event) else {
14478            continue;
14479        };
14480        if sequence < handle.base_sequence
14481            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
14482            || !matches!(
14483                event.event_type.as_str(),
14484                "ActivityFailed"
14485                    | "ActivityCancelled"
14486                    | "ActivityTimedOut"
14487                    | "ChildRunFailed"
14488                    | "ChildRunCancelled"
14489                    | "ChildRunTerminated"
14490            )
14491        {
14492            continue;
14493        }
14494        let Some(command) = state
14495            .recorded_commands
14496            .iter()
14497            .find(|command| command.sequence() == sequence)
14498        else {
14499            continue;
14500        };
14501        match command {
14502            RecordedCommand::Activity {
14503                outcome: Some(Err(failure)),
14504                ..
14505            } => return Err(Error::ActivityFailed(failure.clone())),
14506            RecordedCommand::ChildWorkflow {
14507                outcome: Some(Err(failure)),
14508                ..
14509            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
14510            _ => {}
14511        }
14512    }
14513
14514    let mut results = Vec::with_capacity(handle.size);
14515    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14516        let Some(command) = selection_member_recorded_command(state, sequence) else {
14517            return Ok(None);
14518        };
14519        let result = match command {
14520            RecordedCommand::Activity { outcome, .. } => match outcome {
14521                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
14522                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
14523                None => return Ok(None),
14524            },
14525            RecordedCommand::Timer { fired, .. } => {
14526                if !fired {
14527                    return Ok(None);
14528                }
14529                ParallelAvroResult::Timer
14530            }
14531            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
14532                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
14533                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
14534                None => return Ok(None),
14535            },
14536            RecordedCommand::SignalWait { value, .. } => match value {
14537                Some(value) => ParallelAvroResult::Signal(value.clone()),
14538                None => return Ok(None),
14539            },
14540            RecordedCommand::ConditionWait { result, .. } => match result {
14541                Some(result) => ParallelAvroResult::Condition(*result),
14542                None => return Ok(None),
14543            },
14544            other => {
14545                return Err(command_mismatch(
14546                    other,
14547                    format!("selected {} member", handle.kind),
14548                ))
14549            }
14550        };
14551        results.push(result);
14552    }
14553    let mut results = results.into_iter();
14554    parallel_results_for_shape(&handle.shape, &mut results)
14555        .into_json_result()
14556        .map(Some)
14557}
14558
14559fn recorded_selection_member_is_terminal(
14560    state: &WorkflowState,
14561    handle: &DurableOperationHandle,
14562) -> bool {
14563    let mut completed = 0usize;
14564    let mut all_completed = true;
14565    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14566        let Some(command) = selection_member_recorded_command(state, sequence) else {
14567            all_completed = false;
14568            continue;
14569        };
14570        let terminal = match command {
14571            RecordedCommand::Activity {
14572                outcome: Some(Err(_)),
14573                ..
14574            }
14575            | RecordedCommand::ChildWorkflow {
14576                outcome: Some(Err(_)),
14577                ..
14578            } => return true,
14579            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
14580            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
14581            RecordedCommand::Timer { fired, .. } => *fired,
14582            RecordedCommand::SignalWait { value, .. } => value.is_some(),
14583            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
14584            RecordedCommand::SearchAttributes { .. }
14585            | RecordedCommand::CancellationScope { .. }
14586            | RecordedCommand::SideEffect { .. }
14587            | RecordedCommand::VersionMarker { .. }
14588            | RecordedCommand::Memo { .. }
14589            | RecordedCommand::CancellationBoundary { .. }
14590            | RecordedCommand::CancellationGroup { .. } => false,
14591            RecordedCommand::ServiceOperation { .. } => false,
14592        };
14593        if !terminal {
14594            all_completed = false;
14595            continue;
14596        }
14597        completed += 1;
14598    }
14599    all_completed && completed == handle.size
14600}
14601
14602fn selection_cancellation_for_handle(
14603    state: &WorkflowState,
14604    handle: &DurableOperationHandle,
14605) -> Result<bool> {
14606    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
14607        recorded.selection_group_id == handle.selection_group_id
14608            && recorded.member_base_sequence == handle.base_sequence
14609    }) else {
14610        return Ok(false);
14611    };
14612    validate_selection_cancellation_marker(marker, handle)?;
14613    Ok(true)
14614}
14615
14616fn validate_selection_cancellations_for_handles(
14617    state: &WorkflowState,
14618    handles: &[DurableOperationHandle],
14619) -> Result<()> {
14620    let Some(group_id) = handles
14621        .first()
14622        .map(|handle| handle.selection_group_id.as_str())
14623    else {
14624        return Ok(());
14625    };
14626    for marker in state
14627        .cancelled_selection_members
14628        .iter()
14629        .filter(|marker| marker.selection_group_id == group_id)
14630    {
14631        let Some(handle) = handles
14632            .iter()
14633            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14634        else {
14635            return Err(invalid_recorded_history(
14636                "selection_cancellation_member_mismatch",
14637                marker.member_base_sequence,
14638                "SelectionOperationCancelled matching an authored selection handle",
14639                &format!("{marker:?}"),
14640                "selection cancellation member base does not name an authored member",
14641            ));
14642        };
14643        validate_selection_cancellation_marker(marker, handle)?;
14644    }
14645    Ok(())
14646}
14647
14648fn validate_selection_cancellation_marker(
14649    marker: &SelectionCancellation,
14650    handle: &DurableOperationHandle,
14651) -> Result<()> {
14652    if marker.selection_group_id != handle.selection_group_id
14653        || marker.member_key != handle.key
14654        || marker.member_index != handle.index
14655        || marker.member_base_sequence != handle.base_sequence
14656        || marker.member_size != handle.size
14657        || marker.operation_kind != handle.kind
14658        || marker.operation_identity != handle.identity
14659    {
14660        return Err(invalid_recorded_history(
14661            "selection_cancellation_member_mismatch",
14662            handle.base_sequence,
14663            "SelectionOperationCancelled matching the authored selection handle",
14664            &format!("{marker:?}"),
14665            "selection cancellation history targets different authored member metadata",
14666        ));
14667    }
14668    Ok(())
14669}
14670
14671/// Future returned by [`DurableOperationHandle::await_result`].
14672pub struct DurableOperationAwaitCall {
14673    handle: DurableOperationHandle,
14674}
14675
14676impl Future for DurableOperationAwaitCall {
14677    type Output = Result<ParallelResult>;
14678
14679    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14680        let mut state = match self.handle.ctx.state.lock() {
14681            Ok(state) => state,
14682            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14683        };
14684        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14685            return Poll::Ready(Err(error));
14686        }
14687        match state.prepare_selection_handle_cancellation(&self.handle) {
14688            Ok(true) => return Poll::Pending,
14689            Ok(false) => {}
14690            Err(error) => return Poll::Ready(Err(error)),
14691        }
14692        match selection_cancellation_for_handle(&state, &self.handle) {
14693            Err(error) => return Poll::Ready(Err(error)),
14694            Ok(false) => {}
14695            Ok(true) => {
14696                state.advance_cancellation_receipt(
14697                    &self.handle.selection_group_id,
14698                    self.handle.base_sequence,
14699                );
14700                return Poll::Ready(Err(Error::DurableOperationCancelled(
14701                    DurableOperationCancelled {
14702                        selection_group_id: self.handle.selection_group_id.clone(),
14703                        member_key: self.handle.key.clone(),
14704                        member_index: self.handle.index,
14705                        operation_kind: self.handle.kind.clone(),
14706                        operation_identity: self.handle.identity.clone(),
14707                    },
14708                )));
14709            }
14710        }
14711        match recorded_selection_member_outcome(&state, &self.handle) {
14712            Ok(Some(result)) => {
14713                state.advance_cancellation_handle(&self.handle, false);
14714                Poll::Ready(Ok(result))
14715            }
14716            Ok(None) => Poll::Pending,
14717            Err(error) => {
14718                if !workflow_task_integrity_error(&error) {
14719                    state.advance_cancellation_handle(&self.handle, true);
14720                }
14721                Poll::Ready(Err(error))
14722            }
14723        }
14724    }
14725}
14726
14727fn validate_selection_delivery_handle(
14728    state: &WorkflowState,
14729    handle: &DurableOperationHandle,
14730) -> Result<()> {
14731    let path = state
14732        .recorded_commands
14733        .iter()
14734        .find(|command| command.sequence() == handle.base_sequence)
14735        .and_then(|command| match command {
14736            RecordedCommand::Activity {
14737                parallel_group_path,
14738                ..
14739            }
14740            | RecordedCommand::ChildWorkflow {
14741                parallel_group_path,
14742                ..
14743            }
14744            | RecordedCommand::Timer {
14745                parallel_group_path,
14746                ..
14747            }
14748            | RecordedCommand::SignalWait {
14749                parallel_group_path,
14750                ..
14751            }
14752            | RecordedCommand::ConditionWait {
14753                parallel_group_path,
14754                ..
14755            } => parallel_group_path.as_ref(),
14756            _ => None,
14757        })
14758        .and_then(|path| path.first());
14759    let matches = path.is_some_and(|entry| {
14760        entry.parallel_group_mode.as_deref() == Some("select")
14761            && entry.parallel_group_id == handle.selection_group_id
14762            && entry.selection_member_key.as_ref() == Some(&handle.key)
14763            && entry.selection_member_index == Some(handle.index)
14764            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14765            && entry.selection_member_size == Some(handle.size)
14766            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14767    });
14768    if !matches
14769        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14770            != handle.identity
14771    {
14772        return Err(invalid_recorded_history(
14773            "cooperative_cancellation_call_mismatch",
14774            handle.base_sequence,
14775            "selection handle matching its authored durable identity",
14776            &format!("{handle:?}"),
14777            "selection handle identity or member metadata changed before cancellation replay",
14778        ));
14779    }
14780    Ok(())
14781}
14782
14783/// Future returned by [`DurableOperationHandle::cancel`].
14784pub struct CancelDurableOperationCall {
14785    handle: DurableOperationHandle,
14786    emitted: bool,
14787}
14788
14789impl Future for CancelDurableOperationCall {
14790    type Output = Result<()>;
14791
14792    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14793        let ctx = self.handle.ctx.clone();
14794        let mut state = match ctx.state.lock() {
14795            Ok(state) => state,
14796            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14797        };
14798        match selection_cancellation_for_handle(&state, &self.handle) {
14799            Err(error) => return Poll::Ready(Err(error)),
14800            Ok(true) => {
14801                state.advance_cancellation_receipt(
14802                    &self.handle.selection_group_id,
14803                    self.handle.base_sequence,
14804                );
14805                return Poll::Ready(Ok(()));
14806            }
14807            Ok(false) => {}
14808        }
14809        if recorded_selection_member_is_terminal(&state, &self.handle) {
14810            return Poll::Ready(Ok(()));
14811        }
14812        if !self.emitted {
14813            state.commands.push(json!({
14814                "type": "cancel_selection_operation",
14815                "selection_group_id": self.handle.selection_group_id,
14816                "member_key": self.handle.key,
14817                "member_index": self.handle.index,
14818                "member_base_sequence": self.handle.base_sequence,
14819                "member_size": self.handle.size,
14820                "operation_kind": self.handle.kind,
14821                "operation_identity": self.handle.identity,
14822            }));
14823            self.emitted = true;
14824        }
14825        // Unit completes the request, not the member's outcome. Following
14826        // workflow commands commit atomically with this cancellation request.
14827        // Waiting here would need another workflow task that cancellation
14828        // alone does not create. await_result still requires recorded history.
14829        Poll::Ready(Ok(()))
14830    }
14831}
14832
14833trait PollNestedResultExt<T> {
14834    fn flatten_result(self) -> Poll<Result<T>>;
14835}
14836
14837impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14838    fn flatten_result(self) -> Poll<Result<T>> {
14839        match self {
14840            Poll::Ready(Ok(result)) => Poll::Ready(result),
14841            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14842            Poll::Pending => Poll::Pending,
14843        }
14844    }
14845}
14846
14847struct SagaCompensation {
14848    activity_type: String,
14849    options: ActivityOptions,
14850    arguments: AvroValue,
14851    registration_order: usize,
14852}
14853
14854/// Workflow-local deterministic saga compensation helper.
14855///
14856/// Register each compensation only after its forward step succeeds. Passing
14857/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14858/// reverse registration order after any failure, including cooperative
14859/// cancellation. Each compensation is an ordinary durable activity, so replay,
14860/// duplicate delivery, and worker restart use existing history semantics.
14861pub struct Saga {
14862    ctx: WorkflowContext,
14863    compensations: Vec<SagaCompensation>,
14864}
14865
14866impl Saga {
14867    fn new(ctx: WorkflowContext) -> Self {
14868        Self {
14869            ctx,
14870            compensations: Vec::new(),
14871        }
14872    }
14873
14874    pub fn add_compensation<T: Serialize>(
14875        &mut self,
14876        activity_type: impl Into<String>,
14877        args: T,
14878    ) -> Result<&mut Self> {
14879        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14880    }
14881
14882    pub fn add_compensation_with_options<T: Serialize>(
14883        &mut self,
14884        activity_type: impl Into<String>,
14885        options: ActivityOptions,
14886        args: T,
14887    ) -> Result<&mut Self> {
14888        let activity_type = activity_type.into();
14889        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14890            return Err(Error::Codec(
14891                "saga compensation activity type must be non-empty without surrounding whitespace"
14892                    .to_string(),
14893            ));
14894        }
14895        options.validate().map_err(Error::InvalidActivityOptions)?;
14896        let arguments = AvroValue::from_serialize(&args)?;
14897        let registration_order = self.compensations.len() + 1;
14898        self.compensations.push(SagaCompensation {
14899            activity_type,
14900            options,
14901            arguments,
14902            registration_order,
14903        });
14904        Ok(self)
14905    }
14906
14907    /// Compensate `initiating_failure` and return the failure that must remain.
14908    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14909        let _shield = match self.ctx.cancellation_shield() {
14910            Ok(shield) => shield,
14911            Err(error) => return error,
14912        };
14913        while let Some(compensation) = self.compensations.pop() {
14914            if let Err(compensation_failure) = self
14915                .ctx
14916                .activity_with_options(
14917                    compensation.activity_type.clone(),
14918                    compensation.options,
14919                    compensation.arguments,
14920                )
14921                .await
14922            {
14923                if workflow_task_integrity_error(&compensation_failure) {
14924                    return compensation_failure;
14925                }
14926                return Error::SagaCompensationFailed(SagaCompensationFailure {
14927                    initiating_failure: Box::new(initiating_failure),
14928                    compensation_failure: Box::new(compensation_failure),
14929                    compensation_activity_type: compensation.activity_type,
14930                    compensation_registration_order: compensation.registration_order,
14931                });
14932            }
14933        }
14934        initiating_failure
14935    }
14936
14937    /// Return a successful forward value or compensate and preserve its failure.
14938    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14939        match outcome {
14940            Ok(value) => Ok(value),
14941            Err(error) => Err(self.compensate(error).await),
14942        }
14943    }
14944}
14945
14946pub struct ActivityCall {
14947    ctx: WorkflowContext,
14948    activity_type: String,
14949    options: ActivityOptions,
14950    worker_session: Option<WorkerSessionOptions>,
14951    args: Option<Result<AvroValue>>,
14952    scheduled: bool,
14953    local: bool,
14954    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14955    parallel_group_path: Vec<ParallelGroupMetadata>,
14956}
14957
14958impl ActivityCall {
14959    fn poll_avro_value(
14960        mut self: Pin<&mut Self>,
14961        _cx: &mut TaskContext<'_>,
14962    ) -> Poll<Result<AvroValue>> {
14963        let ctx = self.ctx.clone();
14964        let mut state = match ctx.state.lock() {
14965            Ok(state) => state,
14966            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14967        };
14968
14969        if let Some(result) = &self.local_result {
14970            return match result.lock() {
14971                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14972                    Poll::Ready(result.map_err(Error::ActivityFailed))
14973                }),
14974                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14975            };
14976        }
14977        if self.scheduled {
14978            return Poll::Pending;
14979        }
14980
14981        let options = match self.options.validate() {
14982            Ok(options) => options,
14983            Err(error) => {
14984                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14985            }
14986        };
14987        if self.local {
14988            if self.worker_session.is_some() {
14989                return Poll::Ready(Err(Error::WorkerLoop(
14990                    "local activities cannot use worker-session routing".into(),
14991                )));
14992            }
14993            if let Err(error) = local_activity::validate(&options) {
14994                return Poll::Ready(Err(error));
14995            }
14996        }
14997        let session = match self
14998            .worker_session
14999            .as_ref()
15000            .map(WorkerSessionOptions::to_wire)
15001            .transpose()
15002        {
15003            Ok(value) => value,
15004            Err(error) => return Poll::Ready(Err(error)),
15005        };
15006        let session_queue = session
15007            .as_ref()
15008            .and_then(|session| session["queue"].as_str());
15009        let task_queue = options
15010            .task_queue
15011            .clone()
15012            .or_else(|| session_queue.map(str::to_owned))
15013            .unwrap_or_else(|| state.task_queue.clone());
15014        if session_queue.is_some_and(|queue| queue != task_queue) {
15015            return Poll::Ready(Err(Error::WorkerLoop(
15016                "worker-session queue must match the activity task queue".into(),
15017            )));
15018        }
15019        let current_recorded_options = RecordedActivityOptions {
15020            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15021            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15022            retry_policy: current_activity_retry_snapshot(&options),
15023            worker_session: session,
15024        };
15025
15026        let cursor = state.command_cursor;
15027        let call_kind = if self.local {
15028            CancellationCallKind::LocalActivity
15029        } else {
15030            CancellationCallKind::Activity
15031        };
15032        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15033            return Poll::Ready(Err(error));
15034        }
15035        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15036            Ok(recorded) => recorded,
15037            Err(error) => return Poll::Ready(Err(error)),
15038        };
15039        if let Some(recorded) = recorded {
15040            let sequence = recorded.sequence();
15041            match recorded {
15042                RecordedCommand::Activity {
15043                    activity_type,
15044                    cancellation_policy,
15045                    options: recorded_options,
15046                    outcome,
15047                    parallel_group_path,
15048                    ..
15049                } => {
15050                    let current_policy = options
15051                        .cancellation_policy
15052                        .unwrap_or(CancellationPolicy::TryCancel)
15053                        .as_str();
15054                    if cancellation_policy != current_policy {
15055                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15056                            ReplayFailure::new(
15057                                "activity_cancellation_policy_changed",
15058                                Some(sequence),
15059                                Some(cancellation_policy),
15060                                Some(current_policy.to_string()),
15061                                "Activity cancellation policy changed during replay",
15062                            ),
15063                        )));
15064                    }
15065                    if let Err(error) = ensure_parallel_path_matches(
15066                        sequence,
15067                        parallel_group_path.as_deref(),
15068                        &self.parallel_group_path,
15069                    ) {
15070                        return Poll::Ready(Err(error));
15071                    }
15072                    if let Some(recorded_type) = activity_type {
15073                        if recorded_type != self.activity_type {
15074                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15075                                ReplayFailure::new(
15076                                    "recorded_command_detail_mismatch",
15077                                    Some(sequence),
15078                                    Some(format!("activity:{recorded_type}")),
15079                                    Some(format!("activity:{}", self.activity_type)),
15080                                    "recorded activity type differs from the current workflow command",
15081                                ),
15082                            )));
15083                        }
15084                    }
15085                    if let Some(recorded_options) = recorded_options {
15086                        if recorded_options.worker_session
15087                            != current_recorded_options.worker_session
15088                        {
15089                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15090                                "activity_worker_session_mismatch", Some(sequence),
15091                                Some(activity_options_description(&recorded_options)),
15092                                Some(activity_options_description(&current_recorded_options)),
15093                                "recorded worker-session routing differs from the current activity",
15094                            ))));
15095                        }
15096                        if !recorded_options
15097                            .task_queue
15098                            .matches_current(&current_recorded_options.task_queue)
15099                        {
15100                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15101                                ReplayFailure::new(
15102                                    "activity_task_queue_mismatch",
15103                                    Some(sequence),
15104                                    Some(activity_options_description(&recorded_options)),
15105                                    Some(activity_options_description(&current_recorded_options)),
15106                                    "recorded activity task queue differs from the current workflow command",
15107                                ),
15108                            )));
15109                        }
15110                        if (self.local
15111                            && matches!(
15112                                recorded_options.execution_mode,
15113                                RecordedSnapshotValue::Unknown
15114                            ))
15115                            || !recorded_options
15116                                .execution_mode
15117                                .matches_current(&current_recorded_options.execution_mode)
15118                        {
15119                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15120                                ReplayFailure::new(
15121                                    "activity_execution_mode_mismatch",
15122                                    Some(sequence),
15123                                    Some(activity_options_description(&recorded_options)),
15124                                    Some(activity_options_description(&current_recorded_options)),
15125                                    "recorded activity execution mode differs from the current workflow command",
15126                                ),
15127                            )));
15128                        }
15129                        if !recorded_options
15130                            .retry_policy
15131                            .matches_current(&current_recorded_options.retry_policy)
15132                        {
15133                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15134                                ReplayFailure::new(
15135                                    "activity_retry_policy_mismatch",
15136                                    Some(sequence),
15137                                    Some(activity_options_description(&recorded_options)),
15138                                    Some(activity_options_description(&current_recorded_options)),
15139                                    "recorded activity retry policy differs from the current workflow command",
15140                                ),
15141                            )));
15142                        }
15143                    }
15144                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15145                        return Poll::Ready(Err(error));
15146                    }
15147                    match state.prepare_scalar_cancellation(
15148                        cursor,
15149                        call_kind,
15150                        &self.parallel_group_path,
15151                    ) {
15152                        Ok(true) => {
15153                            self.scheduled = true;
15154                            return Poll::Pending;
15155                        }
15156                        Ok(false) => {}
15157                        Err(error) => return Poll::Ready(Err(error)),
15158                    }
15159                    state.command_cursor += 1;
15160                    if let Some(outcome) = outcome {
15161                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15162                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15163                    }
15164                    state.matched_recorded_pending = true;
15165                    self.scheduled = true;
15166                    return Poll::Pending;
15167                }
15168                other => {
15169                    return Poll::Ready(Err(command_mismatch(
15170                        &other,
15171                        format!("activity:{}", self.activity_type),
15172                    )));
15173                }
15174            }
15175        }
15176
15177        if !self.scheduled {
15178            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15179                Ok(args) => args,
15180                Err(error) => return Poll::Ready(Err(error)),
15181            };
15182            let arguments = normalize_avro_arguments(args);
15183            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15184                Ok(envelope) => envelope,
15185                Err(error) => return Poll::Ready(Err(error)),
15186            };
15187
15188            let mut command = serde_json::Map::from_iter([
15189                (
15190                    "type".to_string(),
15191                    json!(if self.local {
15192                        "record_local_activity"
15193                    } else {
15194                        "schedule_activity"
15195                    }),
15196                ),
15197                (
15198                    "activity_type".to_string(),
15199                    json!(self.activity_type.clone()),
15200                ),
15201                ("queue".to_string(), json!(task_queue)),
15202                ("arguments".to_string(), envelope),
15203            ]);
15204            for (field, value) in [
15205                ("start_to_close_timeout", options.start_to_close_timeout),
15206                (
15207                    "schedule_to_start_timeout",
15208                    options.schedule_to_start_timeout,
15209                ),
15210                (
15211                    "schedule_to_close_timeout",
15212                    options.schedule_to_close_timeout,
15213                ),
15214                ("heartbeat_timeout", options.heartbeat_timeout),
15215            ] {
15216                if let Some(value) = value {
15217                    command.insert(field.to_string(), json!(value));
15218                }
15219            }
15220            if let Some(retry_policy) = &options.retry_policy {
15221                command.insert("retry_policy".to_string(), retry_policy.clone());
15222            }
15223            if let Some(policy) = options.cancellation_policy {
15224                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15225            }
15226            if let Some(session) = current_recorded_options.worker_session {
15227                command.insert("worker_session".into(), session);
15228            }
15229            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15230            ctx.apply_scope_membership(&mut command);
15231            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15232                Ok(true) => {
15233                    self.scheduled = true;
15234                    return Poll::Pending;
15235                }
15236                Ok(false) => {}
15237                Err(error) => return Poll::Ready(Err(error)),
15238            }
15239            if self.local {
15240                command.remove("queue");
15241                command.insert("execution_mode".into(), json!("local"));
15242                let result = Arc::new(Mutex::new(None));
15243                let command_index = state.commands.len();
15244                state.local_activity_requests.push(local_activity::Request {
15245                    command_index,
15246                    options,
15247                    arguments,
15248                    result: result.clone(),
15249                });
15250                self.local_result = Some(result);
15251            }
15252            state.commands.push(Value::Object(command));
15253            self.scheduled = true;
15254        }
15255
15256        Poll::Pending
15257    }
15258}
15259
15260impl Future for ActivityCall {
15261    type Output = Result<Value>;
15262
15263    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15264        match self.poll_avro_value(cx) {
15265            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15266            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15267            Poll::Pending => Poll::Pending,
15268        }
15269    }
15270}
15271
15272/// Future returned by [`WorkflowContext::sleep`].
15273pub struct TimerCall {
15274    ctx: WorkflowContext,
15275    delay_seconds: Option<u64>,
15276    scheduled: bool,
15277    matched_pending: bool,
15278    parallel_group_path: Vec<ParallelGroupMetadata>,
15279}
15280
15281impl Future for TimerCall {
15282    type Output = Result<()>;
15283
15284    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15285        if self.matched_pending {
15286            return Poll::Pending;
15287        }
15288
15289        let ctx = self.ctx.clone();
15290        let Some(requested_delay) = self.delay_seconds else {
15291            return Poll::Ready(Err(Error::TimerDurationOverflow));
15292        };
15293        let mut state = match ctx.state.lock() {
15294            Ok(state) => state,
15295            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15296        };
15297
15298        let cursor = state.command_cursor;
15299        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15300            return Poll::Ready(Err(error));
15301        }
15302        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15303        {
15304            Ok(recorded) => recorded,
15305            Err(error) => return Poll::Ready(Err(error)),
15306        };
15307        if let Some(recorded) = recorded {
15308            match recorded {
15309                RecordedCommand::Timer {
15310                    sequence,
15311                    delay_seconds,
15312                    fired,
15313                    parallel_group_path,
15314                    ..
15315                } => {
15316                    if let Err(error) =
15317                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15318                    {
15319                        return Poll::Ready(Err(error));
15320                    }
15321                    if let Err(error) = ensure_parallel_path_matches(
15322                        sequence,
15323                        parallel_group_path.as_deref(),
15324                        &self.parallel_group_path,
15325                    ) {
15326                        return Poll::Ready(Err(error));
15327                    }
15328                    if delay_seconds != requested_delay {
15329                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15330                            ReplayFailure::new(
15331                                "timer_delay_mismatch",
15332                                Some(sequence),
15333                                Some(format!("timer:{delay_seconds}s")),
15334                                Some(format!("timer:{requested_delay}s")),
15335                                "recorded timer delay differs from the current workflow command",
15336                            ),
15337                        )));
15338                    }
15339                    if let Err(error) =
15340                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
15341                    {
15342                        return Poll::Ready(Err(error));
15343                    }
15344                    match state.prepare_scalar_cancellation(
15345                        cursor,
15346                        CancellationCallKind::Timer,
15347                        &self.parallel_group_path,
15348                    ) {
15349                        Ok(true) => {
15350                            self.scheduled = true;
15351                            self.matched_pending = true;
15352                            return Poll::Pending;
15353                        }
15354                        Ok(false) => {}
15355                        Err(error) => return Poll::Ready(Err(error)),
15356                    }
15357                    state.command_cursor += 1;
15358                    if fired {
15359                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15360                        return Poll::Ready(Ok(()));
15361                    }
15362                    state.matched_recorded_pending = true;
15363                    self.scheduled = true;
15364                    self.matched_pending = true;
15365                    return Poll::Pending;
15366                }
15367                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
15368            }
15369        }
15370
15371        if !self.scheduled {
15372            let mut command = serde_json::Map::from_iter([
15373                ("type".to_string(), json!("start_timer")),
15374                ("delay_seconds".to_string(), json!(requested_delay)),
15375            ]);
15376            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
15377                Ok(Some(proof)) => {
15378                    command.insert("cancellation_cleanup".into(), proof);
15379                }
15380                Ok(None) => {}
15381                Err(error) => return Poll::Ready(Err(error)),
15382            }
15383            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15384            ctx.apply_scope_membership(&mut command);
15385            match state.prepare_scalar_cancellation(
15386                cursor,
15387                CancellationCallKind::Timer,
15388                &self.parallel_group_path,
15389            ) {
15390                Ok(true) => {
15391                    self.scheduled = true;
15392                    self.matched_pending = true;
15393                    return Poll::Pending;
15394                }
15395                Ok(false) => {}
15396                Err(error) => return Poll::Ready(Err(error)),
15397            }
15398            state.commands.push(Value::Object(command));
15399            self.scheduled = true;
15400        }
15401
15402        Poll::Pending
15403    }
15404}
15405
15406/// Future returned by [`WorkflowContext::wait_condition`].
15407pub struct ConditionWaitCall {
15408    ctx: WorkflowContext,
15409    options: ConditionWaitOptions,
15410    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
15411    occurrence_id: Option<String>,
15412    opened_wait: bool,
15413    parallel_group_path: Vec<ParallelGroupMetadata>,
15414}
15415
15416impl Future for ConditionWaitCall {
15417    type Output = Result<ConditionWaitResult>;
15418
15419    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15420        if self.opened_wait {
15421            return Poll::Pending;
15422        }
15423
15424        let options = match self.options.validate() {
15425            Ok(options) => options,
15426            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
15427        };
15428        let ctx = self.ctx.clone();
15429        let occurrence_id = match self.occurrence_id.as_ref() {
15430            Some(occurrence_id) => occurrence_id.clone(),
15431            None => {
15432                let mut state = match ctx.state.lock() {
15433                    Ok(state) => state,
15434                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15435                };
15436                let ordinal = state.condition_wait_occurrence_counter;
15437                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
15438                    Some(next) => next,
15439                    None => {
15440                        return Poll::Ready(Err(Error::WorkerLoop(
15441                            "condition wait occurrence counter overflowed".to_string(),
15442                        )))
15443                    }
15444                };
15445                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
15446                drop(state);
15447                self.occurrence_id = Some(occurrence_id.clone());
15448                occurrence_id
15449            }
15450        };
15451
15452        let recorded_result = {
15453            let mut state = match ctx.state.lock() {
15454                Ok(state) => state,
15455                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15456            };
15457            let initial_cursor = state.command_cursor;
15458            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
15459                return Poll::Ready(Err(error));
15460            }
15461            let recorded = match state
15462                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
15463            {
15464                Ok(recorded) => recorded,
15465                Err(error) => return Poll::Ready(Err(error)),
15466            };
15467            let Some(recorded) = recorded else {
15468                drop(state);
15469                return self.poll_new_condition(options);
15470            };
15471            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
15472                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
15473            }
15474
15475            let mut cursor = state.command_cursor;
15476            let mut result = None;
15477            let mut pending_delivery = false;
15478            loop {
15479                if cursor > initial_cursor
15480                    && matches!(
15481                        state.recorded_commands.get(cursor),
15482                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
15483                    )
15484                {
15485                    break;
15486                }
15487                let recorded = match state
15488                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
15489                {
15490                    Ok(recorded) => recorded,
15491                    Err(error) => return Poll::Ready(Err(error)),
15492                };
15493                let Some(RecordedCommand::ConditionWait {
15494                    sequence,
15495                    occurrence_id: ref recorded_occurrence_id,
15496                    ref condition_key,
15497                    ref predicate_identity,
15498                    timeout_seconds,
15499                    result: recorded_result,
15500                    ref parallel_group_path,
15501                    ..
15502                }) = recorded
15503                else {
15504                    break;
15505                };
15506
15507                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
15508                    break;
15509                }
15510                if let Err(error) = ensure_parallel_path_matches(
15511                    sequence,
15512                    parallel_group_path.as_deref(),
15513                    &self.parallel_group_path,
15514                ) {
15515                    return Poll::Ready(Err(error));
15516                }
15517                if let Err(error) = validate_recorded_condition_wait(
15518                    sequence,
15519                    recorded_occurrence_id,
15520                    condition_key.as_deref(),
15521                    predicate_identity,
15522                    timeout_seconds,
15523                    &occurrence_id,
15524                    &options,
15525                ) {
15526                    return Poll::Ready(Err(error));
15527                }
15528                if result == Some(ConditionWaitResult::TimedOut) {
15529                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15530                        "condition_wait_reopened_after_timeout",
15531                        Some(sequence),
15532                        Some("timed-out condition is terminal".to_string()),
15533                        Some("another physical wait-open".to_string()),
15534                        "condition history reopened one logical wait after its durable timeout",
15535                    ))));
15536                }
15537                if let Err(error) =
15538                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
15539                {
15540                    return Poll::Ready(Err(error));
15541                }
15542                match state.prepare_scalar_cancellation(
15543                    cursor,
15544                    CancellationCallKind::Condition,
15545                    &self.parallel_group_path,
15546                ) {
15547                    Ok(pending) => pending_delivery |= pending,
15548                    Err(error) => return Poll::Ready(Err(error)),
15549                }
15550                result = recorded_result;
15551                if result.is_some() {
15552                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15553                }
15554                cursor += 1;
15555            }
15556            state.command_cursor = cursor;
15557            if pending_delivery {
15558                self.opened_wait = true;
15559                return Poll::Pending;
15560            }
15561            result
15562        };
15563
15564        if let Some(result) = recorded_result {
15565            return Poll::Ready(Ok(result));
15566        }
15567
15568        self.poll_open_condition(options, true)
15569    }
15570}
15571
15572impl ConditionWaitCall {
15573    fn poll_new_condition(
15574        self: Pin<&mut Self>,
15575        options: ValidatedConditionWaitOptions,
15576    ) -> Poll<Result<ConditionWaitResult>> {
15577        self.poll_open_condition(options, false)
15578    }
15579
15580    fn poll_open_condition(
15581        mut self: Pin<&mut Self>,
15582        options: ValidatedConditionWaitOptions,
15583        recorded_wait: bool,
15584    ) -> Poll<Result<ConditionWaitResult>> {
15585        {
15586            let ctx = self.ctx.clone();
15587            let mut state = match ctx.state.lock() {
15588                Ok(state) => state,
15589                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15590            };
15591            let cursor = state.command_cursor;
15592            match state.prepare_scalar_cancellation(
15593                cursor,
15594                CancellationCallKind::Condition,
15595                &self.parallel_group_path,
15596            ) {
15597                Ok(true) => {
15598                    self.opened_wait = true;
15599                    return Poll::Pending;
15600                }
15601                Ok(false) => {}
15602                Err(error) => return Poll::Ready(Err(error)),
15603            }
15604        }
15605        let selection_member = self
15606            .parallel_group_path
15607            .first()
15608            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
15609        match (self.predicate)() {
15610            Ok(true) if !selection_member || recorded_wait => {
15611                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
15612            }
15613            Ok(_) => {}
15614            Err(error) => return Poll::Ready(Err(error)),
15615        }
15616        if options.timeout_seconds == Some(0) && !selection_member {
15617            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15618        }
15619
15620        let ctx = self.ctx.clone();
15621        let mut state = match ctx.state.lock() {
15622            Ok(state) => state,
15623            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15624        };
15625        let mut command = serde_json::Map::from_iter([
15626            ("type".to_string(), json!("open_condition_wait")),
15627            (
15628                "condition_wait_occurrence_id".to_string(),
15629                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15630            ),
15631            ("condition_key".to_string(), json!(options.condition_key)),
15632            (
15633                "condition_definition_fingerprint".to_string(),
15634                json!(options.predicate_identity),
15635            ),
15636        ]);
15637        if let Some(timeout_seconds) = options.timeout_seconds {
15638            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15639        }
15640        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15641        ctx.apply_scope_membership(&mut command);
15642        state.commands.push(Value::Object(command));
15643        drop(state);
15644        self.opened_wait = true;
15645        Poll::Pending
15646    }
15647}
15648
15649fn validate_recorded_condition_wait(
15650    sequence: u64,
15651    recorded_occurrence_id: &str,
15652    recorded_key: Option<&str>,
15653    recorded_predicate_identity: &str,
15654    recorded_timeout_seconds: Option<u64>,
15655    current_occurrence_id: &str,
15656    current: &ValidatedConditionWaitOptions,
15657) -> Result<()> {
15658    if recorded_occurrence_id != current_occurrence_id {
15659        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15660            "condition_wait_occurrence_mismatch",
15661            Some(sequence),
15662            Some(recorded_occurrence_id.to_string()),
15663            Some(current_occurrence_id.to_string()),
15664            "recorded condition occurrence differs from the current authored wait position",
15665        )));
15666    }
15667    if recorded_key != Some(current.condition_key.as_str()) {
15668        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15669            "condition_wait_key_mismatch",
15670            Some(sequence),
15671            recorded_key.map(str::to_string),
15672            Some(current.condition_key.clone()),
15673            "recorded condition identity differs from the current workflow wait",
15674        )));
15675    }
15676    if recorded_predicate_identity != current.predicate_identity {
15677        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15678            "condition_wait_predicate_mismatch",
15679            Some(sequence),
15680            Some(recorded_predicate_identity.to_string()),
15681            Some(current.predicate_identity.clone()),
15682            "recorded condition predicate behavior differs from current workflow code",
15683        )));
15684    }
15685    if recorded_timeout_seconds != current.timeout_seconds {
15686        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15687            "condition_wait_timeout_mismatch",
15688            Some(sequence),
15689            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15690            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15691            "recorded condition timeout differs from the current workflow wait",
15692        )));
15693    }
15694    Ok(())
15695}
15696
15697/// Future returned by [`WorkflowContext::start_child_workflow`].
15698pub struct ChildWorkflowCall {
15699    ctx: WorkflowContext,
15700    workflow_type: String,
15701    options: ChildWorkflowOptions,
15702    args: Option<Result<AvroValue>>,
15703    scheduled: bool,
15704    matched_pending: bool,
15705    parallel_group_path: Vec<ParallelGroupMetadata>,
15706}
15707
15708impl ChildWorkflowCall {
15709    fn poll_avro_value(
15710        mut self: Pin<&mut Self>,
15711        _cx: &mut TaskContext<'_>,
15712    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15713        if self.matched_pending {
15714            return Poll::Pending;
15715        }
15716
15717        let ctx = self.ctx.clone();
15718        let mut state = match ctx.state.lock() {
15719            Ok(state) => state,
15720            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15721        };
15722
15723        let cursor = state.command_cursor;
15724        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15725            return Poll::Ready(Err(error));
15726        }
15727        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15728        {
15729            Ok(recorded) => recorded,
15730            Err(error) => return Poll::Ready(Err(error)),
15731        };
15732        if let Some(recorded) = recorded {
15733            let sequence = recorded.sequence();
15734            match recorded {
15735                RecordedCommand::ChildWorkflow {
15736                    workflow_type,
15737                    policies,
15738                    outcome,
15739                    parallel_group_path,
15740                    ..
15741                } => {
15742                    if let Err(error) = ensure_parallel_path_matches(
15743                        sequence,
15744                        parallel_group_path.as_deref(),
15745                        &self.parallel_group_path,
15746                    ) {
15747                        return Poll::Ready(Err(error));
15748                    }
15749                    if let Some(recorded_type) = workflow_type {
15750                        if recorded_type != self.workflow_type {
15751                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15752                                ReplayFailure::new(
15753                                    "recorded_command_detail_mismatch",
15754                                    Some(sequence),
15755                                    Some(format!("child workflow:{recorded_type}")),
15756                                    Some(format!("child workflow:{}", self.workflow_type)),
15757                                    "recorded child workflow type differs from the current workflow command",
15758                                ),
15759                            )));
15760                        }
15761                    }
15762                    if let Err(error) =
15763                        ensure_child_policies_match(sequence, &policies, &self.options)
15764                    {
15765                        return Poll::Ready(Err(error));
15766                    }
15767                    if let Err(error) =
15768                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15769                    {
15770                        return Poll::Ready(Err(error));
15771                    }
15772                    match state.prepare_scalar_cancellation(
15773                        cursor,
15774                        CancellationCallKind::Child,
15775                        &self.parallel_group_path,
15776                    ) {
15777                        Ok(true) => {
15778                            self.scheduled = true;
15779                            self.matched_pending = true;
15780                            return Poll::Pending;
15781                        }
15782                        Ok(false) => {}
15783                        Err(error) => return Poll::Ready(Err(error)),
15784                    }
15785                    state.command_cursor += 1;
15786                    if let Some(outcome) = outcome {
15787                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15788                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15789                    }
15790                    state.matched_recorded_pending = true;
15791                    self.scheduled = true;
15792                    self.matched_pending = true;
15793                    return Poll::Pending;
15794                }
15795                other => {
15796                    return Poll::Ready(Err(command_mismatch(
15797                        &other,
15798                        format!("child workflow:{}", self.workflow_type),
15799                    )));
15800                }
15801            }
15802        }
15803
15804        if !self.scheduled {
15805            if self.options.task_queue.trim().is_empty() {
15806                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15807                    "task_queue must not be empty".to_string(),
15808                )));
15809            }
15810            for (name, value) in [
15811                (
15812                    "execution_timeout_seconds",
15813                    self.options.execution_timeout_seconds,
15814                ),
15815                ("run_timeout_seconds", self.options.run_timeout_seconds),
15816            ] {
15817                if value == Some(0) {
15818                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15819                        "{name} must be at least 1"
15820                    ))));
15821                }
15822            }
15823
15824            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15825                Ok(args) => args,
15826                Err(error) => return Poll::Ready(Err(error)),
15827            };
15828            let arguments = match encode_typed_envelope(
15829                &normalize_avro_arguments(args),
15830                &state.payload_codec,
15831            ) {
15832                Ok(arguments) => arguments,
15833                Err(error) => return Poll::Ready(Err(error)),
15834            };
15835            let mut command = json!({
15836                "type": "start_child_workflow",
15837                "workflow_type": self.workflow_type,
15838                "queue": self.options.task_queue,
15839                "parent_close_policy": self.options.parent_close_policy.as_str(),
15840                "arguments": arguments,
15841            });
15842            let object = command
15843                .as_object_mut()
15844                .expect("child workflow command is always an object");
15845            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15846                object.insert(
15847                    "cancellation_policy".to_string(),
15848                    json!(self.options.cancellation_policy.as_str()),
15849                );
15850            }
15851            if let Some(policy) = &self.options.retry_policy {
15852                let mut retry_policy = serde_json::Map::new();
15853                if let Some(max_attempts) = policy.max_attempts {
15854                    if max_attempts == 0 {
15855                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15856                            "retry_policy.max_attempts must be at least 1".to_string(),
15857                        )));
15858                    }
15859                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15860                }
15861                if !policy.backoff_seconds.is_empty() {
15862                    retry_policy
15863                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15864                }
15865                if !policy.non_retryable_error_types.is_empty() {
15866                    retry_policy.insert(
15867                        "non_retryable_error_types".to_string(),
15868                        json!(policy.non_retryable_error_types),
15869                    );
15870                }
15871                if retry_policy.is_empty() {
15872                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15873                        "retry_policy must configure at least one field".to_string(),
15874                    )));
15875                }
15876                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15877            }
15878            if let Some(seconds) = self.options.execution_timeout_seconds {
15879                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15880            }
15881            if let Some(seconds) = self.options.run_timeout_seconds {
15882                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15883            }
15884            apply_parallel_group_path(object, &self.parallel_group_path);
15885            ctx.apply_scope_membership(object);
15886            match state.prepare_scalar_cancellation(
15887                cursor,
15888                CancellationCallKind::Child,
15889                &self.parallel_group_path,
15890            ) {
15891                Ok(true) => {
15892                    self.scheduled = true;
15893                    self.matched_pending = true;
15894                    return Poll::Pending;
15895                }
15896                Ok(false) => {}
15897                Err(error) => return Poll::Ready(Err(error)),
15898            }
15899            state.commands.push(command);
15900            self.scheduled = true;
15901        }
15902
15903        Poll::Pending
15904    }
15905}
15906
15907impl Future for ChildWorkflowCall {
15908    type Output = Result<ChildWorkflowResult>;
15909
15910    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15911        match self.poll_avro_value(cx) {
15912            Poll::Ready(Ok(result)) => match result.result.into_json() {
15913                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15914                    parent: result.parent,
15915                    child: result.child,
15916                    child_workflow_type: result.child_workflow_type,
15917                    result: projected,
15918                })),
15919                Err(error) => Poll::Ready(Err(error)),
15920            },
15921            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15922            Poll::Pending => Poll::Pending,
15923        }
15924    }
15925}
15926
15927fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15928    Error::NonDeterministicReplay(ReplayFailure::new(
15929        "recorded_command_mismatch",
15930        Some(recorded.sequence()),
15931        Some(recorded.shape().to_string()),
15932        Some(actual.into()),
15933        "current workflow command does not match the recorded durable command sequence",
15934    ))
15935}
15936
15937pub struct SignalCall {
15938    ctx: WorkflowContext,
15939    signal_name: String,
15940    runtime_reserved_allowed: bool,
15941    opened_wait: bool,
15942    matched_pending: bool,
15943    parallel_group_path: Vec<ParallelGroupMetadata>,
15944}
15945
15946impl SignalCall {
15947    fn poll_avro_value(
15948        mut self: Pin<&mut Self>,
15949        _cx: &mut TaskContext<'_>,
15950    ) -> Poll<Result<Vec<AvroValue>>> {
15951        if self.matched_pending {
15952            return Poll::Pending;
15953        }
15954        if !self.runtime_reserved_allowed {
15955            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15956                return Poll::Ready(Err(error));
15957            }
15958        }
15959
15960        let ctx = self.ctx.clone();
15961        let mut state = match ctx.state.lock() {
15962            Ok(state) => state,
15963            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15964        };
15965
15966        let cursor = state.command_cursor;
15967        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15968            return Poll::Ready(Err(error));
15969        }
15970        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15971        {
15972            Ok(recorded) => recorded,
15973            Err(error) => return Poll::Ready(Err(error)),
15974        };
15975        if let Some(recorded) = recorded {
15976            match recorded {
15977                RecordedCommand::SignalWait {
15978                    sequence,
15979                    signal_name,
15980                    value,
15981                    parallel_group_path,
15982                } => {
15983                    if let Err(error) = ensure_parallel_path_matches(
15984                        sequence,
15985                        parallel_group_path.as_deref(),
15986                        &self.parallel_group_path,
15987                    ) {
15988                        return Poll::Ready(Err(error));
15989                    }
15990                    if signal_name != self.signal_name {
15991                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15992                            ReplayFailure::new(
15993                                "recorded_command_detail_mismatch",
15994                                Some(sequence),
15995                                Some(format!("signal wait:{signal_name}")),
15996                                Some(format!("signal wait:{}", self.signal_name)),
15997                                "recorded signal name differs from the current workflow command",
15998                            ),
15999                        )));
16000                    }
16001
16002                    if let Err(error) =
16003                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16004                    {
16005                        return Poll::Ready(Err(error));
16006                    }
16007                    match state.prepare_scalar_cancellation(
16008                        cursor,
16009                        CancellationCallKind::Signal,
16010                        &self.parallel_group_path,
16011                    ) {
16012                        Ok(true) => {
16013                            self.opened_wait = true;
16014                            self.matched_pending = true;
16015                            return Poll::Pending;
16016                        }
16017                        Ok(false) => {}
16018                        Err(error) => return Poll::Ready(Err(error)),
16019                    }
16020                    state.command_cursor += 1;
16021                    if let Some(value) = value {
16022                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
16023                        return Poll::Ready(Ok(value));
16024                    }
16025                    if state
16026                        .resume_signal
16027                        .as_ref()
16028                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16029                    {
16030                        let signal = state
16031                            .resume_signal
16032                            .take()
16033                            .expect("matching resume signal is present");
16034                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
16035                        return Poll::Ready(Ok(signal.arguments));
16036                    }
16037
16038                    state.matched_recorded_pending = true;
16039                    self.opened_wait = true;
16040                    self.matched_pending = true;
16041                    return Poll::Pending;
16042                }
16043                other => {
16044                    return Poll::Ready(Err(command_mismatch(
16045                        &other,
16046                        format!("signal wait:{}", self.signal_name),
16047                    )));
16048                }
16049            }
16050        }
16051
16052        match state.prepare_scalar_cancellation(
16053            cursor,
16054            CancellationCallKind::Signal,
16055            &self.parallel_group_path,
16056        ) {
16057            Ok(true) => {
16058                self.opened_wait = true;
16059                self.matched_pending = true;
16060                return Poll::Pending;
16061            }
16062            Ok(false) => {}
16063            Err(error) => return Poll::Ready(Err(error)),
16064        }
16065
16066        if state
16067            .resume_signal
16068            .as_ref()
16069            .is_some_and(|signal| signal.signal_name == self.signal_name)
16070        {
16071            let signal = state
16072                .resume_signal
16073                .take()
16074                .expect("matching resume signal is present");
16075            state.unavailable_cancellation_boundary(&self.parallel_group_path);
16076            return Poll::Ready(Ok(signal.arguments));
16077        }
16078
16079        if !self.opened_wait {
16080            let mut command = serde_json::Map::from_iter([
16081                ("type".to_string(), json!("open_signal_wait")),
16082                ("signal_name".to_string(), json!(self.signal_name)),
16083            ]);
16084            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16085            ctx.apply_scope_membership(&mut command);
16086            state.commands.push(Value::Object(command));
16087            self.opened_wait = true;
16088        }
16089
16090        Poll::Pending
16091    }
16092}
16093
16094impl Future for SignalCall {
16095    type Output = Result<Vec<Value>>;
16096
16097    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16098        match self.poll_avro_value(cx) {
16099            Poll::Ready(Ok(values)) => Poll::Ready(
16100                values
16101                    .into_iter()
16102                    .map(AvroValue::into_json)
16103                    .collect::<Result<Vec<_>>>(),
16104            ),
16105            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16106            Poll::Pending => Poll::Pending,
16107        }
16108    }
16109}
16110
16111#[derive(Clone, Debug)]
16112pub struct ActivityContext {
16113    client: Client,
16114    pub task_id: String,
16115    pub activity_attempt_id: String,
16116    pub lease_owner: String,
16117    pub activity_type: String,
16118    pub attempt_number: u64,
16119    pub task_queue: String,
16120    pub worker_id: String,
16121    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16122    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16123    worker_session: Option<WorkerSession>,
16124}
16125
16126impl ActivityContext {
16127    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16128        if let Some(heartbeats) = &self.local_heartbeats {
16129            return heartbeats
16130                .lock()
16131                .map_err(|_| Error::WorkflowStatePoisoned)?
16132                .record(details);
16133        }
16134        if let Some(guard) = &self.claim_guard {
16135            return guard.heartbeat(self, details).await;
16136        }
16137        if let Some(session) = &self.worker_session {
16138            if !session.active() {
16139                return Err(Error::ActivityExecutionAbandoned(
16140                    "worker-session lease or TTL is no longer active".into(),
16141                ));
16142            }
16143            let result = self
16144                .client
16145                .heartbeat_activity_task_value(
16146                    &self.task_id,
16147                    &self.activity_attempt_id,
16148                    &self.lease_owner,
16149                    details,
16150                )
16151                .await;
16152            return worker_session::settle_activity_heartbeat(
16153                session,
16154                result,
16155                &self.task_id,
16156                &self.activity_attempt_id,
16157                &self.lease_owner,
16158            );
16159        }
16160        self.client
16161            .heartbeat_activity_task(
16162                &self.task_id,
16163                &self.activity_attempt_id,
16164                &self.lease_owner,
16165                details,
16166            )
16167            .await
16168    }
16169}
16170
16171fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
16172    validate_payload_codec(codec)?;
16173    match value {
16174        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
16175            value, codec,
16176        )?)),
16177        None => Ok(AvroValue::Array(Vec::new())),
16178    }
16179}
16180
16181fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
16182    let Some(signal_name) = task
16183        .signal_name
16184        .as_deref()
16185        .filter(|value| !value.is_empty())
16186    else {
16187        return Ok(None);
16188    };
16189    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
16190    let AvroValue::Array(arguments) = decoded else {
16191        unreachable!("normalize_avro_arguments always returns an array");
16192    };
16193
16194    Ok(Some(ResumeSignal {
16195        signal_name: signal_name.to_string(),
16196        arguments,
16197    }))
16198}
16199
16200fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
16201    validate_payload_codec(&task.payload_codec)?;
16202    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
16203    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
16204    for event in &task.history_events {
16205        validate_history_event_payloads(event, &task.payload_codec)?;
16206    }
16207    Ok(())
16208}
16209
16210fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
16211    validate_payload_codec(&task.payload_codec)?;
16212    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
16213}
16214
16215fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
16216    validate_payload_codec(&task.payload_codec)?;
16217    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
16218    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
16219    for event in &task.history_events {
16220        validate_history_event_payloads(event, &task.payload_codec)?;
16221    }
16222
16223    let Some(export) = task.history_export.as_ref() else {
16224        return Ok(());
16225    };
16226    let export_codec = match export.get("payloads") {
16227        Some(payloads) => declared_payload_codec(payloads, "codec")?,
16228        None => None,
16229    }
16230    .unwrap_or(&task.payload_codec);
16231    validate_payload_codec(export_codec)?;
16232
16233    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
16234        for event in events {
16235            let event_type = event
16236                .get("event_type")
16237                .or_else(|| event.get("type"))
16238                .and_then(Value::as_str)
16239                .unwrap_or_default();
16240            if let Some(payload) = event.get("payload") {
16241                validate_history_payloads(event_type, payload, export_codec)?;
16242            }
16243        }
16244    }
16245    for signal in export
16246        .get("signals")
16247        .and_then(Value::as_array)
16248        .into_iter()
16249        .flatten()
16250    {
16251        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
16252        validate_payload_codec(codec)?;
16253        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
16254    }
16255    for activity in export
16256        .get("activities")
16257        .and_then(Value::as_array)
16258        .into_iter()
16259        .flatten()
16260    {
16261        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
16262        validate_payload_codec(codec)?;
16263        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
16264        validate_optional_inbound_payload(activity.get("result"), codec)?;
16265    }
16266    Ok(())
16267}
16268
16269fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
16270    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
16271}
16272
16273fn validate_history_payloads(
16274    event_type: &str,
16275    payload: &Value,
16276    fallback_codec: &str,
16277) -> Result<()> {
16278    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
16279    validate_payload_codec(codec)?;
16280    for field in history_payload_fields(event_type) {
16281        validate_optional_inbound_payload(payload.get(*field), codec)?;
16282    }
16283    Ok(())
16284}
16285
16286const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
16287
16288fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
16289    match event_type {
16290        "ActivityCompleted" => &["result"],
16291        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
16292        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
16293        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
16294        "ChildRunCompleted" => &["result", "output"],
16295        "WorkflowCompleted" => &["output"],
16296        "ServiceCallStarted"
16297        | "ServiceCallCompleted"
16298        | "ServiceCallFailed"
16299        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
16300        _ => &[],
16301    }
16302}
16303
16304fn signal_history_payload(payload: &Value) -> Option<&Value> {
16305    SIGNAL_HISTORY_PAYLOAD_FIELDS
16306        .iter()
16307        .find_map(|field| payload.get(*field))
16308}
16309
16310fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
16311    match value.get(field) {
16312        None => Ok(None),
16313        Some(Value::String(codec)) => Ok(Some(codec)),
16314        Some(_) => Err(invalid_payload_envelope()),
16315    }
16316}
16317
16318fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
16319    validate_payload_codec(codec)?;
16320    if let Some(value) = value.filter(|value| !value.is_null()) {
16321        decode_wire_avro_value(value, codec)?;
16322    }
16323    Ok(())
16324}
16325
16326fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
16327    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
16328        invalid_recorded_history(
16329            "parallel_group_metadata_invalid",
16330            sequence,
16331            "non-empty parallel_group_id",
16332            &payload.to_string(),
16333            "parallel-group history is missing its stable identity",
16334        )
16335    })?;
16336    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
16337        invalid_recorded_history(
16338            "parallel_group_metadata_invalid",
16339            sequence,
16340            "activity, child, timer, signal, condition, or mixed group kind",
16341            &payload.to_string(),
16342            "parallel-group history is missing its group kind",
16343        )
16344    })?;
16345    if !matches!(
16346        kind.as_str(),
16347        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
16348    ) {
16349        return Err(invalid_recorded_history(
16350            "parallel_group_metadata_invalid",
16351            sequence,
16352            "activity, child, timer, signal, condition, or mixed group kind",
16353            &kind,
16354            "parallel-group history contains an unsupported group kind",
16355        ));
16356    }
16357    let base_sequence = payload
16358        .get("parallel_group_base_sequence")
16359        .and_then(value_as_u64)
16360        .filter(|value| *value > 0)
16361        .ok_or_else(|| {
16362            invalid_recorded_history(
16363                "parallel_group_metadata_invalid",
16364                sequence,
16365                "positive parallel_group_base_sequence",
16366                &payload.to_string(),
16367                "parallel-group history contains an invalid base sequence",
16368            )
16369        })?;
16370    let size = payload
16371        .get("parallel_group_size")
16372        .and_then(value_as_u64)
16373        .and_then(|value| usize::try_from(value).ok())
16374        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
16375        .ok_or_else(|| {
16376            invalid_recorded_history(
16377                "parallel_group_metadata_invalid",
16378                sequence,
16379                "bounded positive parallel_group_size",
16380                &payload.to_string(),
16381                "parallel-group history contains an invalid group size",
16382            )
16383        })?;
16384    let index = payload
16385        .get("parallel_group_index")
16386        .and_then(value_as_u64)
16387        .and_then(|value| usize::try_from(value).ok())
16388        .filter(|value| *value < size)
16389        .ok_or_else(|| {
16390            invalid_recorded_history(
16391                "parallel_group_metadata_invalid",
16392                sequence,
16393                "parallel_group_index within group bounds",
16394                &payload.to_string(),
16395                "parallel-group history contains an invalid member index",
16396            )
16397        })?;
16398    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
16399        return Err(invalid_recorded_history(
16400            "parallel_group_metadata_invalid",
16401            sequence,
16402            "base sequence plus member index equals workflow sequence",
16403            &payload.to_string(),
16404            "parallel-group path does not preserve durable workflow position",
16405        ));
16406    }
16407    let mode = payload
16408        .get("parallel_group_mode")
16409        .and_then(Value::as_str)
16410        .unwrap_or("all");
16411    if !matches!(mode, "all" | "select") {
16412        return Err(invalid_recorded_history(
16413            "parallel_group_metadata_invalid",
16414            sequence,
16415            "parallel group mode all or select",
16416            mode,
16417            "parallel-group history contains an unsupported group mode",
16418        ));
16419    }
16420    let expected_id = if mode == "select" {
16421        format!("select-calls:{base_sequence}:{size}")
16422    } else {
16423        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
16424    };
16425    if group_id != expected_id {
16426        return Err(invalid_recorded_history(
16427            "parallel_group_metadata_invalid",
16428            sequence,
16429            &expected_id,
16430            &group_id,
16431            "parallel-group history contains an incompatible stable group ID",
16432        ));
16433    }
16434    let selection_member_key = if mode == "select" {
16435        Some(selection_key_from_value(
16436            payload.get("selection_member_key"),
16437            sequence,
16438        )?)
16439    } else {
16440        None
16441    };
16442    let selection_member_index = if mode == "select" {
16443        Some(required_parallel_usize(
16444            payload,
16445            "selection_member_index",
16446            sequence,
16447        )?)
16448    } else {
16449        None
16450    };
16451    let selection_member_base_sequence = if mode == "select" {
16452        Some(
16453            payload
16454                .get("selection_member_base_sequence")
16455                .and_then(value_as_u64)
16456                .filter(|value| *value >= base_sequence)
16457                .ok_or_else(|| {
16458                    invalid_recorded_history(
16459                        "parallel_group_metadata_invalid",
16460                        sequence,
16461                        "selection member base within its group",
16462                        &payload.to_string(),
16463                        "selection history contains an invalid member base sequence",
16464                    )
16465                })?,
16466        )
16467    } else {
16468        None
16469    };
16470    let selection_member_size = if mode == "select" {
16471        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
16472        if member_size == 0 {
16473            return Err(invalid_recorded_history(
16474                "parallel_group_metadata_invalid",
16475                sequence,
16476                "positive selection member size",
16477                &payload.to_string(),
16478                "selection history contains an invalid member size",
16479            ));
16480        }
16481        Some(member_size)
16482    } else {
16483        None
16484    };
16485    let selection_member_kind = if mode == "select" {
16486        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
16487            invalid_recorded_history(
16488                "parallel_group_metadata_invalid",
16489                sequence,
16490                "selection member operation kind",
16491                &payload.to_string(),
16492                "selection history is missing its authored member kind",
16493            )
16494        })?;
16495        if !matches!(
16496            kind.as_str(),
16497            "activity" | "child" | "timer" | "signal" | "condition" | "group"
16498        ) {
16499            return Err(invalid_recorded_history(
16500                "parallel_group_metadata_invalid",
16501                sequence,
16502                "activity, child, timer, signal, condition, or group selection member kind",
16503                &kind,
16504                "selection history contains an unsupported member kind",
16505            ));
16506        }
16507        Some(kind)
16508    } else {
16509        None
16510    };
16511    if let (Some(member_base), Some(member_size)) =
16512        (selection_member_base_sequence, selection_member_size)
16513    {
16514        let member_end = member_base
16515            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
16516            .ok_or_else(|| {
16517                invalid_recorded_history(
16518                    "parallel_group_metadata_invalid",
16519                    sequence,
16520                    "bounded selection member range",
16521                    &payload.to_string(),
16522                    "selection member range overflowed",
16523                )
16524            })?;
16525        let group_end = base_sequence
16526            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
16527            .unwrap_or(u64::MAX);
16528        if sequence < member_base || sequence >= member_end || member_end > group_end {
16529            return Err(invalid_recorded_history(
16530                "parallel_group_metadata_invalid",
16531                sequence,
16532                "workflow sequence within one bounded selection member",
16533                &payload.to_string(),
16534                "selection member range does not contain its durable leaf",
16535            ));
16536        }
16537    }
16538    Ok(ParallelGroupMetadata {
16539        parallel_group_id: group_id,
16540        parallel_group_kind: kind,
16541        parallel_group_base_sequence: base_sequence,
16542        parallel_group_size: size,
16543        parallel_group_index: index,
16544        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
16545        selection_member_key,
16546        selection_member_index,
16547        selection_member_base_sequence,
16548        selection_member_size,
16549        selection_member_kind,
16550    })
16551}
16552
16553fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
16554    payload
16555        .get(field)
16556        .and_then(value_as_u64)
16557        .and_then(|value| usize::try_from(value).ok())
16558        .ok_or_else(|| {
16559            invalid_recorded_history(
16560                "parallel_group_metadata_invalid",
16561                sequence,
16562                &format!("non-negative integer {field}"),
16563                &payload.to_string(),
16564                "selection history contains invalid member metadata",
16565            )
16566        })
16567}
16568
16569fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
16570    match value {
16571        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
16572        Some(value) => value_as_u64(value)
16573            .and_then(|value| usize::try_from(value).ok())
16574            .map(SelectionKey::Index)
16575            .ok_or_else(|| {
16576                invalid_recorded_history(
16577                    "selection_member_key_invalid",
16578                    sequence,
16579                    "non-empty string or non-negative integer member key",
16580                    &value.to_string(),
16581                    "selection history contains an invalid member key",
16582                )
16583            }),
16584        None => Err(invalid_recorded_history(
16585            "selection_member_key_missing",
16586            sequence,
16587            "selection_member_key",
16588            "<missing>",
16589            "selection history is missing its stable member key",
16590        )),
16591    }
16592}
16593
16594fn recorded_parallel_group_path(
16595    events: &[&HistoryEvent],
16596    sequence: u64,
16597) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16598    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
16599    for event in events {
16600        let payload = &event.payload;
16601        let has_metadata = payload.get("parallel_group_path").is_some()
16602            || payload.get("parallel_group_id").is_some()
16603            || payload.get("parallel_group_kind").is_some()
16604            || payload.get("parallel_group_base_sequence").is_some()
16605            || payload.get("parallel_group_size").is_some()
16606            || payload.get("parallel_group_index").is_some()
16607            || payload.get("parallel_group_mode").is_some()
16608            || payload.get("selection_member_key").is_some();
16609        if !has_metadata {
16610            continue;
16611        }
16612
16613        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16614        let path = match payload.get("parallel_group_path") {
16615            None => vec![top_level.clone()],
16616            Some(Value::Array(entries)) if !entries.is_empty() => entries
16617                .iter()
16618                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16619                .collect::<Result<Vec<_>>>()?,
16620            Some(value) => {
16621                return Err(invalid_recorded_history(
16622                    "parallel_group_metadata_invalid",
16623                    sequence,
16624                    "non-empty parallel_group_path list",
16625                    &value.to_string(),
16626                    "parallel-group history contains an invalid group path",
16627                ));
16628            }
16629        };
16630        if path.last() != Some(&top_level) {
16631            return Err(invalid_recorded_history(
16632                "parallel_group_metadata_invalid",
16633                sequence,
16634                &serde_json::to_string(&path.last()).unwrap_or_default(),
16635                &serde_json::to_string(&top_level).unwrap_or_default(),
16636                "parallel-group top-level fields do not match the innermost path entry",
16637            ));
16638        }
16639        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16640            return Err(invalid_recorded_history(
16641                "parallel_group_history_conflict",
16642                sequence,
16643                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16644                &serde_json::to_string(&path).unwrap_or_default(),
16645                "parallel-group metadata changed between scheduling and resolution history",
16646            ));
16647        }
16648        recorded = Some(path);
16649    }
16650    Ok(recorded)
16651}
16652
16653fn recorded_commands(
16654    events: &[HistoryEvent],
16655    fallback_codec: &str,
16656    parent: WorkflowIdentity,
16657) -> Result<Vec<RecordedCommand>> {
16658    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16659    let mut last_new_sequence = None;
16660
16661    for event in events {
16662        let is_activity = matches!(
16663            event.event_type.as_str(),
16664            "ActivityScheduled"
16665                | "ActivityStarted"
16666                | "ActivityHeartbeatRecorded"
16667                | "ActivityRetryScheduled"
16668                | "ActivityCompleted"
16669                | "ActivityFailed"
16670                | "ActivityCancelled"
16671                | "ActivityTimedOut"
16672        );
16673        let is_workflow_timer = matches!(
16674            event.event_type.as_str(),
16675            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16676        ) && !is_internal_timer_event(event);
16677        let is_child_workflow = matches!(
16678            event.event_type.as_str(),
16679            "ChildWorkflowScheduled"
16680                | "ChildRunStarted"
16681                | "ChildRunCompleted"
16682                | "ChildRunFailed"
16683                | "ChildRunCancelled"
16684                | "ChildRunTerminated"
16685        );
16686        let is_signal_wait = is_recorded_signal_wait_event(event);
16687        let is_condition_wait = is_recorded_condition_wait_event(event);
16688        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16689        let is_side_effect = event.event_type == "SideEffectRecorded";
16690        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16691        let is_memo = event.event_type == "MemoUpserted";
16692        let is_service_operation = nexus::is_service_event(event);
16693        if !is_activity
16694            && !is_workflow_timer
16695            && !is_child_workflow
16696            && !is_signal_wait
16697            && !is_condition_wait
16698            && !is_search_attributes
16699            && !is_side_effect
16700            && !is_version_marker
16701            && !is_memo
16702            && !is_service_operation
16703        {
16704            continue;
16705        }
16706
16707        let sequence = durable_event_sequence(event).ok_or_else(|| {
16708            Error::NonDeterministicReplay(ReplayFailure::new(
16709                "durable_command_sequence_missing",
16710                None,
16711                Some("positive workflow sequence".to_string()),
16712                Some(event.event_type.clone()),
16713                "durable command history event has no workflow sequence",
16714            ))
16715        })?;
16716        if sequence == 0 {
16717            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16718                "durable_command_sequence_invalid",
16719                Some(sequence),
16720                Some("positive workflow sequence".to_string()),
16721                Some(sequence.to_string()),
16722                "durable command history uses an invalid workflow sequence",
16723            )));
16724        }
16725        if !events_by_sequence.contains_key(&sequence) {
16726            if let Some(previous) = last_new_sequence {
16727                if sequence < previous {
16728                    return Err(invalid_recorded_history(
16729                        "durable_command_sequence_mismatch",
16730                        sequence,
16731                        &format!("workflow sequence greater than {previous}"),
16732                        &sequence.to_string(),
16733                        "durable commands are not strictly ordered by their recorded workflow sequence",
16734                    ));
16735                }
16736            }
16737            last_new_sequence = Some(sequence);
16738        }
16739        events_by_sequence.entry(sequence).or_default().push(event);
16740    }
16741
16742    let commands: Vec<RecordedCommand> = events_by_sequence
16743        .into_iter()
16744        .map(|(sequence, sequence_events)| {
16745            let activity_events: Vec<_> = sequence_events
16746                .iter()
16747                .copied()
16748                .filter(|event| event.event_type.starts_with("Activity"))
16749                .collect();
16750            let timer_events: Vec<_> = sequence_events
16751                .iter()
16752                .copied()
16753                .filter(|event| event.event_type.starts_with("Timer"))
16754                .collect();
16755            let child_events: Vec<_> = sequence_events
16756                .iter()
16757                .copied()
16758                .filter(|event| {
16759                    event.event_type == "ChildWorkflowScheduled"
16760                        || event.event_type.starts_with("ChildRun")
16761                })
16762                .collect();
16763            let signal_wait_events: Vec<_> = sequence_events
16764                .iter()
16765                .copied()
16766                .filter(|event| is_recorded_signal_wait_event(event))
16767                .collect();
16768            let condition_wait_events: Vec<_> = sequence_events
16769                .iter()
16770                .copied()
16771                .filter(|event| is_recorded_condition_wait_event(event))
16772                .collect();
16773            let search_attribute_events: Vec<_> = sequence_events
16774                .iter()
16775                .copied()
16776                .filter(|event| event.event_type == "SearchAttributesUpserted")
16777                .collect();
16778            let side_effect_events: Vec<_> = sequence_events
16779                .iter()
16780                .copied()
16781                .filter(|event| event.event_type == "SideEffectRecorded")
16782                .collect();
16783            let version_marker_events: Vec<_> = sequence_events
16784                .iter()
16785                .copied()
16786                .filter(|event| event.event_type == "VersionMarkerRecorded")
16787                .collect();
16788            let memo_events: Vec<_> = sequence_events
16789                .iter()
16790                .copied()
16791                .filter(|event| event.event_type == "MemoUpserted")
16792                .collect();
16793            let service_events: Vec<_> = sequence_events.iter().copied()
16794                .filter(|event| nexus::is_service_event(event)).collect();
16795
16796            let command_kind_count = usize::from(!activity_events.is_empty())
16797                + usize::from(!timer_events.is_empty())
16798                + usize::from(!child_events.is_empty())
16799                + usize::from(!signal_wait_events.is_empty())
16800                + usize::from(!condition_wait_events.is_empty())
16801                + usize::from(!search_attribute_events.is_empty())
16802                + usize::from(!side_effect_events.is_empty())
16803                + usize::from(!version_marker_events.is_empty())
16804                + usize::from(!memo_events.is_empty())
16805                + usize::from(!service_events.is_empty());
16806            if command_kind_count > 1 {
16807                let actual = [
16808                    (!activity_events.is_empty()).then_some("activity"),
16809                    (!timer_events.is_empty()).then_some("timer"),
16810                    (!child_events.is_empty()).then_some("child workflow"),
16811                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16812                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16813                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16814                    (!side_effect_events.is_empty()).then_some("side effect"),
16815                    (!version_marker_events.is_empty()).then_some("version marker"),
16816                    (!memo_events.is_empty()).then_some("memo upsert"),
16817                    (!service_events.is_empty()).then_some("service operation"),
16818                ]
16819                .into_iter()
16820                .flatten()
16821                .collect::<Vec<_>>()
16822                .join(" and ");
16823                return Err(invalid_recorded_history(
16824                    "durable_command_sequence_collision",
16825                    sequence,
16826                    "one durable command kind",
16827                    &actual,
16828                    "one workflow sequence records more than one durable command kind",
16829                ));
16830            }
16831
16832            if !service_events.is_empty() {
16833                return Ok(RecordedCommand::ServiceOperation {
16834                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16835                });
16836            }
16837
16838            if !activity_events.is_empty() {
16839                let parallel_group_path =
16840                    recorded_parallel_group_path(&activity_events, sequence)?;
16841                let scheduled_count = activity_events
16842                    .iter()
16843                    .filter(|event| event.event_type == "ActivityScheduled")
16844                    .count();
16845                if scheduled_count > 1 {
16846                    return Err(invalid_recorded_history(
16847                        "duplicate_activity_schedule",
16848                        sequence,
16849                        "at most one ActivityScheduled event",
16850                        "multiple ActivityScheduled events",
16851                        "activity history schedules more than one command at one workflow sequence",
16852                    ));
16853                }
16854                let activity_type = activity_events.iter().find_map(|event| {
16855                    event
16856                        .payload
16857                        .get("activity_type")
16858                        .or_else(|| event.payload.get("activity_name"))
16859                        .and_then(Value::as_str)
16860                        .map(str::to_string)
16861                });
16862                if activity_events.iter().filter_map(|event| {
16863                    event
16864                        .payload
16865                        .get("activity_type")
16866                        .or_else(|| event.payload.get("activity_name"))
16867                        .and_then(Value::as_str)
16868                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16869                    return Err(invalid_recorded_history(
16870                        "activity_identity_mismatch",
16871                        sequence,
16872                        activity_type.as_deref().unwrap_or("one activity identity"),
16873                        "conflicting activity identities",
16874                        "activity lifecycle events at one workflow sequence disagree on identity",
16875                    ));
16876                }
16877                let terminal: Vec<_> = activity_events
16878                    .iter()
16879                    .copied()
16880                    .filter(|event| {
16881                        matches!(
16882                            event.event_type.as_str(),
16883                            "ActivityCompleted"
16884                                | "ActivityFailed"
16885                                | "ActivityCancelled"
16886                                | "ActivityTimedOut"
16887                        )
16888                    })
16889                    .collect();
16890                let duplicate_delivery = terminal.first().is_some_and(|first| {
16891                    terminal.iter().all(|event| {
16892                        event.event_type == first.event_type && event.payload == first.payload
16893                    })
16894                });
16895                if terminal.len() > 1 && !duplicate_delivery {
16896                    return Err(invalid_recorded_history(
16897                        "duplicate_activity_terminal_event",
16898                        sequence,
16899                        "at most one terminal activity event",
16900                        "multiple terminal activity events",
16901                        "activity history settles one command more than once",
16902                    ));
16903                }
16904                let outcome = terminal
16905                    .first()
16906                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16907                    .transpose()?;
16908                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16909                let activity_snapshot = activity_events
16910                    .iter()
16911                    .find(|event| event.event_type == "ActivityScheduled")
16912                    .and_then(|event| event.payload.get("activity"))
16913                    .and_then(Value::as_object);
16914                let options = Some(match activity_snapshot {
16915                    Some(activity) => RecordedActivityOptions {
16916                        task_queue: recorded_optional_string(activity, "queue"),
16917                        execution_mode,
16918                        retry_policy: recorded_activity_retry_snapshot(
16919                            activity.get("retry_policy"),
16920                        ),
16921                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16922                    },
16923                    None => RecordedActivityOptions {
16924                        task_queue: RecordedSnapshotValue::Unknown,
16925                        execution_mode,
16926                        retry_policy: recorded_activity_retry_snapshot(None),
16927                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16928                    },
16929                });
16930                return Ok(RecordedCommand::Activity {
16931                    sequence,
16932                    activity_type,
16933                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16934                    options,
16935                    outcome,
16936                    parallel_group_path,
16937                });
16938            }
16939
16940            if !child_events.is_empty() {
16941                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16942                let scheduled: Vec<_> = child_events
16943                    .iter()
16944                    .copied()
16945                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16946                    .collect();
16947                if scheduled.len() != 1 {
16948                    return Err(invalid_recorded_history(
16949                        "child_workflow_schedule_missing_or_duplicate",
16950                        sequence,
16951                        "one ChildWorkflowScheduled event",
16952                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16953                        "child workflow replay requires exactly one recorded schedule event",
16954                    ));
16955                }
16956                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16957                let workflow_type = child_events.iter().find_map(|event| {
16958                    event
16959                        .payload
16960                        .get("child_workflow_type")
16961                        .or_else(|| event.payload.get("workflow_type"))
16962                        .and_then(Value::as_str)
16963                        .filter(|value| !value.is_empty())
16964                        .map(str::to_string)
16965                });
16966                if child_events
16967                    .iter()
16968                    .filter_map(|event| {
16969                        event
16970                            .payload
16971                            .get("child_workflow_type")
16972                            .or_else(|| event.payload.get("workflow_type"))
16973                            .and_then(Value::as_str)
16974                    })
16975                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
16976                {
16977                    return Err(invalid_recorded_history(
16978                        "child_workflow_identity_mismatch",
16979                        sequence,
16980                        workflow_type
16981                            .as_deref()
16982                            .unwrap_or("one child workflow type"),
16983                        "conflicting child workflow types",
16984                        "child workflow lifecycle events at one sequence disagree on type",
16985                    ));
16986                }
16987                let mut outcomes = child_workflow_outcomes(
16988                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
16989                    fallback_codec,
16990                    parent.clone(),
16991                )?;
16992                let terminal_events = child_events
16993                    .iter()
16994                    .copied()
16995                    .filter(|event| event.event_type.starts_with("ChildRun"))
16996                    .collect::<Vec<_>>();
16997                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
16998                    terminal_events.iter().all(|event| {
16999                        event.event_type == first.event_type && event.payload == first.payload
17000                    })
17001                });
17002                if outcomes.len() > 1 && !duplicate_delivery {
17003                    return Err(invalid_recorded_history(
17004                        "duplicate_child_workflow_terminal_event",
17005                        sequence,
17006                        "at most one terminal child event",
17007                        "multiple terminal child events",
17008                        "child workflow history settles one command more than once",
17009                    ));
17010                }
17011                return Ok(RecordedCommand::ChildWorkflow {
17012                    sequence,
17013                    workflow_type,
17014                    policies,
17015                    outcome: outcomes.pop(),
17016                    parallel_group_path,
17017                });
17018            }
17019
17020            if !signal_wait_events.is_empty() {
17021                let opened: Vec<_> = signal_wait_events
17022                    .iter()
17023                    .copied()
17024                    .filter(|event| event.event_type == "SignalWaitOpened")
17025                    .collect();
17026                if opened.len() != 1 {
17027                    return Err(invalid_recorded_history(
17028                        "signal_wait_open_missing_or_duplicate",
17029                        sequence,
17030                        "one SignalWaitOpened event",
17031                        &format!("{} SignalWaitOpened events", opened.len()),
17032                        "signal replay requires exactly one canonical wait-open event",
17033                    ));
17034                }
17035
17036                let applied: Vec<_> = signal_wait_events
17037                    .iter()
17038                    .copied()
17039                    .filter(|event| event.event_type == "SignalApplied")
17040                    .collect();
17041                if applied.len() > 1 {
17042                    return Err(invalid_recorded_history(
17043                        "duplicate_signal_wait_apply",
17044                        sequence,
17045                        "at most one SignalApplied event",
17046                        "multiple SignalApplied events",
17047                        "signal history applies one durable wait more than once",
17048                    ));
17049                }
17050
17051                let signal_names = signal_wait_events
17052                    .iter()
17053                    .map(|event| required_signal_wait_name(event, sequence))
17054                    .collect::<Result<Vec<_>>>()?;
17055                let signal_name = signal_names
17056                    .first()
17057                    .expect("signal wait events are not empty")
17058                    .clone();
17059                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17060                    return Err(invalid_recorded_history(
17061                        "signal_wait_identity_mismatch",
17062                        sequence,
17063                        &signal_name,
17064                        "conflicting signal names",
17065                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17066                    ));
17067                }
17068                let value = applied
17069                    .first()
17070                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17071                    .transpose()?;
17072                return Ok(RecordedCommand::SignalWait {
17073                    sequence,
17074                    signal_name,
17075                    value,
17076                    parallel_group_path: recorded_parallel_group_path(
17077                        &signal_wait_events,
17078                        sequence,
17079                    )?,
17080                });
17081            }
17082
17083            if !condition_wait_events.is_empty() {
17084                return recorded_condition_wait(
17085                    sequence,
17086                    &condition_wait_events,
17087                    events,
17088                );
17089            }
17090
17091            if !search_attribute_events.is_empty() {
17092                if search_attribute_events.len() != 1 {
17093                    return Err(invalid_recorded_history(
17094                        "duplicate_search_attribute_update",
17095                        sequence,
17096                        "one SearchAttributesUpserted event",
17097                        &format!(
17098                            "{} SearchAttributesUpserted events",
17099                            search_attribute_events.len()
17100                        ),
17101                        "search-attribute history records one workflow command more than once",
17102                    ));
17103                }
17104                let payload = &search_attribute_events[0].payload;
17105                let attributes = payload
17106                    .get("attributes")
17107                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17108                    .cloned()
17109                    .ok_or_else(|| {
17110                        invalid_recorded_history(
17111                            "search_attribute_update_missing",
17112                            sequence,
17113                            "non-empty attributes object",
17114                            "missing or invalid attributes",
17115                            "search-attribute history is missing its recorded mutation",
17116                        )
17117                    })?;
17118                let attribute_types =
17119                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17120                return Ok(RecordedCommand::SearchAttributes {
17121                    sequence,
17122                    attributes,
17123                    attribute_types,
17124                });
17125            }
17126
17127            if !side_effect_events.is_empty() {
17128                if side_effect_events.len() != 1 {
17129                    return Err(invalid_recorded_history(
17130                        "duplicate_side_effect_record",
17131                        sequence,
17132                        "one SideEffectRecorded event",
17133                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17134                        "side-effect history records one workflow command more than once",
17135                    ));
17136                }
17137                let event = side_effect_events[0];
17138                let result = event.payload.get("result").ok_or_else(|| {
17139                    invalid_recorded_history(
17140                        "side_effect_result_missing",
17141                        sequence,
17142                        "recorded result payload",
17143                        "missing result",
17144                        "side-effect history is missing its recorded value",
17145                    )
17146                })?;
17147                let has_published_envelope = result.as_str().is_some()
17148                    || result.as_object().is_some_and(|envelope| {
17149                        envelope.get("codec").and_then(Value::as_str).is_some()
17150                            && envelope.get("blob").and_then(Value::as_str).is_some()
17151                    });
17152                if !has_published_envelope {
17153                    return Err(invalid_recorded_history(
17154                        "side_effect_payload_malformed",
17155                        sequence,
17156                        "payload blob or {codec, blob} envelope",
17157                        &result.to_string(),
17158                        "side-effect history result does not use a published payload envelope",
17159                    ));
17160                }
17161                let codec = event
17162                    .payload
17163                    .get("payload_codec")
17164                    .and_then(Value::as_str)
17165                    .unwrap_or(fallback_codec);
17166                let value = decode_wire_avro_value(result, codec).map_err(|error| {
17167                    if error.to_string().contains("unsupported_payload_codec") {
17168                        return error;
17169                    }
17170
17171                    invalid_recorded_history(
17172                        "side_effect_payload_incompatible",
17173                        sequence,
17174                        &format!("valid {codec} payload envelope"),
17175                        &error.to_string(),
17176                        "side-effect history payload cannot be decoded with its recorded codec",
17177                    )
17178                })?;
17179                return Ok(RecordedCommand::SideEffect { sequence, value });
17180            }
17181
17182            if !version_marker_events.is_empty() {
17183                if version_marker_events.len() != 1 {
17184                    return Err(invalid_recorded_history(
17185                        "duplicate_version_marker_record",
17186                        sequence,
17187                        "one VersionMarkerRecorded event",
17188                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
17189                        "version-marker history records one workflow command more than once",
17190                    ));
17191                }
17192                let payload = &version_marker_events[0].payload;
17193                let change_id = payload
17194                    .get("change_id")
17195                    .and_then(Value::as_str)
17196                    .filter(|value| !value.is_empty())
17197                    .map(str::to_string)
17198                    .ok_or_else(|| {
17199                        invalid_recorded_history(
17200                            "version_marker_field_missing",
17201                            sequence,
17202                            "non-empty change_id",
17203                            "missing or invalid change_id",
17204                            "version-marker history is missing its stable change ID",
17205                        )
17206                    })?;
17207                let version = required_version_i32(payload, "version", sequence)?;
17208                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
17209                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
17210                if min_supported > max_supported || version < min_supported || version > max_supported {
17211                    return Err(invalid_recorded_history(
17212                        "version_marker_history_range_invalid",
17213                        sequence,
17214                        "min_supported <= version <= max_supported",
17215                        &format!("{min_supported} <= {version} <= {max_supported}"),
17216                        "recorded version marker contains an internally incompatible range",
17217                    ));
17218                }
17219                return Ok(RecordedCommand::VersionMarker {
17220                    sequence,
17221                    change_id,
17222                    version,
17223                });
17224            }
17225
17226            if !memo_events.is_empty() {
17227                if memo_events.len() != 1 {
17228                    return Err(invalid_recorded_history(
17229                        "duplicate_memo_upsert_record",
17230                        sequence,
17231                        "one MemoUpserted event",
17232                        &format!("{} MemoUpserted events", memo_events.len()),
17233                        "memo history records one workflow update more than once",
17234                    ));
17235                }
17236                let payload = &memo_events[0].payload;
17237                let entries = payload.get("entries").cloned().ok_or_else(|| {
17238                    invalid_recorded_history(
17239                        "memo_entries_missing",
17240                        sequence,
17241                        "memo entries object",
17242                        "missing entries",
17243                        "MemoUpserted history is missing replay identity entries",
17244                    )
17245                })?;
17246                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
17247                    invalid_recorded_history(
17248                        "memo_entries_invalid",
17249                        sequence,
17250                        "valid canonical memo entries",
17251                        &error.to_string(),
17252                        "MemoUpserted history contains invalid replay identity entries",
17253                    )
17254                })?;
17255                let merged = payload.get("merged").cloned().ok_or_else(|| {
17256                    invalid_recorded_history(
17257                        "memo_merged_projection_missing",
17258                        sequence,
17259                        "merged memo projection",
17260                        "missing merged",
17261                        "MemoUpserted history is missing its merged projection",
17262                    )
17263                })?;
17264                decode_memo_history_map(&merged, false).map_err(|error| {
17265                    invalid_recorded_history(
17266                        "memo_merged_projection_invalid",
17267                        sequence,
17268                        "valid merged memo projection",
17269                        &error.to_string(),
17270                        "MemoUpserted history contains an invalid merged projection",
17271                    )
17272                })?;
17273
17274                return Ok(RecordedCommand::Memo { sequence, entries });
17275            }
17276            let scheduled: Vec<_> = timer_events
17277                .iter()
17278                .copied()
17279                .filter(|event| event.event_type == "TimerScheduled")
17280                .collect();
17281            let fired: Vec<_> = timer_events
17282                .iter()
17283                .copied()
17284                .filter(|event| event.event_type == "TimerFired")
17285                .collect();
17286            if scheduled.len() != 1 {
17287                return Err(invalid_recorded_history(
17288                    "timer_schedule_missing_or_duplicate",
17289                    sequence,
17290                    "one TimerScheduled event",
17291                    &format!("{} TimerScheduled events", scheduled.len()),
17292                    "timer replay requires exactly one recorded schedule event",
17293                ));
17294            }
17295            if fired.len() > 1 {
17296                return Err(invalid_recorded_history(
17297                    "duplicate_timer_fire",
17298                    sequence,
17299                    "at most one TimerFired event",
17300                    "multiple TimerFired events",
17301                    "timer history contains more than one fire event for a workflow sequence",
17302                ));
17303            }
17304
17305            let scheduled = scheduled[0];
17306            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17307            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17308            if let Some(fired) = fired.first() {
17309                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17310                if fired_timer_id != timer_id {
17311                    return Err(invalid_recorded_history(
17312                        "timer_identity_mismatch",
17313                        sequence,
17314                        &timer_id,
17315                        &fired_timer_id,
17316                        "TimerFired does not correspond to the recorded TimerScheduled event",
17317                    ));
17318                }
17319                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17320                if fired_delay != delay_seconds {
17321                    return Err(invalid_recorded_history(
17322                        "timer_history_delay_mismatch",
17323                        sequence,
17324                        &delay_seconds.to_string(),
17325                        &fired_delay.to_string(),
17326                        "TimerScheduled and TimerFired record different delays",
17327                    ));
17328                }
17329            }
17330
17331            Ok(RecordedCommand::Timer {
17332                sequence,
17333                delay_seconds,
17334                fired: !fired.is_empty(),
17335                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
17336            })
17337        })
17338        .collect::<Result<_>>()?;
17339
17340    let mut marker_decisions = HashMap::new();
17341    for command in &commands {
17342        if let RecordedCommand::VersionMarker {
17343            sequence,
17344            change_id,
17345            version,
17346        } = command
17347        {
17348            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
17349                if version != first_version {
17350                    return Err(invalid_recorded_history(
17351                        "version_marker_conflict",
17352                        *sequence,
17353                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
17354                        &format!("version {version} at sequence {sequence}"),
17355                        "workflow history contains conflicting decisions for one stable change ID",
17356                    ));
17357                }
17358            } else {
17359                marker_decisions.insert(change_id.clone(), (*version, *sequence));
17360            }
17361        }
17362    }
17363
17364    Ok(commands)
17365}
17366
17367fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
17368    payload
17369        .get(field)
17370        .and_then(Value::as_i64)
17371        .and_then(|value| i32::try_from(value).ok())
17372        .ok_or_else(|| {
17373            invalid_recorded_history(
17374                "version_marker_field_missing",
17375                sequence,
17376                &format!("integer {field}"),
17377                "missing or out-of-range integer",
17378                "version-marker history is missing a required integer field",
17379            )
17380        })
17381}
17382
17383fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
17384    event
17385        .payload
17386        .get("sequence")
17387        .or_else(|| event.payload.get("workflow_sequence"))
17388        .or_else(|| event.raw.get("sequence"))
17389        .or_else(|| event.raw.get("workflow_sequence"))
17390        .and_then(value_as_u64)
17391}
17392
17393fn is_internal_timer_event(event: &HistoryEvent) -> bool {
17394    matches!(
17395        event
17396            .payload
17397            .get("timer_kind")
17398            .or_else(|| event.raw.get("timer_kind"))
17399            .and_then(Value::as_str),
17400        Some("condition_timeout" | "signal_timeout")
17401    )
17402}
17403
17404fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
17405    matches!(
17406        event.event_type.as_str(),
17407        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17408    )
17409}
17410
17411fn recorded_condition_wait(
17412    sequence: u64,
17413    condition_events: &[&HistoryEvent],
17414    all_events: &[HistoryEvent],
17415) -> Result<RecordedCommand> {
17416    let opened = condition_events
17417        .iter()
17418        .copied()
17419        .filter(|event| event.event_type == "ConditionWaitOpened")
17420        .collect::<Vec<_>>();
17421    if opened.len() != 1 {
17422        return Err(invalid_recorded_history(
17423            "condition_wait_open_missing_or_duplicate",
17424            sequence,
17425            "one ConditionWaitOpened event",
17426            &format!("{} ConditionWaitOpened events", opened.len()),
17427            "condition replay requires exactly one canonical wait-open event",
17428        ));
17429    }
17430    let terminal = condition_events
17431        .iter()
17432        .copied()
17433        .filter(|event| {
17434            matches!(
17435                event.event_type.as_str(),
17436                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17437            )
17438        })
17439        .collect::<Vec<_>>();
17440    if terminal.len() > 1 {
17441        return Err(invalid_recorded_history(
17442            "duplicate_condition_wait_terminal_event",
17443            sequence,
17444            "at most one condition terminal event",
17445            "multiple condition terminal events",
17446            "condition history settles one durable wait more than once",
17447        ));
17448    }
17449
17450    let opened = opened[0];
17451    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
17452    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
17453    for event in condition_events
17454        .iter()
17455        .copied()
17456        .filter(|event| !std::ptr::eq(*event, opened))
17457    {
17458        let event_wait_id = required_condition_wait_id(event, sequence)?;
17459        if event_wait_id != condition_wait_id {
17460            return Err(invalid_recorded_history(
17461                "condition_wait_id_mismatch",
17462                sequence,
17463                &condition_wait_id,
17464                &event_wait_id,
17465                "condition lifecycle events at one sequence disagree on wait identity",
17466            ));
17467        }
17468        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
17469        if event_occurrence_id != occurrence_id {
17470            return Err(invalid_recorded_history(
17471                "condition_wait_occurrence_history_mismatch",
17472                sequence,
17473                &occurrence_id,
17474                &event_occurrence_id,
17475                "condition lifecycle events at one sequence disagree on authored occurrence identity",
17476            ));
17477        }
17478    }
17479
17480    let condition_key = optional_non_empty_history_string(opened, "condition_key");
17481    let predicate_identity = opened
17482        .payload
17483        .get("condition_definition_fingerprint")
17484        .and_then(Value::as_str)
17485        .filter(|value| !value.is_empty())
17486        .map(str::to_string)
17487        .ok_or_else(|| {
17488            invalid_recorded_history(
17489                "condition_wait_predicate_fingerprint_missing",
17490                sequence,
17491                "non-empty condition_definition_fingerprint",
17492                &opened.event_type,
17493                "canonical condition history is missing its predicate identity",
17494            )
17495        })?;
17496    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
17497    for event in condition_events
17498        .iter()
17499        .copied()
17500        .filter(|event| !std::ptr::eq(*event, opened))
17501    {
17502        for (field, opened_value) in [
17503            ("condition_key", condition_key.as_deref()),
17504            (
17505                "condition_definition_fingerprint",
17506                Some(predicate_identity.as_str()),
17507            ),
17508        ] {
17509            if let Some(value) = optional_non_empty_history_string(event, field) {
17510                if opened_value.is_some_and(|opened_value| opened_value != value) {
17511                    return Err(invalid_recorded_history(
17512                        "condition_wait_definition_history_mismatch",
17513                        sequence,
17514                        opened_value.unwrap_or_default(),
17515                        &value,
17516                        "condition lifecycle events disagree on the recorded definition",
17517                    ));
17518                }
17519            }
17520        }
17521        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
17522            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
17523                return Err(invalid_recorded_history(
17524                    "condition_wait_definition_history_mismatch",
17525                    sequence,
17526                    &format!("{}s", timeout_seconds.unwrap_or_default()),
17527                    &format!("{event_timeout}s"),
17528                    "condition lifecycle events disagree on the recorded timeout",
17529                ));
17530            }
17531        }
17532    }
17533
17534    let timeout_timer_events = all_events
17535        .iter()
17536        .filter(|event| {
17537            matches!(
17538                event.event_type.as_str(),
17539                "TimerScheduled" | "TimerCancelled" | "TimerFired"
17540            ) && event.payload.get("timer_kind").and_then(Value::as_str)
17541                == Some("condition_timeout")
17542                && event
17543                    .payload
17544                    .get("condition_wait_id")
17545                    .and_then(Value::as_str)
17546                    == Some(condition_wait_id.as_str())
17547        })
17548        .collect::<Vec<_>>();
17549    let scheduled = timeout_timer_events
17550        .iter()
17551        .copied()
17552        .filter(|event| event.event_type == "TimerScheduled")
17553        .collect::<Vec<_>>();
17554    let fired = timeout_timer_events
17555        .iter()
17556        .copied()
17557        .filter(|event| event.event_type == "TimerFired")
17558        .collect::<Vec<_>>();
17559    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
17560        return Err(invalid_recorded_history(
17561            "condition_wait_timeout_history_invalid",
17562            sequence,
17563            "one timeout schedule and at most one fire",
17564            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
17565            "condition timeout history has a missing or duplicate lifecycle event",
17566        ));
17567    }
17568    if let Some(scheduled) = scheduled.first() {
17569        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17570        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17571        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
17572            return Err(invalid_recorded_history(
17573                "condition_wait_timeout_delay_mismatch",
17574                sequence,
17575                &format!("{}s", timeout_seconds.unwrap_or_default()),
17576                &format!("{delay_seconds}s"),
17577                "condition timeout timer differs from the wait definition",
17578            ));
17579        }
17580        if let Some(fired) = fired.first() {
17581            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17582            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17583            if fired_timer_id != timer_id || fired_delay != delay_seconds {
17584                return Err(invalid_recorded_history(
17585                    "condition_wait_timeout_identity_mismatch",
17586                    sequence,
17587                    &format!("{timer_id}:{delay_seconds}s"),
17588                    &format!("{fired_timer_id}:{fired_delay}s"),
17589                    "condition timeout fire does not match its durable schedule",
17590                ));
17591            }
17592        }
17593    }
17594
17595    let result = terminal.first().map(|event| {
17596        if event.event_type == "ConditionWaitTimedOut" {
17597            ConditionWaitResult::TimedOut
17598        } else {
17599            ConditionWaitResult::Satisfied
17600        }
17601    });
17602    let result = if !fired.is_empty() {
17603        if result == Some(ConditionWaitResult::Satisfied) {
17604            return Err(invalid_recorded_history(
17605                "condition_wait_terminal_conflict",
17606                sequence,
17607                "one satisfied or timed-out outcome",
17608                "satisfied event and fired timeout",
17609                "condition history records conflicting terminal outcomes",
17610            ));
17611        }
17612        Some(ConditionWaitResult::TimedOut)
17613    } else {
17614        result
17615    };
17616
17617    Ok(RecordedCommand::ConditionWait {
17618        sequence,
17619        occurrence_id,
17620        condition_key,
17621        predicate_identity,
17622        timeout_seconds,
17623        result,
17624        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17625    })
17626}
17627
17628fn recorded_condition_group_path(
17629    condition_events: &[&HistoryEvent],
17630    all_events: &[HistoryEvent],
17631    sequence: u64,
17632) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17633    let opened = condition_events
17634        .iter()
17635        .copied()
17636        .find(|event| event.event_type == "ConditionWaitOpened")
17637        .expect("canonical condition opener is validated first");
17638    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17639    let previous_events = all_events
17640        .iter()
17641        .take_while(|event| !std::ptr::eq(*event, opened))
17642        .collect::<Vec<_>>();
17643    let originals = previous_events
17644        .iter()
17645        .copied()
17646        .filter(|event| event.event_type == "ConditionWaitOpened")
17647        .filter(|event| {
17648            event
17649                .payload
17650                .get("condition_wait_occurrence_id")
17651                .and_then(Value::as_str)
17652                == Some(occurrence.as_str())
17653        })
17654        .collect::<Vec<_>>();
17655    let Some(original) = originals.first().copied() else {
17656        return recorded_parallel_group_path(condition_events, sequence);
17657    };
17658    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17659    if authored_sequence == sequence {
17660        return recorded_parallel_group_path(condition_events, sequence);
17661    }
17662    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17663    if original_path.is_none() {
17664        return recorded_parallel_group_path(condition_events, sequence);
17665    }
17666    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17667    let identity_matches = [
17668        "condition_key",
17669        "condition_definition_fingerprint",
17670        "timeout_seconds",
17671    ]
17672    .iter()
17673    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17674    let previous = originals
17675        .iter()
17676        .copied()
17677        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17678        .max_by_key(|event| durable_event_sequence(event));
17679    let previously_satisfied = previous.is_some_and(|previous| {
17680        previous_events.iter().any(|event| {
17681            event.event_type == "ConditionWaitSatisfied"
17682                && event.payload.get("condition_wait_id")
17683                    == previous.payload.get("condition_wait_id")
17684                && event.payload.get("condition_wait_occurrence_id")
17685                    == previous.payload.get("condition_wait_occurrence_id")
17686                && durable_event_sequence(event) == durable_event_sequence(previous)
17687        })
17688    });
17689    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17690        return Err(invalid_recorded_history(
17691            "condition_wait_group_reopen_mismatch",
17692            sequence,
17693            "same authored condition and group path after a satisfied physical wait",
17694            &opened.payload.to_string(),
17695            "grouped condition reopen has no matching recorded predecessor",
17696        ));
17697    }
17698    Ok(reopened_path)
17699}
17700
17701fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17702    event
17703        .payload
17704        .get("condition_wait_occurrence_id")
17705        .and_then(Value::as_str)
17706        .filter(|value| !value.is_empty())
17707        .map(str::to_string)
17708        .ok_or_else(|| {
17709            invalid_recorded_history(
17710                "condition_wait_occurrence_id_missing",
17711                sequence,
17712                "non-empty condition_wait_occurrence_id",
17713                &event.event_type,
17714                "condition history is missing authored occurrence identity",
17715            )
17716        })
17717}
17718
17719fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17720    event
17721        .payload
17722        .get("condition_wait_id")
17723        .and_then(Value::as_str)
17724        .filter(|value| !value.is_empty())
17725        .map(str::to_string)
17726        .ok_or_else(|| {
17727            invalid_recorded_history(
17728                "condition_wait_id_missing",
17729                sequence,
17730                "non-empty condition_wait_id",
17731                &event.event_type,
17732                "canonical condition history is missing its durable wait identity",
17733            )
17734        })
17735}
17736
17737fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17738    event
17739        .payload
17740        .get(field)
17741        .and_then(Value::as_str)
17742        .filter(|value| !value.is_empty())
17743        .map(str::to_string)
17744}
17745
17746fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17747    match event.payload.get(field) {
17748        None | Some(Value::Null) => Ok(None),
17749        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17750            invalid_recorded_history(
17751                "condition_wait_definition_invalid",
17752                sequence,
17753                &format!("non-negative integer {field}"),
17754                &value.to_string(),
17755                "condition history contains an invalid numeric definition field",
17756            )
17757        }),
17758    }
17759}
17760
17761fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17762    event
17763        .payload
17764        .get("signal_name")
17765        .or_else(|| event.raw.get("signal_name"))
17766        .and_then(Value::as_str)
17767        .filter(|value| !value.is_empty())
17768        .map(str::to_string)
17769        .ok_or_else(|| {
17770            invalid_recorded_history(
17771                "signal_wait_name_missing",
17772                sequence,
17773                "non-empty signal_name",
17774                &event.event_type,
17775                "canonical signal-wait history is missing its signal identity",
17776            )
17777        })
17778}
17779
17780fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17781    // Applying a buffered control-plane signal has no authored call sequence.
17782    // Its outer sequence orders history events and must not become a wait.
17783    if event.event_type == "SignalApplied"
17784        && event
17785            .payload
17786            .get("signal_wait_id")
17787            .and_then(Value::as_str)
17788            .is_some_and(|id| id.starts_with("signal-command:"))
17789        && event.payload.get("sequence").is_none()
17790        && event.payload.get("workflow_sequence").is_none()
17791    {
17792        return false;
17793    }
17794    matches!(
17795        event.event_type.as_str(),
17796        "SignalWaitOpened" | "SignalApplied"
17797    )
17798}
17799
17800fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17801    event
17802        .payload
17803        .get(field)
17804        .and_then(Value::as_str)
17805        .filter(|value| !value.is_empty())
17806        .map(str::to_string)
17807        .ok_or_else(|| {
17808            invalid_recorded_history(
17809                "timer_history_field_missing",
17810                sequence,
17811                field,
17812                &event.event_type,
17813                "timer history is missing a required identity field",
17814            )
17815        })
17816}
17817
17818fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17819    event
17820        .payload
17821        .get(field)
17822        .and_then(value_as_u64)
17823        .ok_or_else(|| {
17824            invalid_recorded_history(
17825                "timer_history_field_missing",
17826                sequence,
17827                field,
17828                &event.event_type,
17829                "timer history is missing a required numeric field",
17830            )
17831        })
17832}
17833
17834fn recorded_search_attribute_types(
17835    payload: &Value,
17836    attributes: &Value,
17837    sequence: u64,
17838) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17839    let Some(raw_types) = payload.get("attribute_types") else {
17840        // This is the explicit compatibility rule for histories recorded
17841        // before typed identity was persisted. Values still constrain replay;
17842        // the unknown type snapshot does not assert a typed match.
17843        return Ok(RecordedSnapshotValue::Unknown);
17844    };
17845    let Some(raw_types) = raw_types.as_object() else {
17846        return Err(invalid_recorded_history(
17847            "search_attribute_types_malformed",
17848            sequence,
17849            "canonical attribute type map",
17850            &raw_types.to_string(),
17851            "search-attribute history contains malformed type identity",
17852        ));
17853    };
17854    let attribute_keys = attributes
17855        .as_object()
17856        .expect("recorded search attributes were validated as an object");
17857    let mut types = BTreeMap::new();
17858    for (key, value) in raw_types {
17859        let Some(attribute_type) = value.as_str() else {
17860            return Err(invalid_recorded_history(
17861                "search_attribute_types_malformed",
17862                sequence,
17863                "canonical string type name",
17864                &value.to_string(),
17865                "search-attribute history contains a non-string type identity",
17866            ));
17867        };
17868        if !attribute_keys.contains_key(key)
17869            || !matches!(
17870                attribute_type,
17871                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17872            )
17873        {
17874            return Err(invalid_recorded_history(
17875                "search_attribute_types_malformed",
17876                sequence,
17877                "canonical types for keys present in attributes",
17878                &format!("{key}:{attribute_type}"),
17879                "search-attribute history contains unsupported or orphaned type identity",
17880            ));
17881        }
17882        types.insert(key.clone(), attribute_type.to_string());
17883    }
17884    Ok(RecordedSnapshotValue::Known(types))
17885}
17886
17887fn invalid_recorded_history(
17888    reason: &str,
17889    sequence: u64,
17890    expected: &str,
17891    actual: &str,
17892    message: &str,
17893) -> Error {
17894    Error::NonDeterministicReplay(ReplayFailure::new(
17895        reason,
17896        Some(sequence),
17897        Some(expected.to_string()),
17898        Some(actual.to_string()),
17899        message,
17900    ))
17901}
17902
17903type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17904
17905fn activity_outcome(
17906    event: &HistoryEvent,
17907    fallback_codec: &str,
17908    recorded_activity_type: Option<String>,
17909) -> Result<ActivityOutcome> {
17910    if event.event_type == "ActivityCompleted" {
17911        let codec = event
17912            .payload
17913            .get("payload_codec")
17914            .and_then(Value::as_str)
17915            .unwrap_or(fallback_codec);
17916        return Ok(Ok(decode_wire_avro_value(
17917            event.payload.get("result").unwrap_or(&Value::Null),
17918            codec,
17919        )?));
17920    }
17921
17922    let payload = &event.payload;
17923    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17924        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17925        "ActivityCancelled" => (
17926            ActivityFailureKind::Cancelled,
17927            "cancelled",
17928            "activity was cancelled",
17929        ),
17930        "ActivityTimedOut" => (
17931            ActivityFailureKind::TimedOut,
17932            "timeout",
17933            "activity timed out",
17934        ),
17935        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17936    };
17937    let exception = payload
17938        .get("exception")
17939        .filter(|value| !value.is_null())
17940        .cloned();
17941    let failure_category = payload_string(payload, "failure_category");
17942    let timeout_kind = payload_string(payload, "timeout_kind");
17943    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17944        ActivityFailureKind::Failed => failure_category
17945            .clone()
17946            .unwrap_or_else(|| fallback_reason.to_string()),
17947        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17948        ActivityFailureKind::TimedOut => timeout_kind
17949            .clone()
17950            .unwrap_or_else(|| fallback_reason.to_string()),
17951    });
17952    let message = payload_string(payload, "message")
17953        .or_else(|| {
17954            exception
17955                .as_ref()
17956                .and_then(|value| payload_string(value, "message"))
17957        })
17958        .unwrap_or_else(|| fallback_message.to_string());
17959
17960    Ok(Err(ActivityFailure {
17961        kind,
17962        reason,
17963        message,
17964        activity_execution_id: payload_string(payload, "activity_execution_id"),
17965        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17966        activity_type: payload_string(payload, "activity_type")
17967            .or_else(|| payload_string(payload, "activity_name"))
17968            .or(recorded_activity_type),
17969        activity_class: payload_string(payload, "activity_class"),
17970        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17971        failure_id: payload_string(payload, "failure_id"),
17972        failure_category,
17973        timeout_kind,
17974        non_retryable: payload
17975            .get("non_retryable")
17976            .and_then(Value::as_bool)
17977            .unwrap_or(false),
17978        exception_type: payload_string(payload, "exception_type").or_else(|| {
17979            exception
17980                .as_ref()
17981                .and_then(|value| payload_string(value, "type"))
17982        }),
17983        exception_class: payload_string(payload, "exception_class").or_else(|| {
17984            exception
17985                .as_ref()
17986                .and_then(|value| payload_string(value, "class"))
17987        }),
17988        code: payload
17989            .get("code")
17990            .filter(|value| !value.is_null())
17991            .cloned(),
17992        exception,
17993    }))
17994}
17995
17996type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
17997
17998fn child_workflow_outcomes(
17999    events: &[HistoryEvent],
18000    fallback_codec: &str,
18001    parent: WorkflowIdentity,
18002) -> Result<Vec<ChildWorkflowOutcome>> {
18003    let mut outcomes = Vec::new();
18004
18005    for event in events {
18006        let kind = match event.event_type.as_str() {
18007            "ChildRunCompleted" => None,
18008            "ChildRunFailed" => Some((
18009                ChildWorkflowFailureKind::Failed,
18010                "child_workflow",
18011                "child workflow failed",
18012            )),
18013            "ChildRunCancelled" => Some((
18014                ChildWorkflowFailureKind::Cancelled,
18015                "cancelled",
18016                "child workflow was cancelled",
18017            )),
18018            "ChildRunTerminated" => Some((
18019                ChildWorkflowFailureKind::Terminated,
18020                "terminated",
18021                "child workflow was terminated",
18022            )),
18023            _ => continue,
18024        };
18025        let payload = &event.payload;
18026        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
18027        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
18028        let child_workflow_type = payload_string(payload, "child_workflow_type");
18029
18030        if let Some((kind, reason, fallback_message)) = kind {
18031            let exception = payload
18032                .get("exception")
18033                .filter(|value| !value.is_null())
18034                .cloned();
18035            let message = payload_string(payload, "message")
18036                .or_else(|| {
18037                    exception
18038                        .as_ref()
18039                        .and_then(|value| payload_string(value, "message"))
18040                })
18041                .unwrap_or_else(|| fallback_message.to_string());
18042            let exception_type = payload_string(payload, "exception_type").or_else(|| {
18043                exception
18044                    .as_ref()
18045                    .and_then(|value| payload_string(value, "type"))
18046            });
18047            let exception_class = payload_string(payload, "exception_class").or_else(|| {
18048                exception
18049                    .as_ref()
18050                    .and_then(|value| payload_string(value, "class"))
18051            });
18052            outcomes.push(Err(ChildWorkflowFailure {
18053                kind,
18054                reason: reason.to_string(),
18055                message,
18056                parent_workflow_id: parent.workflow_id.clone(),
18057                parent_workflow_run_id: parent.run_id.clone(),
18058                child_workflow_id,
18059                child_workflow_run_id,
18060                child_workflow_type,
18061                failure_id: payload_string(payload, "failure_id"),
18062                failure_category: payload_string(payload, "failure_category"),
18063                exception_type,
18064                exception_class,
18065                non_retryable: payload
18066                    .get("non_retryable")
18067                    .and_then(Value::as_bool)
18068                    .unwrap_or(false),
18069                code: payload
18070                    .get("code")
18071                    .filter(|value| !value.is_null())
18072                    .cloned(),
18073                exception,
18074            }));
18075            continue;
18076        }
18077
18078        let codec = payload
18079            .get("payload_codec")
18080            .and_then(Value::as_str)
18081            .unwrap_or(fallback_codec);
18082        let result = payload
18083            .get("result")
18084            .or_else(|| payload.get("output"))
18085            .unwrap_or(&Value::Null);
18086        outcomes.push(Ok(ChildWorkflowAvroResult {
18087            parent: parent.clone(),
18088            child: WorkflowIdentity {
18089                workflow_id: child_workflow_id,
18090                run_id: child_workflow_run_id,
18091            },
18092            child_workflow_type,
18093            result: decode_wire_avro_value(result, codec)?,
18094        }));
18095    }
18096
18097    Ok(outcomes)
18098}
18099
18100fn payload_string(payload: &Value, key: &str) -> Option<String> {
18101    payload
18102        .get(key)
18103        .and_then(Value::as_str)
18104        .filter(|value| !value.is_empty())
18105        .map(str::to_string)
18106}
18107
18108fn recorded_activity_failure_boundary(
18109    ctx: &WorkflowContext,
18110    error: &Error,
18111) -> Option<(u64, String)> {
18112    let Error::ActivityFailed(failure) = error else {
18113        return None;
18114    };
18115    if failure.kind != ActivityFailureKind::Failed {
18116        return None;
18117    }
18118    let activity_execution_id = failure
18119        .activity_execution_id
18120        .as_deref()
18121        .filter(|value| !value.is_empty())?;
18122    let state = ctx.state.lock().ok()?;
18123    let mut matches = state.recorded_commands.iter().filter_map(|command| {
18124        let RecordedCommand::Activity {
18125            sequence,
18126            outcome: Some(Err(recorded_failure)),
18127            ..
18128        } = command
18129        else {
18130            return None;
18131        };
18132        (*sequence > 0 && recorded_failure == failure)
18133            .then_some((*sequence, activity_execution_id.to_string()))
18134    });
18135    let boundary = matches.next()?;
18136    matches.next().is_none().then_some(boundary)
18137}
18138
18139fn workflow_failure_command(
18140    error: &Error,
18141    failed_activity_boundary: Option<(u64, String)>,
18142) -> Value {
18143    let (exception_type, exception_class, properties) = match error {
18144        Error::NexusOperationFailed(failure) => (
18145            "NexusOperationFailed",
18146            "durable_workflow::NexusOperationFailure",
18147            json!({"service_call_id":failure.service_call_id, "status":failure.status,
18148                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
18149        ),
18150        Error::ActivityFailed(failure) => (
18151            match failure.kind {
18152                ActivityFailureKind::Failed => "ActivityFailed",
18153                ActivityFailureKind::Cancelled => "ActivityCancelled",
18154                ActivityFailureKind::TimedOut => "ActivityTimedOut",
18155            },
18156            "durable_workflow::ActivityFailure",
18157            json!({
18158                "reason": failure.reason,
18159                "activity_execution_id": failure.activity_execution_id,
18160                "activity_attempt_id": failure.activity_attempt_id,
18161                "activity_type": failure.activity_type,
18162                "activity_class": failure.activity_class,
18163                "attempt_number": failure.attempt_number,
18164                "failure_id": failure.failure_id,
18165                "failure_category": failure.failure_category,
18166                "timeout_kind": failure.timeout_kind,
18167                "activity_non_retryable": failure.non_retryable,
18168                "activity_exception_type": failure.exception_type,
18169                "activity_exception_class": failure.exception_class,
18170                "activity_code": failure.code,
18171                "activity_exception": failure.exception,
18172            }),
18173        ),
18174        Error::ChildWorkflowFailed(failure) => (
18175            match failure.kind {
18176                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18177                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18178                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18179            },
18180            "durable_workflow::ChildWorkflowFailure",
18181            json!({
18182                "reason": failure.reason,
18183                "parent_workflow_id": failure.parent_workflow_id,
18184                "parent_workflow_run_id": failure.parent_workflow_run_id,
18185                "child_workflow_id": failure.child_workflow_id,
18186                "child_workflow_run_id": failure.child_workflow_run_id,
18187                "child_workflow_type": failure.child_workflow_type,
18188                "failure_id": failure.failure_id,
18189                "failure_category": failure.failure_category,
18190                "child_exception_type": failure.exception_type,
18191                "child_exception_class": failure.exception_class,
18192                "child_non_retryable": failure.non_retryable,
18193                "child_code": failure.code,
18194                "child_exception": failure.exception,
18195            }),
18196        ),
18197        Error::ParallelFailed(failure) => (
18198            "ParallelFailed",
18199            "durable_workflow::ParallelFailure",
18200            json!({
18201                "parallel_group_id": failure.group_id,
18202                "parallel_member_path": failure.member_path,
18203                "parallel_group_path": failure.group_path,
18204                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
18205                "cause_type": workflow_error_type(&failure.cause),
18206                "cause_message": failure.cause.to_string(),
18207            }),
18208        ),
18209        Error::SagaCompensationFailed(failure) => (
18210            "SagaCompensationFailed",
18211            "durable_workflow::SagaCompensationFailure",
18212            json!({
18213                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
18214                "initiating_failure_message": failure.initiating_failure.to_string(),
18215                "compensation_activity_type": failure.compensation_activity_type,
18216                "compensation_registration_order": failure.compensation_registration_order,
18217                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
18218                "compensation_failure_message": failure.compensation_failure.to_string(),
18219            }),
18220        ),
18221        Error::WorkflowCancellationRequested(_) => (
18222            "WorkflowCancellationRequested",
18223            "durable_workflow::WorkflowCancellationRequested",
18224            json!({"reason": "cancelled"}),
18225        ),
18226        Error::CooperativeCancellationRequested(cancellation) => (
18227            "WorkflowCancellationRequested",
18228            "durable_workflow::CooperativeCancellationRequested",
18229            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
18230                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
18231        ),
18232        Error::CancellationScopeRequested(cancellation) => (
18233            "WorkflowCancellationRequested",
18234            "durable_workflow::CancellationScopeRequested",
18235            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
18236                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
18237                "cancellation":cancellation.context.to_value()}),
18238        ),
18239        Error::NonDeterministicReplay(_) => (
18240            "NonDeterministicReplay",
18241            "durable_workflow::Error",
18242            Value::Null,
18243        ),
18244        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
18245    };
18246    let non_retryable = match error {
18247        Error::ActivityFailed(failure) => failure.non_retryable,
18248        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18249        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18250        Error::SagaCompensationFailed(failure) => {
18251            workflow_error_non_retryable(&failure.compensation_failure)
18252        }
18253        Error::WorkflowCancellationRequested(_)
18254        | Error::CooperativeCancellationRequested(_)
18255        | Error::CancellationScopeRequested(_) => true,
18256        Error::NonDeterministicReplay(_) => true,
18257        _ => false,
18258    };
18259
18260    let mut command = json!({
18261        "type": "fail_workflow",
18262        "message": error.to_string(),
18263        "exception_type": exception_type,
18264        "exception_class": exception_class,
18265        "non_retryable": non_retryable,
18266        "exception": {
18267            "type": exception_type,
18268            "class": exception_class,
18269            "message": error.to_string(),
18270            "properties": properties,
18271        }
18272    });
18273
18274    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
18275        command["failed_step_sequence"] = json!(sequence);
18276        command["failed_activity_execution_id"] = json!(activity_execution_id);
18277    }
18278
18279    command
18280}
18281
18282fn workflow_error_type(error: &Error) -> &'static str {
18283    match error {
18284        Error::NexusOperationFailed(_) => "NexusOperationFailed",
18285        Error::ActivityFailed(failure) => match failure.kind {
18286            ActivityFailureKind::Failed => "ActivityFailed",
18287            ActivityFailureKind::Cancelled => "ActivityCancelled",
18288            ActivityFailureKind::TimedOut => "ActivityTimedOut",
18289        },
18290        Error::ChildWorkflowFailed(failure) => match failure.kind {
18291            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18292            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18293            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18294        },
18295        Error::ParallelFailed(_) => "ParallelFailed",
18296        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
18297        Error::WorkflowCancellationRequested(_)
18298        | Error::CooperativeCancellationRequested(_)
18299        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
18300        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
18301        _ => "RustWorkflowError",
18302    }
18303}
18304
18305fn workflow_error_non_retryable(error: &Error) -> bool {
18306    match error {
18307        Error::ActivityFailed(failure) => failure.non_retryable,
18308        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18309        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18310        Error::SagaCompensationFailed(failure) => {
18311            workflow_error_non_retryable(&failure.compensation_failure)
18312        }
18313        Error::WorkflowCancellationRequested(_)
18314        | Error::CooperativeCancellationRequested(_)
18315        | Error::CancellationScopeRequested(_)
18316        | Error::NonDeterministicReplay(_) => true,
18317        _ => false,
18318    }
18319}
18320
18321fn workflow_task_integrity_error(error: &Error) -> bool {
18322    matches!(
18323        error,
18324        Error::NonDeterministicReplay(_)
18325            | Error::Protocol(_)
18326            | Error::CancellationScopeExecutionUnavailable
18327            | Error::MissingWorkflowCommandIdentity
18328            | Error::WorkflowStatePoisoned
18329    )
18330}
18331
18332fn decode_signal_event_arguments(
18333    event: &HistoryEvent,
18334    fallback_codec: &str,
18335) -> Result<Vec<AvroValue>> {
18336    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18337    validate_payload_codec(codec)?;
18338    let raw = signal_history_payload(&event.payload);
18339    let decoded = match raw.filter(|value| !value.is_null()) {
18340        Some(value) => decode_wire_avro_value(value, codec)?,
18341        None => AvroValue::Array(Vec::new()),
18342    };
18343    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18344        unreachable!("normalize_avro_arguments always returns an array");
18345    };
18346    Ok(arguments)
18347}
18348
18349fn decode_update_event_arguments(
18350    event: &HistoryEvent,
18351    fallback_codec: &str,
18352) -> Result<Vec<AvroValue>> {
18353    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18354    validate_payload_codec(codec)?;
18355    let decoded = match event
18356        .payload
18357        .get("arguments")
18358        .filter(|value| !value.is_null())
18359    {
18360        Some(value) => decode_wire_avro_value(value, codec)?,
18361        None => AvroValue::Array(Vec::new()),
18362    };
18363    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18364        unreachable!("normalize_avro_arguments always returns an array");
18365    };
18366    Ok(arguments)
18367}
18368
18369fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18370    let Some(export_events) = task
18371        .history_export
18372        .as_ref()
18373        .and_then(|export| export.get("history_events"))
18374        .and_then(Value::as_array)
18375    else {
18376        return Ok(());
18377    };
18378
18379    if export_events.len() > task.history_events.len() {
18380        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
18381    }
18382
18383    Ok(())
18384}
18385
18386fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18387    let Some(export) = task.history_export.as_ref() else {
18388        return Ok(());
18389    };
18390    let signals = export
18391        .get("signals")
18392        .and_then(Value::as_array)
18393        .cloned()
18394        .unwrap_or_default();
18395    let activities = export
18396        .get("activities")
18397        .and_then(Value::as_array)
18398        .cloned()
18399        .unwrap_or_default();
18400    let export_codec = export
18401        .get("payloads")
18402        .and_then(|payloads| payloads.get("codec"))
18403        .and_then(Value::as_str)
18404        .unwrap_or(&task.payload_codec)
18405        .to_string();
18406    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
18407
18408    for event in &mut task.history_events {
18409        if event.event_type == "ActivityCompleted" {
18410            let sequence = event
18411                .payload
18412                .get("sequence")
18413                .or_else(|| event.payload.get("workflow_sequence"))
18414                .and_then(value_as_u64);
18415            let Some(activity) = sequence.and_then(|sequence| {
18416                activities.iter().find(|activity| {
18417                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
18418                })
18419            }) else {
18420                continue;
18421            };
18422            let Some(payload) = event.payload.as_object_mut() else {
18423                continue;
18424            };
18425            if missing_payload(payload.get("result")) {
18426                if let Some(result) = activity
18427                    .get("result")
18428                    .filter(|value| !missing_payload(Some(value)))
18429                {
18430                    payload.insert("result".to_string(), result.clone());
18431                }
18432            }
18433            for field in ["payload_codec", "activity_type"] {
18434                if payload
18435                    .get(field)
18436                    .and_then(Value::as_str)
18437                    .unwrap_or_default()
18438                    .is_empty()
18439                {
18440                    if let Some(value) = activity.get(field) {
18441                        payload.insert(field.to_string(), value.clone());
18442                    }
18443                }
18444            }
18445            continue;
18446        }
18447
18448        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
18449            continue;
18450        }
18451        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18452        let command_id = event
18453            .payload
18454            .get("workflow_command_id")
18455            .or_else(|| event.raw.get("workflow_command_id"))
18456            .and_then(Value::as_str);
18457        let signal_name = event
18458            .payload
18459            .get("signal_name")
18460            .and_then(Value::as_str)
18461            .unwrap_or_default()
18462            .to_string();
18463        let matched = signals
18464            .iter()
18465            .find(|signal| {
18466                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
18467            })
18468            .or_else(|| {
18469                signals.iter().find(|signal| {
18470                    command_id.is_some()
18471                        && signal.get("command_id").and_then(Value::as_str) == command_id
18472                })
18473            })
18474            .or_else(|| {
18475                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
18476                let signal = signals
18477                    .iter()
18478                    .filter(|signal| {
18479                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
18480                    })
18481                    .nth(*offset);
18482                if signal.is_some() {
18483                    *offset += 1;
18484                }
18485                signal
18486            });
18487        let Some(signal) = matched else {
18488            continue;
18489        };
18490        let signal_codec = signal
18491            .get("payload_codec")
18492            .and_then(Value::as_str)
18493            .unwrap_or(&export_codec);
18494        let Some(payload) = event.payload.as_object_mut() else {
18495            continue;
18496        };
18497        if missing_payload(payload.get("arguments")) {
18498            if let Some(arguments) = signal
18499                .get("arguments")
18500                .filter(|value| !missing_payload(Some(value)))
18501            {
18502                let envelope = match arguments {
18503                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
18504                    other => other.clone(),
18505                };
18506                payload.insert("arguments".to_string(), envelope);
18507            }
18508        }
18509        if payload
18510            .get("payload_codec")
18511            .and_then(Value::as_str)
18512            .unwrap_or_default()
18513            .is_empty()
18514        {
18515            payload.insert("payload_codec".to_string(), json!(signal_codec));
18516        }
18517    }
18518
18519    Ok(())
18520}
18521
18522fn missing_payload(value: Option<&Value>) -> bool {
18523    match value {
18524        None | Some(Value::Null) => true,
18525        Some(Value::String(value)) => value.is_empty(),
18526        Some(_) => false,
18527    }
18528}
18529
18530fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
18531    history_signal_events(
18532        &task.history_events,
18533        task.history_export.as_ref(),
18534        &task.payload_codec,
18535    )
18536}
18537
18538fn history_signal_events(
18539    history_events: &[HistoryEvent],
18540    history_export: Option<&Value>,
18541    payload_codec: &str,
18542) -> Result<Vec<QuerySignal>> {
18543    let export_signals = history_export
18544        .and_then(|export| export.get("signals"))
18545        .and_then(Value::as_array)
18546        .cloned()
18547        .unwrap_or_default();
18548    let export_codec = history_export
18549        .and_then(|export| export.get("payloads"))
18550        .and_then(|payloads| payloads.get("codec"))
18551        .and_then(Value::as_str)
18552        .unwrap_or(payload_codec);
18553    let mut name_offsets: HashMap<String, usize> = HashMap::new();
18554    let mut signals: Vec<QuerySignal> = Vec::new();
18555    let mut signal_indices = HashMap::new();
18556    let mut command_indices = HashMap::new();
18557
18558    for event in history_events {
18559        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
18560            continue;
18561        }
18562
18563        let name = event
18564            .payload
18565            .get("signal_name")
18566            .and_then(Value::as_str)
18567            .unwrap_or_default();
18568        if name.is_empty() {
18569            continue;
18570        }
18571        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18572        let command_id = event
18573            .payload
18574            .get("workflow_command_id")
18575            .or_else(|| event.raw.get("workflow_command_id"))
18576            .and_then(Value::as_str);
18577        let matched_export = export_signals
18578            .iter()
18579            .find(|candidate| {
18580                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
18581            })
18582            .or_else(|| {
18583                export_signals.iter().find(|candidate| {
18584                    command_id.is_some()
18585                        && candidate.get("command_id").and_then(Value::as_str) == command_id
18586                })
18587            })
18588            .or_else(|| {
18589                let offset = name_offsets.entry(name.to_string()).or_default();
18590                let candidate = export_signals
18591                    .iter()
18592                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
18593                    .nth(*offset);
18594                if candidate.is_some() {
18595                    *offset += 1;
18596                }
18597                candidate
18598            });
18599        let codec = event
18600            .payload
18601            .get("payload_codec")
18602            .and_then(Value::as_str)
18603            .or_else(|| {
18604                matched_export
18605                    .and_then(|signal| signal.get("payload_codec"))
18606                    .and_then(Value::as_str)
18607            })
18608            .unwrap_or(export_codec);
18609        let raw_arguments = signal_history_payload(&event.payload)
18610            .filter(|value| !value.is_null())
18611            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
18612        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18613        let workflow_sequence = event
18614            .payload
18615            .get("workflow_sequence")
18616            .and_then(value_as_u64)
18617            .or_else(|| {
18618                matched_export
18619                    .and_then(|signal| signal.get("workflow_sequence"))
18620                    .and_then(value_as_u64)
18621            });
18622
18623        let id = signal_id.or_else(|| {
18624            matched_export
18625                .and_then(|signal| signal.get("id"))
18626                .and_then(Value::as_str)
18627        });
18628        let command_id = command_id.or_else(|| {
18629            matched_export
18630                .and_then(|signal| signal.get("command_id"))
18631                .and_then(Value::as_str)
18632        });
18633        let duplicate = id
18634            .and_then(|id| signal_indices.get(id))
18635            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18636            .copied();
18637        let index = duplicate.unwrap_or(signals.len());
18638        if let Some(index) = duplicate {
18639            let original = &mut signals[index];
18640            let same_arguments = if event.event_type == "SignalApplied" {
18641                if let Some(value) = event.payload.get("value") {
18642                    let expected = match original.avro_arguments.as_slice() {
18643                        [] => AvroValue::Boolean(true),
18644                        [value] => value.clone(),
18645                        values => AvroValue::Array(values.to_vec()),
18646                    };
18647                    let applied = decode_wire_avro_value(value, codec)?;
18648                    applied == expected
18649                        || applied == AvroValue::Array(original.avro_arguments.clone())
18650                } else {
18651                    original.avro_arguments == avro_arguments
18652                }
18653            } else {
18654                original.avro_arguments == avro_arguments
18655            };
18656            if original.name != name
18657                || !same_arguments
18658                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18659            {
18660                return Err(Error::Codec("conflicting committed signal identity".into()));
18661            }
18662            if original.id.is_none() {
18663                original.id = id.map(str::to_string);
18664            }
18665            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18666        } else {
18667            signals.push(QuerySignal {
18668                id: id.map(str::to_string),
18669                name: name.to_string(),
18670                arguments,
18671                avro_arguments,
18672                workflow_sequence,
18673            });
18674        }
18675        if let Some(id) = id {
18676            signal_indices.insert(id.to_string(), index);
18677        }
18678        if let Some(id) = command_id {
18679            command_indices.insert(id.to_string(), index);
18680        }
18681    }
18682
18683    if signals.is_empty() {
18684        for signal in export_signals {
18685            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18686                continue;
18687            }
18688            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18689                continue;
18690            };
18691            let codec = signal
18692                .get("payload_codec")
18693                .and_then(Value::as_str)
18694                .unwrap_or(export_codec);
18695            let (arguments, avro_arguments) =
18696                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18697            signals.push(QuerySignal {
18698                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18699                name: name.to_string(),
18700                arguments,
18701                avro_arguments,
18702                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18703            });
18704        }
18705        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18706    }
18707
18708    Ok(signals)
18709}
18710
18711fn decode_query_signal_arguments(
18712    raw: Option<&Value>,
18713    codec: &str,
18714) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18715    validate_payload_codec(codec)?;
18716    let decoded = match raw.filter(|value| !value.is_null()) {
18717        Some(value) => decode_wire_avro_value(value, codec)?,
18718        None => AvroValue::Array(Vec::new()),
18719    };
18720    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18721        unreachable!("normalize_avro_arguments always returns an array");
18722    };
18723    let arguments = avro_arguments
18724        .iter()
18725        .cloned()
18726        .map(AvroValue::into_json)
18727        .collect::<Result<Vec<_>>>()?;
18728    Ok((arguments, avro_arguments))
18729}
18730
18731fn value_as_u64(value: &Value) -> Option<u64> {
18732    value
18733        .as_u64()
18734        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18735}
18736
18737#[cfg(test)]
18738mod tests {
18739    use super::*;
18740    #[cfg(feature = "telemetry")]
18741    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
18742        tokio::sync::Mutex::const_new(());
18743    mod activity_cancellation_policies;
18744    mod activity_lease_worker;
18745    mod cancellation_scope_admission;
18746    mod cancellation_scope_authoring;
18747    mod cancellation_scope_history;
18748    mod cancellation_scope_opening;
18749    mod cancellation_scope_replay;
18750    mod child_workflow_policies;
18751    mod cooperative_cancellation;
18752    mod local_activity;
18753    mod nexus;
18754    mod runtime_payloads;
18755    mod runtime_uploads;
18756    mod version_marker_contract;
18757    mod worker_capacity;
18758    mod worker_session;
18759    use std::{
18760        fs,
18761        io::{Read, Write},
18762        net::{SocketAddr, TcpListener, TcpStream},
18763        process::Command as ProcessCommand,
18764        sync::atomic::AtomicUsize,
18765        thread,
18766    };
18767
18768    #[derive(Clone, Copy, Debug)]
18769    enum InvalidTaskPayloadCodec {
18770        Missing,
18771        Null,
18772        NonString,
18773    }
18774
18775    impl InvalidTaskPayloadCodec {
18776        fn label(self) -> &'static str {
18777            match self {
18778                Self::Missing => "missing",
18779                Self::Null => "null",
18780                Self::NonString => "non-string",
18781            }
18782        }
18783
18784        fn apply(self, task: &mut Value) {
18785            let task = task.as_object_mut().expect("task fixture object");
18786            match self {
18787                Self::Missing => {
18788                    task.remove("payload_codec");
18789                }
18790                Self::Null => {
18791                    task.insert("payload_codec".to_string(), Value::Null);
18792                }
18793                Self::NonString => {
18794                    task.insert("payload_codec".to_string(), json!(42));
18795                }
18796            }
18797        }
18798    }
18799
18800    fn fixture_envelope(value: Value) -> Value {
18801        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18802    }
18803
18804    fn fixture_blob(value: Value) -> String {
18805        encode_payload(&value, DEFAULT_CODEC)
18806            .expect("encode Avro test fixture")
18807            .blob
18808    }
18809
18810    #[test]
18811    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18812        for base_url in [
18813            "http://127.0.0.1:8080/api",
18814            "http://localhost:8080/api/",
18815            "https://runtime.example.test/namespaces/orders/api",
18816        ] {
18817            let error = Client::builder(base_url)
18818                .build()
18819                .expect_err("SDK-owned /api suffix must be rejected during build");
18820
18821            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18822            assert!(
18823                error.to_string().contains("SDK appends /api automatically"),
18824                "the validation error must explain how to fix the endpoint"
18825            );
18826        }
18827    }
18828
18829    #[test]
18830    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18831        for (base_url, expected) in [
18832            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18833            (
18834                "http://localhost:8080/durable-workflow/",
18835                "http://localhost:8080/durable-workflow",
18836            ),
18837            (
18838                "https://runtime.example.test/namespaces/orders",
18839                "https://runtime.example.test/namespaces/orders",
18840            ),
18841            (
18842                "https://runtime.example.test/gateway/api/namespaces/orders",
18843                "https://runtime.example.test/gateway/api/namespaces/orders",
18844            ),
18845            (
18846                "https://api.example.test/runtime/orders/",
18847                "https://api.example.test/runtime/orders",
18848            ),
18849        ] {
18850            let client = Client::builder(base_url)
18851                .build()
18852                .expect("Server and Cloud runtime base URL must remain valid");
18853
18854            assert_eq!(client.base_url, expected);
18855        }
18856    }
18857
18858    #[test]
18859    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18860        assert_eq!(
18861            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18862            MINIMUM_WORKER_PROTOCOL_VERSION
18863        );
18864        assert_eq!(
18865            workflow_completion_protocol_version(&[json!({
18866                "type": "upsert_search_attributes",
18867                "attributes": {"OrderStatus": "waiting"},
18868            })]),
18869            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18870        );
18871        assert_eq!(
18872            workflow_completion_protocol_version(&[json!({
18873                "type": "upsert_search_attributes",
18874                "attributes": {"OrderStatus": "waiting"},
18875                "attribute_types": {"OrderStatus": "keyword"},
18876            })]),
18877            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18878        );
18879        assert_eq!(
18880            workflow_completion_protocol_version(&[
18881                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18882                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18883            ]),
18884            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18885        );
18886        assert_eq!(
18887            workflow_completion_protocol_version(&[
18888                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18889                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18890            ]),
18891            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18892        );
18893        assert_eq!(
18894            workflow_completion_protocol_version(&[json!({
18895                "type": "open_condition_wait",
18896                "condition_wait_occurrence_id": "rust:condition-wait:0",
18897                "condition_key": "ready",
18898            })]),
18899            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18900        );
18901        assert_eq!(
18902            workflow_completion_protocol_version_with_message_streams(
18903                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18904                true,
18905            ),
18906            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18907        );
18908        assert_eq!(
18909            workflow_completion_protocol_version_with_message_streams(
18910                &[json!({
18911                    "type": "open_condition_wait",
18912                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18913                    "condition_key": "ready",
18914                })],
18915                true,
18916            ),
18917            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18918        );
18919    }
18920
18921    #[test]
18922    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18923        let manifest = portable_worker_affinity_capability_manifest();
18924
18925        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18926            assert_eq!(manifest[capability]["supported"], json!(false));
18927            assert_eq!(
18928                manifest[capability]["minimum_protocol_version"],
18929                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18930            );
18931            assert!(manifest[capability]["reason"]
18932                .as_str()
18933                .is_some_and(|reason| !reason.is_empty()));
18934        }
18935    }
18936
18937    fn typed_fidelity_probe() -> AvroValue {
18938        AvroValue::Map(BTreeMap::from([
18939            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18940            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18941            (
18942                "numeric".to_string(),
18943                AvroValue::Map(BTreeMap::from([
18944                    ("0".to_string(), AvroValue::String("zero".to_string())),
18945                    ("1".to_string(), AvroValue::String("one".to_string())),
18946                ])),
18947            ),
18948            (
18949                "nested".to_string(),
18950                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18951                    "enabled".to_string(),
18952                    AvroValue::Boolean(true),
18953                )]))]),
18954            ),
18955            (
18956                "projection_collisions".to_string(),
18957                AvroValue::Array(projection_collision_probe()),
18958            ),
18959        ]))
18960    }
18961
18962    fn projection_collision_probe() -> Vec<AvroValue> {
18963        vec![
18964            AvroValue::Map(BTreeMap::from([
18965                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18966                (
18967                    "base64".to_string(),
18968                    AvroValue::String("ordinary user text".to_string()),
18969                ),
18970            ])),
18971            AvroValue::Map(BTreeMap::from([
18972                ("$type".to_string(), AvroValue::String("map".to_string())),
18973                (
18974                    "entries".to_string(),
18975                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
18976                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
18977                        (
18978                            "value".to_string(),
18979                            AvroValue::String("user map".to_string()),
18980                        ),
18981                    ]))]),
18982                ),
18983            ])),
18984        ]
18985    }
18986
18987    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18988    struct TypedContract {
18989        nested: TypedNested,
18990        mode: TypedMode,
18991        optional: Option<String>,
18992        absent: Option<String>,
18993        items: Vec<i64>,
18994        labels: BTreeMap<String, String>,
18995        bytes: serde_bytes::ByteBuf,
18996        signed: i64,
18997        finite: f64,
18998    }
18999
19000    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19001    struct TypedNested {
19002        enabled: bool,
19003    }
19004
19005    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19006    enum TypedMode {
19007        Detailed { label: String },
19008    }
19009
19010    fn typed_contract() -> TypedContract {
19011        TypedContract {
19012            nested: TypedNested { enabled: true },
19013            mode: TypedMode::Detailed {
19014                label: "compiler-checked".to_string(),
19015            },
19016            optional: Some("present".to_string()),
19017            absent: None,
19018            items: vec![i64::MIN, 0, i64::MAX],
19019            labels: BTreeMap::from([
19020                ("language".to_string(), "rust".to_string()),
19021                ("wire".to_string(), "avro".to_string()),
19022            ]),
19023            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
19024            signed: -9_223_372_036_854_775_000,
19025            finite: 12.5,
19026        }
19027    }
19028
19029    #[derive(Clone, Debug, Default, PartialEq)]
19030    struct ReplayCounterState {
19031        loaded: Option<String>,
19032        count: i64,
19033        finished: bool,
19034    }
19035
19036    fn replay_counter_worker() -> Worker {
19037        let client = Client::new("http://127.0.0.1:8080").expect("client");
19038        let mut worker = Worker::new(client, "rust-workers");
19039        worker.register_replayed_workflow(
19040            "replay-counter",
19041            ReplayCounterState::default,
19042            |ctx, _input, state| async move {
19043                let loaded = ctx.activity("load-counter", json!([])).await?;
19044                state.update(|current| {
19045                    current.loaded = loaded.as_str().map(str::to_string);
19046                })?;
19047                for _ in 0..2 {
19048                    let signal = ctx.wait_signal("increment").await?;
19049                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
19050                    state.update(|current| current.count += amount)?;
19051                }
19052                state.update(|current| current.finished = true)?;
19053                state.read(|current| Ok(json!(current.count)))?
19054            },
19055        );
19056        worker.register_replayed_query::<ReplayCounterState, _, _>(
19057            "replay-counter",
19058            "current",
19059            |_ctx, state, _args| async move {
19060                Ok(json!({
19061                    "loaded": state.loaded,
19062                    "count": state.count,
19063                    "finished": state.finished,
19064                }))
19065            },
19066        );
19067        worker.register_replayed_query::<ReplayCounterState, _, _>(
19068            "replay-counter",
19069            "detached-mutation",
19070            |_ctx, state, _args| async move {
19071                let mut detached = (*state).clone();
19072                detached.count = 999;
19073                Ok(json!(detached.count))
19074            },
19075        );
19076        worker.register_replayed_query::<ReplayCounterState, _, _>(
19077            "replay-counter",
19078            "failed-mutation",
19079            |_ctx, state, _args| async move {
19080                let mut detached = (*state).clone();
19081                detached.count = 999;
19082                Err(Error::WorkerLoop("query refused".to_string()))
19083            },
19084        );
19085        worker
19086    }
19087
19088    fn replay_counter_query(
19089        query_name: &str,
19090        history_events: Value,
19091        run_status: &str,
19092    ) -> QueryTask {
19093        let arguments = fixture_envelope(json!([]));
19094        serde_json::from_value(json!({
19095            "query_task_id": format!("query-{query_name}"),
19096            "workflow_type": "replay-counter",
19097            "query_name": query_name,
19098            "payload_codec": DEFAULT_CODEC,
19099            "workflow_arguments": arguments.clone(),
19100            "query_arguments": arguments,
19101            "history_events": history_events,
19102            "run_status": run_status,
19103        }))
19104        .expect("query task")
19105    }
19106
19107    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
19108        workflow_context_with_codec(history, DEFAULT_CODEC)
19109    }
19110
19111    fn workflow_context_with_codec(
19112        history: Vec<HistoryEvent>,
19113        payload_codec: &str,
19114    ) -> WorkflowContext {
19115        WorkflowContext {
19116            cancellation_scope_id: "root".into(),
19117            state: Arc::new(Mutex::new(
19118                WorkflowState::new_with_identity(
19119                    history,
19120                    None,
19121                    None,
19122                    "rust-workers".to_string(),
19123                    payload_codec.to_string(),
19124                    None,
19125                )
19126                .expect("valid workflow history"),
19127            )),
19128        }
19129    }
19130
19131    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
19132        HistoryEvent {
19133            event_type: event_type.to_string(),
19134            payload,
19135            raw: HashMap::new(),
19136        }
19137    }
19138
19139    fn parallel_path_entry(
19140        kind: &str,
19141        base: u64,
19142        size: usize,
19143        index: usize,
19144    ) -> ParallelGroupMetadata {
19145        parallel_group_entry(base, size, index, kind)
19146    }
19147
19148    fn parallel_history_event(
19149        event_type: &str,
19150        sequence: u64,
19151        identity_field: &str,
19152        identity: &str,
19153        path: Vec<ParallelGroupMetadata>,
19154        result: Option<Value>,
19155    ) -> HistoryEvent {
19156        let mut payload = serde_json::Map::from_iter([
19157            ("sequence".to_string(), json!(sequence)),
19158            (identity_field.to_string(), json!(identity)),
19159        ]);
19160        let inner = path.last().expect("parallel history path");
19161        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
19162        payload.insert("parallel_group_path".to_string(), json!(path));
19163        if let Some(result) = result {
19164            let field = if event_type == "ChildRunCompleted" {
19165                "result"
19166            } else {
19167                "result"
19168            };
19169            payload.insert(field.to_string(), fixture_envelope(result));
19170            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
19171        }
19172        history_event(event_type, Value::Object(payload))
19173    }
19174
19175    fn nested_parallel_operations() -> Vec<ParallelOperation> {
19176        vec![
19177            ParallelOperation::activity("first", json!([])),
19178            ParallelOperation::group(vec![
19179                ParallelOperation::child_workflow(
19180                    "second",
19181                    ChildWorkflowOptions::new("child-workers"),
19182                    json!([]),
19183                ),
19184                ParallelOperation::activity("third", json!([])),
19185            ]),
19186        ]
19187    }
19188
19189    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
19190        let outer = [
19191            parallel_path_entry("mixed", 1, 3, 0),
19192            parallel_path_entry("mixed", 1, 3, 1),
19193            parallel_path_entry("mixed", 1, 3, 2),
19194        ];
19195        [
19196            vec![outer[0].clone()],
19197            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
19198            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
19199        ]
19200    }
19201
19202    #[test]
19203    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
19204        let ctx = workflow_context(Vec::new());
19205        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19206        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19207
19208        assert!(matches!(
19209            call.as_mut().poll(&mut task_context),
19210            Poll::Pending
19211        ));
19212        let commands = ctx.take_commands().expect("parallel commands");
19213        assert_eq!(
19214            commands
19215                .iter()
19216                .map(|command| command["type"].as_str().unwrap_or_default())
19217                .collect::<Vec<_>>(),
19218            [
19219                "schedule_activity",
19220                "start_child_workflow",
19221                "schedule_activity"
19222            ]
19223        );
19224        let paths = nested_parallel_paths();
19225        for (command, path) in commands.iter().zip(paths) {
19226            assert_eq!(command["parallel_group_path"], json!(path));
19227            assert_eq!(
19228                command["parallel_group_id"],
19229                json!(path.last().expect("inner group").parallel_group_id)
19230            );
19231        }
19232    }
19233
19234    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
19235        let paths = nested_parallel_paths();
19236        let third = parallel_history_event(
19237            "ActivityCompleted",
19238            3,
19239            "activity_type",
19240            "third",
19241            paths[2].clone(),
19242            Some(json!("three")),
19243        );
19244        vec![
19245            parallel_history_event(
19246                "ActivityCompleted",
19247                1,
19248                "activity_type",
19249                "first",
19250                paths[0].clone(),
19251                Some(json!("one")),
19252            ),
19253            parallel_history_event(
19254                "ChildWorkflowScheduled",
19255                2,
19256                "child_workflow_type",
19257                "second",
19258                paths[1].clone(),
19259                None,
19260            ),
19261            parallel_history_event(
19262                "ChildRunCompleted",
19263                2,
19264                "child_workflow_type",
19265                "second",
19266                paths[1].clone(),
19267                Some(json!("two")),
19268            ),
19269            third.clone(),
19270            third,
19271        ]
19272    }
19273
19274    #[test]
19275    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
19276        for _restart_or_completed_replay in 0..2 {
19277            let ctx = workflow_context(completed_nested_parallel_history());
19278            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19279            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19280            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
19281                panic!("completed nested parallel history must replay");
19282            };
19283            assert_eq!(
19284                results,
19285                vec![
19286                    ParallelResult::Activity(json!("one")),
19287                    ParallelResult::Group(vec![
19288                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
19289                            parent: WorkflowIdentity {
19290                                workflow_id: None,
19291                                run_id: None,
19292                            },
19293                            child: WorkflowIdentity {
19294                                workflow_id: None,
19295                                run_id: None,
19296                            },
19297                            child_workflow_type: Some("second".to_string()),
19298                            result: json!("two"),
19299                        }),
19300                        ParallelResult::Activity(json!("three")),
19301                    ]),
19302                ]
19303            );
19304            assert!(ctx.take_commands().expect("commands").is_empty());
19305            ctx.ensure_history_consumed().expect("history consumed");
19306        }
19307    }
19308
19309    #[test]
19310    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
19311        let paths = nested_parallel_paths();
19312        let history = vec![
19313            parallel_history_event(
19314                "ActivityCompleted",
19315                1,
19316                "activity_type",
19317                "first",
19318                paths[0].clone(),
19319                Some(json!("one")),
19320            ),
19321            parallel_history_event(
19322                "ChildWorkflowScheduled",
19323                2,
19324                "child_workflow_type",
19325                "second",
19326                paths[1].clone(),
19327                None,
19328            ),
19329            parallel_history_event(
19330                "ChildRunFailed",
19331                2,
19332                "child_workflow_type",
19333                "second",
19334                paths[1].clone(),
19335                None,
19336            ),
19337            parallel_history_event(
19338                "ActivityCompleted",
19339                3,
19340                "activity_type",
19341                "third",
19342                paths[2].clone(),
19343                Some(json!("late")),
19344            ),
19345        ];
19346        let ctx = workflow_context(history);
19347        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19348        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19349        let outcome = call.as_mut().poll(&mut task_context);
19350        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
19351            panic!("one failed child must return a typed partial failure: {outcome:?}");
19352        };
19353        assert_eq!(failure.member_path, [1, 0]);
19354        assert_eq!(failure.group_id, "parallel-calls:1:3");
19355        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
19356        assert_eq!(
19357            failure
19358                .completed
19359                .iter()
19360                .map(|completion| completion.member_path.clone())
19361                .collect::<Vec<_>>(),
19362            [vec![0], vec![1, 1]]
19363        );
19364    }
19365
19366    #[test]
19367    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
19368        let paths = nested_parallel_paths();
19369        let history = vec![
19370            parallel_history_event(
19371                "ActivityScheduled",
19372                1,
19373                "activity_type",
19374                "first",
19375                paths[0].clone(),
19376                None,
19377            ),
19378            parallel_history_event(
19379                "ChildWorkflowScheduled",
19380                2,
19381                "child_workflow_type",
19382                "second",
19383                paths[1].clone(),
19384                None,
19385            ),
19386            parallel_history_event(
19387                "ActivityScheduled",
19388                3,
19389                "activity_type",
19390                "third",
19391                paths[2].clone(),
19392                None,
19393            ),
19394        ];
19395        for _restart in 0..2 {
19396            let ctx = workflow_context(history.clone());
19397            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19398            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19399            let outcome = call.as_mut().poll(&mut task_context);
19400            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
19401            assert!(ctx.take_commands().expect("commands").is_empty());
19402        }
19403    }
19404
19405    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
19406        vec![selection_group_entry(
19407            1,
19408            2,
19409            index,
19410            "activity",
19411            &SelectionMemberMetadata {
19412                key: SelectionKey::Name(key.to_string()),
19413                index,
19414                base_sequence: index as u64 + 1,
19415                size: 1,
19416                kind: "activity".to_string(),
19417            },
19418        )]
19419    }
19420
19421    fn selection_activity_event(
19422        event_type: &str,
19423        index: usize,
19424        key: &str,
19425        result: Option<Value>,
19426    ) -> HistoryEvent {
19427        let sequence = index as u64 + 1;
19428        let mut event = parallel_history_event(
19429            event_type,
19430            sequence,
19431            "activity_type",
19432            &format!("{key}-activity"),
19433            selection_path(index, key),
19434            result,
19435        );
19436        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
19437        event.raw.insert(
19438            "id".to_string(),
19439            json!(if event_type == "ActivityCompleted" {
19440                format!("event-{key}")
19441            } else {
19442                format!("{event_type}-{key}")
19443            }),
19444        );
19445        event
19446    }
19447
19448    fn selection_winner_marker() -> HistoryEvent {
19449        history_event(
19450            "SelectionResolved",
19451            json!({
19452                "selection_group_id": "select-calls:1:2",
19453                "selection_group_base_sequence": 1,
19454                "selection_group_size": 2,
19455                "member_key": "fast",
19456                "member_index": 1,
19457                "member_base_sequence": 2,
19458                "member_size": 1,
19459                "operation_kind": "activity",
19460                "operation_identity": "activity-fast",
19461                "outcome": "completed",
19462                "resolution_event_id": "event-fast",
19463                "resolution_event_type": "ActivityCompleted",
19464            }),
19465        )
19466    }
19467
19468    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
19469        ctx.select_keyed(vec![
19470            (
19471                "slow",
19472                ParallelOperation::activity_with_options(
19473                    "slow-activity",
19474                    ActivityOptions::new().task_queue("default"),
19475                    json!([]),
19476                ),
19477            ),
19478            (
19479                "fast",
19480                ParallelOperation::activity_with_options(
19481                    "fast-activity",
19482                    ActivityOptions::new().task_queue("default"),
19483                    json!([]),
19484                ),
19485            ),
19486        ])
19487    }
19488
19489    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
19490        let ctx = workflow_context(history);
19491        let mut call = Box::pin(keyed_activity_selection(&ctx));
19492        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19493        let selected = match call.as_mut().poll(&mut task_context) {
19494            Poll::Ready(Ok(selected)) => selected,
19495            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
19496            Poll::Pending => panic!("persisted selection winner must replay without pending"),
19497        };
19498        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
19499        assert_eq!(
19500            selected.value,
19501            Some(ParallelResult::Activity(json!("winner-value")))
19502        );
19503        let slow = selected
19504            .handle(&SelectionKey::Name("slow".to_string()))
19505            .expect("slow handle")
19506            .clone();
19507        let mut await_slow = Box::pin(slow.await_result());
19508        assert!(matches!(
19509            await_slow.as_mut().poll(&mut task_context),
19510            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
19511        ));
19512        assert!(ctx.take_commands().expect("commands").is_empty());
19513    }
19514
19515    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
19516
19517    fn canonical_selection_history() -> Vec<HistoryEvent> {
19518        const FIXTURE: &[u8] =
19519            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
19520        assert_eq!(
19521            format!("{:x}", Sha256::digest(FIXTURE)),
19522            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19523        );
19524        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
19525
19526        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
19527    }
19528
19529    #[test]
19530    fn selection_fresh_process_entrypoint() {
19531        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
19532            return;
19533        };
19534        let persisted = fs::read(path).expect("persisted selection history");
19535        assert_eq!(
19536            format!("{:x}", Sha256::digest(&persisted)),
19537            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19538        );
19539        let fixture: Value =
19540            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
19541        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
19542            .expect("valid persisted selection history");
19543
19544        assert_persisted_selection_replay(history);
19545    }
19546
19547    #[test]
19548    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
19549        let ctx = workflow_context(Vec::new());
19550        let mut call = Box::pin(keyed_activity_selection(&ctx));
19551        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19552
19553        assert!(matches!(
19554            call.as_mut().poll(&mut task_context),
19555            Poll::Pending
19556        ));
19557        let commands = ctx.take_commands().expect("selection commands");
19558        assert_eq!(commands.len(), 2);
19559        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
19560        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
19561        assert!(commands.iter().all(|command| {
19562            command["parallel_group_id"] == json!("select-calls:1:2")
19563                && command["parallel_group_mode"] == json!("select")
19564        }));
19565    }
19566
19567    #[test]
19568    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
19569        let ctx = workflow_context(Vec::new());
19570        let mut invalid = Box::pin(ctx.select_keyed(vec![(
19571            "",
19572            ParallelOperation::activity("invalid", json!([])),
19573        )]));
19574        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19575        assert!(matches!(
19576            invalid.as_mut().poll(&mut task_context),
19577            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
19578                reason: "selection_key_invalid",
19579                ..
19580            })))
19581        ));
19582
19583        for invalid_key in [json!(""), json!(-1)] {
19584            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
19585            event.payload["selection_member_key"] = invalid_key.clone();
19586            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
19587            assert!(matches!(
19588                WorkflowState::new_with_identity(
19589                    vec![event],
19590                    None,
19591                    None,
19592                    "rust-workers".to_string(),
19593                    DEFAULT_CODEC.to_string(),
19594                    None,
19595                ),
19596                Err(Error::NonDeterministicReplay(_))
19597            ));
19598        }
19599    }
19600
19601    #[test]
19602    fn selection_preserves_valid_named_and_numeric_keys() {
19603        let ctx = workflow_context(Vec::new());
19604        let mut selection = Box::pin(ctx.select_keyed(vec![
19605            (
19606                SelectionKey::Index(0),
19607                ParallelOperation::activity("numeric", json!([])),
19608            ),
19609            (
19610                SelectionKey::Name("named".to_string()),
19611                ParallelOperation::timer(Duration::from_secs(1)),
19612            ),
19613        ]));
19614        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19615
19616        assert!(matches!(
19617            selection.as_mut().poll(&mut task_context),
19618            Poll::Pending
19619        ));
19620        let commands = ctx.take_commands().expect("selection commands");
19621        assert_eq!(commands[0]["selection_member_key"], json!(0));
19622        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19623    }
19624
19625    #[test]
19626    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19627        let history = canonical_selection_history();
19628        assert_persisted_selection_replay(history.clone());
19629
19630        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19631            .join("tests/fixtures/durable_selection_runtime_history.json");
19632        let output =
19633            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19634                .args([
19635                    "--exact",
19636                    "tests::selection_fresh_process_entrypoint",
19637                    "--nocapture",
19638                ])
19639                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19640                .output()
19641                .expect("run fresh selection replay process");
19642
19643        assert!(
19644            output.status.success(),
19645            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19646            String::from_utf8_lossy(&output.stdout),
19647            String::from_utf8_lossy(&output.stderr),
19648        );
19649    }
19650
19651    #[test]
19652    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19653        let mut history = canonical_selection_history();
19654        history.retain(|event| event.event_type != "SelectionResolved");
19655        let ctx = workflow_context(history);
19656        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19657        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19658
19659        assert!(matches!(
19660            selection.as_mut().poll(&mut task_context),
19661            Poll::Pending
19662        ));
19663        assert!(ctx.take_commands().expect("commands").is_empty());
19664        assert!(
19665            ctx.matched_recorded_pending()
19666                .expect("selection pending state"),
19667            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19668        );
19669    }
19670
19671    #[test]
19672    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19673        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19674            ("ConditionWaitSatisfied", true, None),
19675            ("ConditionWaitTimedOut", false, Some(0)),
19676        ] {
19677            let member = SelectionMemberMetadata {
19678                key: SelectionKey::Name("condition".to_string()),
19679                index: 0,
19680                base_sequence: 1,
19681                size: 1,
19682                kind: "condition".to_string(),
19683            };
19684            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19685            let mut payload = json!({
19686                "sequence": 1,
19687                "condition_wait_id": "condition-1",
19688                "condition_wait_occurrence_id": "rust:condition-wait:0",
19689                "condition_key": "ready",
19690                "condition_definition_fingerprint": "sha256:ready-v1",
19691                "parallel_group_path": path,
19692            });
19693            payload
19694                .as_object_mut()
19695                .expect("condition history payload")
19696                .extend(
19697                    serde_json::to_value(&path[0])
19698                        .expect("condition selection metadata")
19699                        .as_object()
19700                        .expect("condition selection metadata object")
19701                        .clone(),
19702                );
19703            if let Some(timeout_seconds) = timeout_seconds {
19704                payload["timeout_seconds"] = json!(timeout_seconds);
19705            }
19706            let history = vec![
19707                history_event("ConditionWaitOpened", payload.clone()),
19708                history_event(terminal_event, payload),
19709            ];
19710            let ctx = workflow_context(history);
19711            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19712            if timeout_seconds.is_some() {
19713                options = options.timeout(Duration::ZERO);
19714            }
19715            let mut selection = Box::pin(ctx.select_keyed(vec![(
19716                "condition",
19717                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19718            )]));
19719            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19720
19721            assert!(matches!(
19722                selection.as_mut().poll(&mut task_context),
19723                Poll::Pending
19724            ));
19725            assert!(ctx.take_commands().expect("commands").is_empty());
19726            assert!(
19727                ctx.matched_recorded_pending()
19728                    .expect("condition selection pending state"),
19729                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19730            );
19731        }
19732    }
19733
19734    #[test]
19735    fn selection_immediate_condition_members_open_a_durable_wait() {
19736        for predicate_satisfied in [true, false] {
19737            let ctx = workflow_context(Vec::new());
19738            let mut selection = Box::pin(ctx.select_keyed(vec![(
19739                "condition",
19740                ParallelOperation::condition(
19741                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19742                    move || Ok(predicate_satisfied),
19743                ),
19744            )]));
19745            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19746
19747            assert!(matches!(
19748                selection.as_mut().poll(&mut task_context),
19749                Poll::Pending
19750            ));
19751            let commands = ctx.take_commands().expect("condition selection command");
19752            assert_eq!(commands.len(), 1);
19753            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19754            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19755            assert_eq!(
19756                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19757                json!("select")
19758            );
19759        }
19760    }
19761
19762    #[test]
19763    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19764        let history = vec![
19765            selection_activity_event("ActivityScheduled", 0, "slow", None),
19766            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19767            selection_winner_marker(),
19768        ];
19769        let ctx = workflow_context(history.clone());
19770        let mut call = Box::pin(keyed_activity_selection(&ctx));
19771        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19772        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19773            panic!("winner must replay");
19774        };
19775        let slow = selected
19776            .handle(&SelectionKey::Name("slow".to_string()))
19777            .expect("slow handle")
19778            .clone();
19779        let mut cancel = Box::pin(slow.cancel());
19780        assert!(matches!(
19781            cancel.as_mut().poll(&mut task_context),
19782            Poll::Ready(Ok(()))
19783        ));
19784        assert!(matches!(
19785            cancel.as_mut().poll(&mut task_context),
19786            Poll::Ready(Ok(()))
19787        ));
19788        let mut outcome = Box::pin(slow.await_result());
19789        assert!(matches!(
19790            outcome.as_mut().poll(&mut task_context),
19791            Poll::Pending
19792        ));
19793        let commands = ctx.take_commands().expect("cancel command");
19794        assert_eq!(commands.len(), 1);
19795        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19796        assert_eq!(commands[0]["member_key"], json!("slow"));
19797
19798        let mut cancelled_history = history;
19799        cancelled_history.push(history_event(
19800            "SelectionOperationCancelled",
19801            json!({
19802                "selection_group_id": "select-calls:1:2",
19803                "member_key": "slow",
19804                "member_index": 0,
19805                "member_base_sequence": 1,
19806                "member_size": 1,
19807                "operation_kind": "activity",
19808                "operation_identity": "activity-slow",
19809                "cancelled_at": "2026-08-27T00:00:00Z",
19810            }),
19811        ));
19812        let replayed = workflow_context(cancelled_history);
19813        let mut call = Box::pin(keyed_activity_selection(&replayed));
19814        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19815            panic!("winner must replay after cancellation");
19816        };
19817        let slow = selected
19818            .handle(&SelectionKey::Name("slow".to_string()))
19819            .expect("slow handle")
19820            .clone();
19821        let mut cancel = Box::pin(slow.cancel());
19822        assert!(matches!(
19823            cancel.as_mut().poll(&mut task_context),
19824            Poll::Ready(Ok(()))
19825        ));
19826        assert!(replayed.take_commands().expect("commands").is_empty());
19827    }
19828
19829    #[test]
19830    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19831        let base_history = vec![
19832            selection_activity_event("ActivityScheduled", 0, "slow", None),
19833            selection_activity_event("ActivityScheduled", 1, "fast", None),
19834            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19835            selection_winner_marker(),
19836        ];
19837        for (field, corrupt) in [
19838            ("member_key", json!("fast")),
19839            ("member_index", json!(1)),
19840            ("member_base_sequence", json!(3)),
19841            ("member_size", json!(2)),
19842            ("operation_kind", json!("timer")),
19843            ("operation_identity", json!("forged")),
19844        ] {
19845            let mut cancellation = json!({
19846                "selection_group_id": "select-calls:1:2",
19847                "member_key": "slow",
19848                "member_index": 0,
19849                "member_base_sequence": 1,
19850                "member_size": 1,
19851                "operation_kind": "activity",
19852                "operation_identity": "activity-slow",
19853            });
19854            cancellation[field] = corrupt;
19855            let mut history = base_history.clone();
19856            history.push(history_event("SelectionOperationCancelled", cancellation));
19857            let ctx = workflow_context(history);
19858            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19859            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19860
19861            assert!(matches!(
19862                selection.as_mut().poll(&mut task_context),
19863                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19864            ));
19865        }
19866    }
19867
19868    #[test]
19869    fn selection_child_identity_prefers_the_durable_run_id() {
19870        let ctx = workflow_context(vec![history_event(
19871            "ChildWorkflowScheduled",
19872            json!({
19873                "sequence": 1,
19874                "child_workflow_type": "child",
19875                "child_workflow_instance_id": "child-instance",
19876                "child_workflow_run_id": "child-run",
19877            }),
19878        )]);
19879        let state = ctx.state.lock().expect("workflow state");
19880
19881        assert_eq!(
19882            selection_operation_identity(&state, "child", 1, 1),
19883            "child-run"
19884        );
19885    }
19886
19887    #[test]
19888    fn selection_activity_identity_requires_canonical_execution_id() {
19889        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19890        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19891        let mut fast_completed =
19892            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19893        for event in [&mut fast_open, &mut fast_completed] {
19894            event
19895                .payload
19896                .as_object_mut()
19897                .expect("activity payload")
19898                .remove("activity_execution_id");
19899            event.payload["activity_id"] = json!("forged-activity-id");
19900        }
19901        let mut marker = selection_winner_marker();
19902        marker.payload["operation_identity"] = json!("forged-activity-id");
19903        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19904        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19905        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19906
19907        assert!(matches!(
19908            selection.as_mut().poll(&mut task_context),
19909            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19910        ));
19911    }
19912
19913    #[test]
19914    fn selection_completion_before_cancellation_remains_awaitable() {
19915        let history = vec![
19916            selection_activity_event("ActivityScheduled", 0, "slow", None),
19917            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19918            selection_winner_marker(),
19919            selection_activity_event(
19920                "ActivityCompleted",
19921                0,
19922                "slow",
19923                Some(json!("completed-first")),
19924            ),
19925        ];
19926        let ctx = workflow_context(history);
19927        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19928        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19929        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19930            panic!("winner must replay");
19931        };
19932        let slow = selected
19933            .handle(&SelectionKey::Name("slow".to_string()))
19934            .expect("slow handle")
19935            .clone();
19936        let mut cancel = Box::pin(slow.cancel());
19937        assert!(matches!(
19938            cancel.as_mut().poll(&mut task_context),
19939            Poll::Ready(Ok(()))
19940        ));
19941        let mut await_slow = Box::pin(slow.await_result());
19942        assert!(matches!(
19943            await_slow.as_mut().poll(&mut task_context),
19944            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19945        ));
19946        let commands = ctx.take_commands().expect("commands");
19947        assert!(commands.is_empty());
19948    }
19949
19950    #[test]
19951    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19952        let nested_member = SelectionMemberMetadata {
19953            key: SelectionKey::Name("nested".to_string()),
19954            index: 0,
19955            base_sequence: 1,
19956            size: 2,
19957            kind: "group".to_string(),
19958        };
19959        let deadline_member = SelectionMemberMetadata {
19960            key: SelectionKey::Name("deadline".to_string()),
19961            index: 1,
19962            base_sequence: 3,
19963            size: 1,
19964            kind: "timer".to_string(),
19965        };
19966        let nested_paths = [
19967            vec![
19968                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19969                parallel_group_entry(1, 2, 0, "activity"),
19970            ],
19971            vec![
19972                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19973                parallel_group_entry(1, 2, 1, "activity"),
19974            ],
19975        ];
19976        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
19977        let mut timer_fired = parallel_history_event(
19978            "TimerFired",
19979            3,
19980            "timer_id",
19981            "timer-3",
19982            deadline_path.clone(),
19983            None,
19984        );
19985        timer_fired.payload["delay_seconds"] = json!(0);
19986        timer_fired
19987            .raw
19988            .insert("id".to_string(), json!("timer-fired"));
19989        let mut timer_scheduled = parallel_history_event(
19990            "TimerScheduled",
19991            3,
19992            "timer_id",
19993            "timer-3",
19994            deadline_path,
19995            None,
19996        );
19997        timer_scheduled.payload["delay_seconds"] = json!(0);
19998        let history = vec![
19999            parallel_history_event(
20000                "ActivityScheduled",
20001                1,
20002                "activity_type",
20003                "nested-first",
20004                nested_paths[0].clone(),
20005                None,
20006            ),
20007            parallel_history_event(
20008                "ActivityScheduled",
20009                2,
20010                "activity_type",
20011                "nested-second",
20012                nested_paths[1].clone(),
20013                None,
20014            ),
20015            timer_scheduled,
20016            timer_fired,
20017            history_event(
20018                "SelectionResolved",
20019                json!({
20020                    "selection_group_id": "select-calls:1:3",
20021                    "selection_group_base_sequence": 1,
20022                    "selection_group_size": 3,
20023                    "member_key": "deadline",
20024                    "member_index": 1,
20025                    "member_base_sequence": 3,
20026                    "member_size": 1,
20027                    "operation_kind": "timer",
20028                    "operation_identity": "timer-3",
20029                    "outcome": "completed",
20030                    "resolution_event_id": "timer-fired",
20031                    "resolution_event_type": "TimerFired",
20032                }),
20033            ),
20034            parallel_history_event(
20035                "ActivityFailed",
20036                2,
20037                "activity_type",
20038                "nested-second",
20039                nested_paths[1].clone(),
20040                None,
20041            ),
20042        ];
20043        let ctx = workflow_context(history);
20044        let mut selection = Box::pin(ctx.select_keyed(vec![
20045            (
20046                "nested",
20047                ParallelOperation::group(vec![
20048                    ParallelOperation::activity("nested-first", json!([])),
20049                    ParallelOperation::activity("nested-second", json!([])),
20050                ]),
20051            ),
20052            ("deadline", ParallelOperation::timer(Duration::ZERO)),
20053        ]));
20054        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20055        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20056            panic!("deadline winner must replay");
20057        };
20058        let nested = selected
20059            .handle(&SelectionKey::Name("nested".to_string()))
20060            .expect("nested handle")
20061            .clone();
20062        let mut cancel = Box::pin(nested.cancel());
20063        assert!(matches!(
20064            cancel.as_mut().poll(&mut task_context),
20065            Poll::Ready(Ok(()))
20066        ));
20067        let mut await_nested = Box::pin(nested.await_result());
20068
20069        assert!(matches!(
20070            await_nested.as_mut().poll(&mut task_context),
20071            Poll::Ready(Err(Error::ActivityFailed(_)))
20072        ));
20073        assert!(ctx.take_commands().expect("commands").is_empty());
20074    }
20075
20076    #[test]
20077    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
20078        let ctx = workflow_context(Vec::new());
20079        let mut call = Box::pin(ctx.select(vec![
20080            ParallelOperation::child_workflow(
20081                "child",
20082                ChildWorkflowOptions::new("children"),
20083                json!([]),
20084            ),
20085            ParallelOperation::timer(Duration::from_secs(30)),
20086            ParallelOperation::signal("approval"),
20087            ParallelOperation::condition(
20088                ConditionWaitOptions::new("ready", "sha256:ready"),
20089                || Ok(false),
20090            ),
20091            ParallelOperation::group(vec![
20092                ParallelOperation::activity("nested-one", json!([])),
20093                ParallelOperation::activity("nested-two", json!([])),
20094            ]),
20095        ]));
20096        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20097        assert!(matches!(
20098            call.as_mut().poll(&mut task_context),
20099            Poll::Pending
20100        ));
20101        let commands = ctx.take_commands().expect("selection commands");
20102        assert_eq!(
20103            commands
20104                .iter()
20105                .map(|command| command["type"].as_str().unwrap_or_default())
20106                .collect::<Vec<_>>(),
20107            [
20108                "start_child_workflow",
20109                "start_timer",
20110                "open_signal_wait",
20111                "open_condition_wait",
20112                "schedule_activity",
20113                "schedule_activity",
20114            ]
20115        );
20116        assert!(commands.iter().all(|command| {
20117            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
20118        }));
20119        assert_eq!(
20120            commands[4]["parallel_group_path"].as_array().map(Vec::len),
20121            Some(2)
20122        );
20123        assert_eq!(
20124            commands[4]["parallel_group_path"][0]["selection_member_kind"],
20125            json!("group")
20126        );
20127        assert_eq!(
20128            commands[5]["parallel_group_path"][0]["selection_member_kind"],
20129            json!("group")
20130        );
20131
20132        let one_leaf_ctx = workflow_context(Vec::new());
20133        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
20134            ParallelOperation::activity("nested-only", json!([])),
20135        ])]));
20136        assert!(matches!(
20137            one_leaf.as_mut().poll(&mut task_context),
20138            Poll::Pending
20139        ));
20140        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
20141        assert_eq!(one_leaf_commands.len(), 1);
20142        assert_eq!(
20143            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
20144            json!("group")
20145        );
20146        assert_eq!(
20147            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
20148            json!(1)
20149        );
20150    }
20151
20152    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
20153        let mut saga = ctx.saga();
20154        let outcome = async {
20155            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20156            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20157            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
20158            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
20159            ctx.activity("trip.charge", json!([])).await?;
20160            Ok(json!({"status": "booked"}))
20161        }
20162        .await;
20163        saga.finish(outcome).await
20164    }
20165
20166    fn saga_activity(
20167        event_type: &str,
20168        sequence: u64,
20169        activity_type: &str,
20170        result: Option<Value>,
20171    ) -> HistoryEvent {
20172        let mut payload = json!({
20173            "sequence": sequence,
20174            "activity_type": activity_type,
20175            "message": format!("{activity_type} failed"),
20176            "exception_type": "PlannedFailure",
20177            "non_retryable": true,
20178        });
20179        if let Some(result) = result {
20180            payload["result"] = fixture_envelope(result);
20181        }
20182        history_event(event_type, payload)
20183    }
20184
20185    #[test]
20186    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
20187        let completed_hotel_compensation = saga_activity(
20188            "ActivityCompleted",
20189            4,
20190            "trip.cancel-hotel",
20191            Some(Value::Null),
20192        );
20193        let history = vec![
20194            saga_activity(
20195                "ActivityCompleted",
20196                1,
20197                "trip.reserve-flight",
20198                Some(json!("flight-1")),
20199            ),
20200            saga_activity(
20201                "ActivityCompleted",
20202                2,
20203                "trip.reserve-hotel",
20204                Some(json!("hotel-1")),
20205            ),
20206            saga_activity("ActivityFailed", 3, "trip.charge", None),
20207            completed_hotel_compensation.clone(),
20208            completed_hotel_compensation,
20209        ];
20210
20211        for _restart in 0..2 {
20212            let ctx = workflow_context(history.clone());
20213            let mut future = Box::pin(trip_saga(ctx.clone()));
20214            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20215            assert!(matches!(
20216                future.as_mut().poll(&mut task_context),
20217                Poll::Pending
20218            ));
20219            let commands = ctx.take_commands().expect("compensation command");
20220            assert_eq!(commands.len(), 1);
20221            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20222        }
20223    }
20224
20225    #[test]
20226    fn saga_compensation_failure_preserves_both_typed_failures() {
20227        let history = vec![
20228            saga_activity(
20229                "ActivityCompleted",
20230                1,
20231                "trip.reserve-flight",
20232                Some(json!("flight-1")),
20233            ),
20234            saga_activity(
20235                "ActivityCompleted",
20236                2,
20237                "trip.reserve-hotel",
20238                Some(json!("hotel-1")),
20239            ),
20240            saga_activity("ActivityFailed", 3, "trip.charge", None),
20241            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
20242        ];
20243        let ctx = workflow_context(history);
20244        let mut future = Box::pin(trip_saga(ctx));
20245        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20246        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
20247            future.as_mut().poll(&mut task_context)
20248        else {
20249            panic!("compensation failure must remain structured");
20250        };
20251        assert!(matches!(
20252            *failure.initiating_failure,
20253            Error::ActivityFailed(_)
20254        ));
20255        assert!(matches!(
20256            *failure.compensation_failure,
20257            Error::ActivityFailed(_)
20258        ));
20259        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
20260        assert_eq!(failure.compensation_registration_order, 2);
20261    }
20262
20263    #[test]
20264    fn saga_compensates_cooperative_cancellation() {
20265        let ctx = workflow_context(vec![saga_activity(
20266            "ActivityCompleted",
20267            1,
20268            "trip.reserve-flight",
20269            Some(json!("flight-1")),
20270        )]);
20271        ctx.state.lock().expect("state").cancel_requested = true;
20272        let run = {
20273            let ctx = ctx.clone();
20274            async move {
20275                let mut saga = ctx.saga();
20276                let outcome = async {
20277                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20278                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20279                    ctx.throw_if_cancellation_requested()?;
20280                    Ok(json!("unexpected"))
20281                }
20282                .await;
20283                saga.finish(outcome).await
20284            }
20285        };
20286        let mut future = Box::pin(run);
20287        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20288        assert!(matches!(
20289            future.as_mut().poll(&mut task_context),
20290            Poll::Pending
20291        ));
20292        let commands = ctx.take_commands().expect("cancellation compensation");
20293        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20294    }
20295
20296    #[test]
20297    fn optional_task_observability_fields_round_trip_without_interpretation() {
20298        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
20299        let dispatch = json!({"task_id": "other-task"});
20300        let links = json!({"links": []});
20301        let mut value = json!({
20302            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
20303            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
20304        });
20305        let workflow: WorkflowTask =
20306            serde_json::from_value(value.clone()).expect("legacy workflow task");
20307        let activity: ActivityTask =
20308            serde_json::from_value(value.clone()).expect("legacy activity task");
20309        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
20310        assert!(workflow.observability_context.is_none());
20311        assert!(activity.observability_context.is_none());
20312        assert!(query.observability_context.is_none());
20313        assert!(activity.workflow_id.is_none());
20314        assert!(activity.run_id.is_none());
20315        assert!(activity.activity_execution_id.is_none());
20316
20317        value["observability_context"] = context.clone();
20318        value["dispatch_observability_context"] = dispatch.clone();
20319        value["observability_links"] = links.clone();
20320        value["workflow_id"] = json!("workflow-id");
20321        value["run_id"] = json!("run-id");
20322        value["activity_execution_id"] = json!("activity-id");
20323        let workflow: WorkflowTask =
20324            serde_json::from_value(value.clone()).expect("workflow metadata");
20325        let activity: ActivityTask =
20326            serde_json::from_value(value.clone()).expect("activity metadata");
20327        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
20328        for fields in [
20329            (
20330                workflow.observability_context,
20331                workflow.dispatch_observability_context,
20332                workflow.observability_links,
20333            ),
20334            (
20335                activity.observability_context,
20336                activity.dispatch_observability_context,
20337                activity.observability_links,
20338            ),
20339            (
20340                query.observability_context,
20341                query.dispatch_observability_context,
20342                query.observability_links,
20343            ),
20344        ] {
20345            assert_eq!(
20346                fields,
20347                (
20348                    Some(context.clone()),
20349                    Some(dispatch.clone()),
20350                    Some(links.clone())
20351                )
20352            );
20353        }
20354        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
20355        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
20356        assert_eq!(
20357            activity.activity_execution_id.as_deref(),
20358            Some("activity-id")
20359        );
20360    }
20361
20362    fn workflow_task(
20363        workflow_type: &str,
20364        history_events: Vec<HistoryEvent>,
20365        payload_codec: &str,
20366    ) -> WorkflowTask {
20367        WorkflowTask {
20368            task_id: format!("wft-{workflow_type}"),
20369            observability_context: None,
20370            dispatch_observability_context: None,
20371            observability_links: None,
20372            workflow_command_id: None,
20373            workflow_id: Some(format!("wf-{workflow_type}")),
20374            run_id: Some(format!("run-{workflow_type}")),
20375            workflow_type: workflow_type.to_string(),
20376            cancel_requested: false,
20377            payload_codec: payload_codec.to_string(),
20378            arguments: Some(
20379                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
20380            ),
20381            total_history_events: Some(history_events.len() as u64),
20382            history_size_bytes: None,
20383            continue_as_new_recommended: None,
20384            history_budget_pressure: None,
20385            history_events,
20386            next_history_page_token: None,
20387            workflow_task_attempt: 1,
20388            workflow_signal_id: None,
20389            signal_name: None,
20390            signal_arguments: None,
20391            workflow_update_id: None,
20392            update_name: None,
20393            lease_owner: Some("rust-worker".to_string()),
20394        }
20395    }
20396
20397    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20398    struct SideEffectProbe {
20399        request_id: String,
20400        attempt: u32,
20401    }
20402
20403    #[test]
20404    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
20405        let calls = AtomicUsize::new(0);
20406        let ctx = workflow_context(Vec::new());
20407        let value = ctx
20408            .side_effect(|| {
20409                calls.fetch_add(1, Ordering::SeqCst);
20410                SideEffectProbe {
20411                    request_id: "request-42".to_string(),
20412                    attempt: 3,
20413                }
20414            })
20415            .expect("first side effect");
20416        assert_eq!(value.attempt, 3);
20417        assert_eq!(calls.load(Ordering::SeqCst), 1);
20418        let commands = ctx.take_commands().expect("commands");
20419        assert_eq!(commands.len(), 1);
20420        assert_eq!(commands[0]["type"], "record_side_effect");
20421        assert_eq!(
20422            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20423            serde_json::to_value(&value).expect("value")
20424        );
20425
20426        let replay = workflow_context(vec![history_event(
20427            "SideEffectRecorded",
20428            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20429        )]);
20430        let replayed: SideEffectProbe = replay
20431            .side_effect(|| {
20432                calls.fetch_add(1, Ordering::SeqCst);
20433                panic!("committed side-effect callbacks must not run during replay")
20434            })
20435            .expect("replayed side effect");
20436        assert_eq!(replayed, value);
20437        assert_eq!(calls.load(Ordering::SeqCst), 1);
20438        assert!(replay.take_commands().expect("commands").is_empty());
20439        replay.ensure_history_consumed().expect("history consumed");
20440    }
20441
20442    #[test]
20443    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
20444        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20445        let value = ctx
20446            .side_effect(|| SideEffectProbe {
20447                request_id: "avro-request".to_string(),
20448                attempt: 1,
20449            })
20450            .expect("Avro side effect");
20451        let uuid = ctx.uuid_v4().expect("deterministic UUID");
20452        let commands = ctx.take_commands().expect("commands");
20453        assert_eq!(commands.len(), 2);
20454        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
20455        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
20456        assert_eq!(
20457            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20458            serde_json::to_value(&value).expect("value")
20459        );
20460
20461        let replay = workflow_context_with_codec(
20462            vec![
20463                history_event(
20464                    "SideEffectRecorded",
20465                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20466                ),
20467                history_event(
20468                    "SideEffectRecorded",
20469                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
20470                ),
20471            ],
20472            DEFAULT_CODEC,
20473        );
20474        let replayed: SideEffectProbe = replay
20475            .side_effect(|| panic!("Avro callback must not run"))
20476            .expect("replayed Avro value");
20477        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
20478        assert_eq!(replayed, value);
20479        assert_eq!(replayed_uuid, uuid);
20480        assert!(replay.take_commands().expect("commands").is_empty());
20481    }
20482
20483    #[test]
20484    fn typed_side_effect_replay_preserves_bytes_and_maps() {
20485        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20486        let value = ctx
20487            .side_effect_avro_value(typed_fidelity_probe)
20488            .expect("typed side effect");
20489        let commands = ctx.take_commands().expect("side-effect command");
20490        assert_eq!(
20491            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20492                .expect("recorded side effect"),
20493            value
20494        );
20495
20496        let replay = workflow_context_with_codec(
20497            vec![history_event(
20498                "SideEffectRecorded",
20499                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20500            )],
20501            DEFAULT_CODEC,
20502        );
20503        assert_eq!(
20504            replay
20505                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
20506                .expect("replayed typed side effect"),
20507            value
20508        );
20509    }
20510
20511    #[test]
20512    fn ordered_side_effects_share_the_durable_command_stream() {
20513        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
20514        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
20515        let ctx = workflow_context(vec![
20516            history_event(
20517                "SideEffectRecorded",
20518                json!({"sequence": 1, "result": first}),
20519            ),
20520            history_event(
20521                "SideEffectRecorded",
20522                json!({"sequence": 2, "result": second}),
20523            ),
20524        ]);
20525        let first: String = ctx
20526            .side_effect(|| panic!("first callback must not run"))
20527            .expect("first replay");
20528        let second: i32 = ctx
20529            .side_effect(|| panic!("second callback must not run"))
20530            .expect("second replay");
20531        assert_eq!(first, "first");
20532        assert_eq!(second, 29);
20533        ctx.ensure_history_consumed().expect("ordered history");
20534
20535        let reordered = workflow_context(vec![history_event(
20536            "VersionMarkerRecorded",
20537            json!({
20538                "sequence": 1,
20539                "change_id": "before-side-effect",
20540                "version": 1,
20541                "min_supported": 1,
20542                "max_supported": 1,
20543            }),
20544        )]);
20545        let error = reordered
20546            .side_effect(|| "new".to_string())
20547            .expect_err("command reordering must fail");
20548        assert!(matches!(
20549            error,
20550            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20551                if reason == "recorded_command_mismatch"
20552        ));
20553    }
20554
20555    #[test]
20556    fn legacy_patch_preserves_pending_and_completed_activity_history() {
20557        for completed in [false, true] {
20558            let mut history = vec![history_event(
20559                "ActivityScheduled",
20560                json!({"sequence": 1, "activity_type": "old"}),
20561            )];
20562            if completed {
20563                history.push(history_event(
20564                    "ActivityCompleted",
20565                    json!({
20566                        "sequence": 1,
20567                        "activity_type": "old",
20568                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
20569                    }),
20570                ));
20571            }
20572            for _cold_replay in 0..2 {
20573                let ctx = workflow_context(history.clone());
20574                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
20575                assert!(!ctx.patched("added-step").expect("same frozen decision"));
20576                ctx.deprecate_patch("added-step")
20577                    .expect("retained boundary");
20578                let mut activity = Box::pin(ctx.activity("old", json!([])));
20579                let mut context = TaskContext::from_waker(noop_waker_ref());
20580                match activity.as_mut().poll(&mut context) {
20581                    Poll::Ready(result) => {
20582                        assert!(completed);
20583                        assert_eq!(result.expect("recorded result"), json!(41));
20584                        ctx.ensure_history_consumed().expect("old command retained");
20585                    }
20586                    Poll::Pending => assert!(!completed),
20587                }
20588                assert!(ctx.take_commands().expect("commands").is_empty());
20589            }
20590        }
20591    }
20592
20593    #[test]
20594    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
20595        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
20596        assert!(!ctx.patched("added-step").expect("legacy completed run"));
20597        ctx.deprecate_patch("added-step")
20598            .expect("same legacy decision");
20599        assert!(ctx.take_commands().expect("commands").is_empty());
20600        ctx.ensure_history_consumed().expect("completed history");
20601    }
20602
20603    #[test]
20604    fn legacy_patch_rejects_a_range_without_the_original_branch() {
20605        let ctx = workflow_context(vec![history_event(
20606            "ActivityScheduled",
20607            json!({"sequence": 1, "activity_type": "old"}),
20608        )]);
20609        let error = ctx
20610            .get_version("added-step", 0, 1)
20611            .expect_err("legacy is unsupported");
20612        assert!(matches!(
20613            error,
20614            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20615                if reason == "version_marker_incompatible_range"
20616        ));
20617        assert!(!ctx
20618            .patched("supported-step")
20619            .expect("failed check did not consume history"));
20620        assert!(ctx.take_commands().expect("commands").is_empty());
20621    }
20622
20623    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20624        let mut event = history_event(
20625            "VersionMarkerRecorded",
20626            json!({
20627                "sequence": sequence,
20628                "change_id": "retained-patch",
20629                "version": version,
20630                "min_supported": -1,
20631                "max_supported": 1,
20632            }),
20633        );
20634        event.raw.insert("timestamp".into(), json!(time));
20635        event
20636    }
20637
20638    #[test]
20639    fn retained_patch_markers_preserve_each_original_boundary() {
20640        for completed in [false, true] {
20641            let mut history = vec![
20642                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20643                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20644                history_event(
20645                    "ActivityScheduled",
20646                    json!({"sequence": 3, "activity_type": "old"}),
20647                ),
20648            ];
20649            if completed {
20650                history.push(history_event(
20651                    "ActivityCompleted",
20652                    json!({
20653                        "sequence": 3,
20654                        "activity_type": "old",
20655                        "result": fixture_envelope(json!(41)),
20656                    }),
20657                ));
20658            }
20659            for _cold_replay in 0..2 {
20660                let ctx = workflow_context(history.clone());
20661                assert!(ctx.patched("retained-patch").unwrap());
20662                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20663                assert!(ctx.patched("retained-patch").unwrap());
20664                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20665                ctx.deprecate_patch("retained-patch").unwrap();
20666                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20667                let mut activity = Box::pin(ctx.activity("old", json!([])));
20668                let mut context = TaskContext::from_waker(noop_waker_ref());
20669                match activity.as_mut().poll(&mut context) {
20670                    Poll::Ready(result) => {
20671                        assert!(completed);
20672                        assert_eq!(result.unwrap(), json!(41));
20673                        ctx.ensure_history_consumed().unwrap();
20674                    }
20675                    Poll::Pending => assert!(!completed),
20676                }
20677                assert!(ctx.take_commands().unwrap().is_empty());
20678                let state = ctx.state.lock().unwrap();
20679                for (actual, original) in state.history_events.iter().zip(&history) {
20680                    assert_eq!(actual.payload, original.payload);
20681                    assert_eq!(actual.raw, original.raw);
20682                }
20683            }
20684        }
20685    }
20686
20687    #[test]
20688    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20689        let ctx = workflow_context(vec![
20690            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20691            history_event(
20692                "SideEffectRecorded",
20693                json!({
20694                    "sequence": 2, "result": fixture_envelope(json!("between")),
20695                }),
20696            ),
20697            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20698            history_event(
20699                "VersionMarkerRecorded",
20700                json!({
20701                    "sequence": 4, "change_id": "other-patch", "version": 1,
20702                    "min_supported": -1, "max_supported": 1,
20703                }),
20704            ),
20705        ]);
20706        assert!(ctx.patched("retained-patch").unwrap());
20707        assert!(ctx.patched("retained-patch").unwrap());
20708        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20709        assert_eq!(
20710            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20711            "between"
20712        );
20713        ctx.deprecate_patch("retained-patch").unwrap();
20714        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20715        ctx.deprecate_patch("retained-patch").unwrap();
20716        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20717        assert!(ctx.patched("other-patch").unwrap());
20718        ctx.ensure_history_consumed().unwrap();
20719        assert!(ctx.take_commands().unwrap().is_empty());
20720    }
20721
20722    #[test]
20723    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20724        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20725        alias.payload["max_supported"] = json!(3);
20726        let ctx = workflow_context(vec![
20727            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20728            alias,
20729        ]);
20730        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20731        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20732        assert!(matches!(error,
20733            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20734                if reason == "version_marker_incompatible_range"));
20735        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20736        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20737        ctx.ensure_history_consumed().unwrap();
20738        assert!(ctx.take_commands().unwrap().is_empty());
20739    }
20740
20741    #[test]
20742    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20743        let ctx = workflow_context(Vec::new());
20744        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20745        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20746        assert!(ctx.patched("new-search").expect("patch"));
20747        ctx.deprecate_patch("new-search").expect("deprecate patch");
20748        let commands = ctx.take_commands().expect("commands");
20749        assert_eq!(commands.len(), 2);
20750        assert_eq!(commands[0]["type"], "record_version_marker");
20751        assert_eq!(commands[0]["version"], 2);
20752        assert_eq!(commands[1]["change_id"], "new-search");
20753
20754        let replay = workflow_context(vec![history_event(
20755            "VersionMarkerRecorded",
20756            json!({
20757                "sequence": 1,
20758                "change_id": "checkout-v2",
20759                "version": 2,
20760                "min_supported": 1,
20761                "max_supported": 2,
20762            }),
20763        )]);
20764        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20765        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20766        assert!(replay.take_commands().expect("commands").is_empty());
20767        replay.ensure_history_consumed().expect("history consumed");
20768    }
20769
20770    #[test]
20771    fn version_markers_reject_incompatible_or_malformed_history() {
20772        let incompatible = workflow_context(vec![history_event(
20773            "VersionMarkerRecorded",
20774            json!({
20775                "sequence": 1,
20776                "change_id": "checkout-v2",
20777                "version": 1,
20778                "min_supported": 1,
20779                "max_supported": 2,
20780            }),
20781        )]);
20782        let error = incompatible
20783            .get_version("checkout-v2", 2, 3)
20784            .expect_err("old version is unsupported");
20785        assert!(matches!(
20786            error,
20787            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20788                if reason == "version_marker_incompatible_range"
20789        ));
20790
20791        for (history, reason) in [
20792            (
20793                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20794                "side_effect_result_missing",
20795            ),
20796            (
20797                vec![history_event(
20798                    "SideEffectRecorded",
20799                    json!({
20800                        "sequence": 1,
20801                        "result": {"codec": "avro", "blob": "not-base64"},
20802                    }),
20803                )],
20804                "side_effect_payload_incompatible",
20805            ),
20806            (
20807                vec![history_event(
20808                    "SideEffectRecorded",
20809                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20810                )],
20811                "side_effect_payload_malformed",
20812            ),
20813            (
20814                vec![history_event(
20815                    "VersionMarkerRecorded",
20816                    json!({
20817                        "sequence": 1,
20818                        "change_id": "change",
20819                        "version": 1,
20820                        "min_supported": 2,
20821                        "max_supported": 1,
20822                    }),
20823                )],
20824                "version_marker_history_range_invalid",
20825            ),
20826        ] {
20827            let error = WorkflowState::new(
20828                history,
20829                "rust-workers".to_string(),
20830                DEFAULT_CODEC.to_string(),
20831                None,
20832            )
20833            .expect_err("malformed history must fail");
20834            assert!(matches!(
20835                error,
20836                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20837                    if actual == reason
20838            ));
20839        }
20840    }
20841
20842    #[test]
20843    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20844        let history = vec![history_event(
20845            "SearchAttributesUpserted",
20846            json!({
20847                "sequence": 1,
20848                "attributes": {"customer_tier": "gold"},
20849                "attribute_types": {"customer_tier": "keyword"},
20850                "merged": {"customer_tier": "gold"}
20851            }),
20852        )];
20853
20854        let matching = workflow_context(history.clone());
20855        matching
20856            .upsert_search_attributes(
20857                SearchAttributeUpdate::new()
20858                    .keyword("customer_tier", "gold")
20859                    .expect("keyword update"),
20860            )
20861            .expect("matching typed update must replay");
20862        matching
20863            .ensure_history_consumed()
20864            .expect("history consumed");
20865
20866        let changed_type = workflow_context(history.clone());
20867        let error = changed_type
20868            .upsert_search_attributes(
20869                SearchAttributeUpdate::new()
20870                    .string("customer_tier", "gold")
20871                    .expect("string update"),
20872            )
20873            .expect_err("same JSON value with a different declaration must be nondeterministic");
20874        let Error::NonDeterministicReplay(failure) = error else {
20875            panic!("typed identity drift must be a replay failure");
20876        };
20877        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20878        assert_eq!(failure.sequence, Some(1));
20879
20880        let changed_value = workflow_context(history);
20881        let error = changed_value
20882            .upsert_search_attributes(
20883                SearchAttributeUpdate::new()
20884                    .keyword("customer_tier", "platinum")
20885                    .expect("keyword update"),
20886            )
20887            .expect_err("changed values must be nondeterministic");
20888        let Error::NonDeterministicReplay(failure) = error else {
20889            panic!("value drift must be a replay failure");
20890        };
20891        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20892    }
20893
20894    #[test]
20895    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20896        let history = vec![history_event(
20897            "SearchAttributesUpserted",
20898            json!({
20899                "sequence": 1,
20900                "attributes": {"customer_tier": "gold"},
20901                "merged": {"customer_tier": "gold"}
20902            }),
20903        )];
20904
20905        for update in [
20906            SearchAttributeUpdate::new()
20907                .keyword("customer_tier", "gold")
20908                .expect("keyword update"),
20909            SearchAttributeUpdate::new()
20910                .string("customer_tier", "gold")
20911                .expect("string update"),
20912        ] {
20913            let restarted = workflow_context(history.clone());
20914            restarted
20915                .upsert_search_attributes(update)
20916                .expect("legacy history constrains values but has unknown type identity");
20917            restarted
20918                .ensure_history_consumed()
20919                .expect("history consumed");
20920        }
20921    }
20922
20923    #[test]
20924    fn search_attribute_command_emits_canonical_types() {
20925        let ctx = workflow_context(Vec::new());
20926        ctx.upsert_search_attributes(
20927            SearchAttributeUpdate::new()
20928                .keyword("customer_tier", "gold")
20929                .expect("keyword update")
20930                .int("attempts", 3)
20931                .expect("int update")
20932                .delete("obsolete")
20933                .expect("delete update"),
20934        )
20935        .expect("valid search attributes");
20936
20937        assert_eq!(
20938            ctx.take_commands().expect("commands"),
20939            vec![json!({
20940                "type": "upsert_search_attributes",
20941                "attributes": {
20942                    "attempts": 3,
20943                    "customer_tier": "gold",
20944                    "obsolete": null
20945                },
20946                "attribute_types": {
20947                    "attempts": "int",
20948                    "customer_tier": "keyword"
20949                }
20950            })]
20951        );
20952    }
20953
20954    #[test]
20955    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20956        let duplicate_side_effect = WorkflowState::new(
20957            vec![
20958                history_event(
20959                    "SideEffectRecorded",
20960                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
20961                ),
20962                history_event(
20963                    "SideEffectRecorded",
20964                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
20965                ),
20966            ],
20967            "rust-workers".to_string(),
20968            DEFAULT_CODEC.to_string(),
20969            None,
20970        )
20971        .expect_err("duplicate side effect");
20972        assert!(matches!(
20973            duplicate_side_effect,
20974            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20975                if reason == "duplicate_side_effect_record"
20976        ));
20977
20978        let marker = |sequence, version| {
20979            history_event(
20980                "VersionMarkerRecorded",
20981                json!({
20982                    "sequence": sequence,
20983                    "change_id": "same-change",
20984                    "version": version,
20985                    "min_supported": -1,
20986                    "max_supported": 1,
20987                }),
20988            )
20989        };
20990        let duplicate_marker = WorkflowState::new(
20991            vec![marker(1, 1), marker(3, -1)],
20992            "rust-workers".to_string(),
20993            DEFAULT_CODEC.to_string(),
20994            None,
20995        )
20996        .expect_err("conflicting marker");
20997        assert!(matches!(
20998            duplicate_marker,
20999            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21000                if reason == "version_marker_conflict"
21001        ));
21002    }
21003
21004    #[test]
21005    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
21006        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
21007        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21008        invalid_alias.payload["max_supported"] = json!(0);
21009        for (history, expected_reason) in [
21010            (
21011                vec![marker.clone(), marker.clone()],
21012                "duplicate_version_marker_record",
21013            ),
21014            (
21015                vec![marker, invalid_alias],
21016                "version_marker_history_range_invalid",
21017            ),
21018        ] {
21019            let error =
21020                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
21021                    .expect_err("invalid historical alias");
21022            assert!(matches!(error,
21023                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
21024                    if reason == expected_reason));
21025        }
21026    }
21027
21028    #[test]
21029    fn retained_patch_aliases_require_the_original_call_boundary() {
21030        let ctx = workflow_context(vec![
21031            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21032            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21033        ]);
21034        assert!(ctx.patched("retained-patch").unwrap());
21035        assert!(ctx.ensure_history_consumed().is_err());
21036        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21037        ctx.deprecate_patch("retained-patch").unwrap();
21038        ctx.ensure_history_consumed().unwrap();
21039        assert!(ctx.take_commands().unwrap().is_empty());
21040    }
21041
21042    #[test]
21043    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
21044        let ctx = workflow_context(vec![
21045            history_event(
21046                "SideEffectRecorded",
21047                json!({
21048                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
21049                }),
21050            ),
21051            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21052        ]);
21053        assert!(!ctx.patched("retained-patch").unwrap());
21054        assert_eq!(
21055            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21056            "old-operation"
21057        );
21058        let error = ctx.patched("retained-patch").unwrap_err();
21059        assert!(matches!(error,
21060            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21061                if reason == "version_marker_conflict"));
21062        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21063        assert!(ctx.take_commands().unwrap().is_empty());
21064    }
21065
21066    #[test]
21067    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
21068        let mut state = WorkflowState::new(
21069            Vec::new(),
21070            "rust-workers".to_string(),
21071            DEFAULT_CODEC.to_string(),
21072            None,
21073        )
21074        .expect("workflow state");
21075        state.workflow_command_identity = "command-7".to_string();
21076        let context = WorkflowContext {
21077            state: Arc::new(Mutex::new(state)),
21078            cancellation_scope_id: "root".into(),
21079        };
21080        let item =
21081            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
21082
21083        context
21084            .append_workflow_stream("output", &[item], Some(10))
21085            .expect("append command");
21086        context
21087            .error_workflow_stream("output", "producer failed", None)
21088            .expect("error command");
21089        let commands = context.take_commands().expect("commands");
21090
21091        assert_eq!(commands[0]["type"], "record_side_effect");
21092        assert_eq!(
21093            commands[0]["workflow_stream"]["command_identity"],
21094            "command-7"
21095        );
21096        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
21097        assert_eq!(
21098            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21099            "dw-stream:command-7:0:0"
21100        );
21101        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
21102
21103        let recorded = history_event(
21104            "SideEffectRecorded",
21105            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
21106        );
21107        let mut replay_state = WorkflowState::new(
21108            vec![recorded],
21109            "rust-workers".to_string(),
21110            DEFAULT_CODEC.to_string(),
21111            None,
21112        )
21113        .expect("replay state");
21114        replay_state.workflow_command_identity = "command-7".to_string();
21115        let replay_context = WorkflowContext {
21116            state: Arc::new(Mutex::new(replay_state)),
21117            cancellation_scope_id: "root".into(),
21118        };
21119        replay_context
21120            .append_workflow_stream(
21121                "output",
21122                &[WorkflowStreamAppendItem::from_reference(
21123                    "s3://bucket/item.avro",
21124                )],
21125                Some(10),
21126            )
21127            .expect("replayed append");
21128        assert!(replay_context
21129            .take_commands()
21130            .expect("replayed commands")
21131            .is_empty());
21132    }
21133
21134    #[test]
21135    fn workflow_stream_authoring_requires_server_durable_command_identity() {
21136        let context = workflow_context(Vec::new());
21137        let error = context
21138            .append_workflow_stream(
21139                "output",
21140                &[WorkflowStreamAppendItem::from_reference(
21141                    "s3://bucket/item.avro",
21142                )],
21143                None,
21144            )
21145            .expect_err("stream append without durable command identity must fail closed");
21146
21147        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
21148        assert!(context.take_commands().expect("commands").is_empty());
21149    }
21150
21151    #[test]
21152    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
21153        let client = Client::builder("http://localhost:8080").build().unwrap();
21154        let mut worker = Worker::new(client, "rust-workers");
21155        worker.register_workflow("streams.worker", |ctx, _| async move {
21156            ctx.append_workflow_stream(
21157                "output",
21158                &[WorkflowStreamAppendItem::new(json!("hello"))?],
21159                None,
21160            )?;
21161            ctx.close_workflow_stream("output", None)?;
21162            Ok(json!("done"))
21163        });
21164        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
21165            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21166            task.workflow_command_id = command_id.clone();
21167            let expected_identity = command_id
21168                .as_deref()
21169                .filter(|id| !id.is_empty())
21170                .unwrap_or(&task.task_id)
21171                .to_string();
21172            let commands = worker
21173                .execute_workflow_task(task)
21174                .expect("ordinary worker stream output");
21175            assert_eq!(commands.len(), 3);
21176            assert_eq!(
21177                commands[0]["workflow_stream"]["command_identity"],
21178                expected_identity
21179            );
21180            assert_eq!(
21181                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21182                format!("dw-stream:{expected_identity}:0:0")
21183            );
21184            assert_eq!(
21185                commands[1]["workflow_stream"]["command_identity"],
21186                expected_identity
21187            );
21188            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
21189            let history = commands[..2]
21190                .iter()
21191                .enumerate()
21192                .map(|(index, command)| {
21193                    history_event(
21194                        "SideEffectRecorded",
21195                        json!({"sequence":index + 1,"result":command["result"]}),
21196                    )
21197                })
21198                .collect();
21199            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
21200            replay.task_id = "replacement-task".to_string();
21201            let replayed = worker
21202                .execute_workflow_task(replay)
21203                .expect("replacement worker consumes recorded stream effects");
21204            assert_eq!(replayed.len(), 1);
21205            assert_eq!(replayed[0]["type"], "complete_workflow");
21206        }
21207        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21208        missing.task_id.clear();
21209        assert!(matches!(
21210            worker.execute_workflow_task(missing),
21211            Err(Error::MissingWorkflowCommandIdentity)
21212        ));
21213    }
21214
21215    #[test]
21216    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
21217        fn worker(calls: Arc<AtomicUsize>) -> Worker {
21218            let client = Client::new("http://127.0.0.1:8080").expect("client");
21219            let mut worker = Worker::new(client, "rust-workers");
21220            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
21221                let calls = Arc::clone(&calls);
21222                async move {
21223                    let captured = ctx.side_effect(|| {
21224                        calls.fetch_add(1, Ordering::SeqCst);
21225                        "captured-once".to_string()
21226                    })?;
21227                    let version = ctx.get_version("cold-restart", 1, 2)?;
21228                    Ok(json!({"captured": captured, "version": version}))
21229                }
21230            });
21231            worker
21232        }
21233
21234        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
21235            WorkflowTask {
21236                task_id: "wft-side-effect-version".to_string(),
21237                observability_context: None,
21238                dispatch_observability_context: None,
21239                observability_links: None,
21240                workflow_command_id: None,
21241                workflow_id: Some("wf-side-effect-version".to_string()),
21242                run_id: Some("run-side-effect-version".to_string()),
21243                workflow_type: "rust.side-effect-version".to_string(),
21244                cancel_requested: false,
21245                payload_codec: DEFAULT_CODEC.to_string(),
21246                arguments: Some(
21247                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
21248                ),
21249                history_events,
21250                total_history_events: None,
21251                history_size_bytes: None,
21252                continue_as_new_recommended: None,
21253                history_budget_pressure: None,
21254                next_history_page_token: None,
21255                workflow_task_attempt: 1,
21256                workflow_signal_id: None,
21257                signal_name: None,
21258                signal_arguments: None,
21259                workflow_update_id: None,
21260                update_name: None,
21261                lease_owner: Some("rust-worker".to_string()),
21262            }
21263        }
21264
21265        let calls = Arc::new(AtomicUsize::new(0));
21266        let initial = worker(Arc::clone(&calls))
21267            .execute_workflow_task(task(Vec::new()))
21268            .expect("initial execution");
21269        assert_eq!(
21270            initial
21271                .iter()
21272                .map(|command| &command["type"])
21273                .collect::<Vec<_>>(),
21274            vec![
21275                "record_side_effect",
21276                "record_version_marker",
21277                "complete_workflow"
21278            ]
21279        );
21280        assert_eq!(calls.load(Ordering::SeqCst), 1);
21281
21282        let restarted = worker(Arc::clone(&calls));
21283        let replayed = restarted
21284            .execute_workflow_task(task(vec![
21285                history_event(
21286                    "SideEffectRecorded",
21287                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
21288                ),
21289                history_event(
21290                    "VersionMarkerRecorded",
21291                    json!({
21292                        "sequence": 2,
21293                        "change_id": "cold-restart",
21294                        "version": 2,
21295                        "min_supported": 1,
21296                        "max_supported": 2,
21297                    }),
21298                ),
21299            ]))
21300            .expect("cold replay");
21301        assert_eq!(replayed.len(), 1);
21302        assert_eq!(replayed[0]["type"], "complete_workflow");
21303        assert_eq!(calls.load(Ordering::SeqCst), 1);
21304    }
21305
21306    #[test]
21307    fn side_effect_replay_rejects_changed_rust_value_type() {
21308        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
21309        let ctx = workflow_context(vec![history_event(
21310            "SideEffectRecorded",
21311            json!({"sequence": 1, "result": result}),
21312        )]);
21313        let error = ctx
21314            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
21315            .expect_err("changed type must fail replay");
21316        assert!(matches!(
21317            error,
21318            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21319                if reason == "side_effect_type_mismatch"
21320        ));
21321    }
21322
21323    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
21324        vec![
21325            history_event(
21326                "ActivityScheduled",
21327                json!({
21328                    "sequence": 1,
21329                    "activity_type": "flaky",
21330                    "activity_execution_id": "act-1",
21331                    "activity": {
21332                        "id": "act-1",
21333                        "sequence": 1,
21334                        "type": "flaky",
21335                        "queue": "critical-activities",
21336                        "execution_mode": null,
21337                        "retry_policy": {
21338                            "snapshot_version": 1,
21339                            "max_attempts": 3,
21340                            "backoff_seconds": [2, 4],
21341                            "start_to_close_timeout": 30,
21342                            "schedule_to_start_timeout": 5,
21343                            "schedule_to_close_timeout": 90,
21344                            "heartbeat_timeout": 10,
21345                            "non_retryable_error_types": ["PermanentError"]
21346                        }
21347                    }
21348                }),
21349            ),
21350            history_event(
21351                "ActivityStarted",
21352                json!({
21353                    "sequence": 1,
21354                    "activity_type": "flaky",
21355                    "activity_execution_id": "act-1",
21356                    "activity_attempt_id": "attempt-1",
21357                    "attempt_number": 1
21358                }),
21359            ),
21360            history_event(
21361                "ActivityRetryScheduled",
21362                json!({
21363                    "sequence": 1,
21364                    "activity_type": "flaky",
21365                    "activity_execution_id": "act-1",
21366                    "activity_attempt_id": "attempt-1",
21367                    "attempt_number": 1,
21368                    "retry_after_attempt": 1,
21369                    "retry_backoff_seconds": 2,
21370                    "failure_category": "activity",
21371                    "exception_type": "TransientError"
21372                }),
21373            ),
21374            history_event(
21375                "ActivityStarted",
21376                json!({
21377                    "sequence": 1,
21378                    "activity_type": "flaky",
21379                    "activity_execution_id": "act-1",
21380                    "activity_attempt_id": "attempt-2",
21381                    "attempt_number": 2
21382                }),
21383            ),
21384            history_event(
21385                "ActivityCompleted",
21386                json!({
21387                    "sequence": 1,
21388                    "activity_type": "flaky",
21389                    "activity_execution_id": "act-1",
21390                    "activity_attempt_id": "attempt-2",
21391                    "attempt_number": 2,
21392                    "payload_codec": DEFAULT_CODEC,
21393                    "result": fixture_envelope(json!({"status":"recovered"}))
21394                }),
21395            ),
21396        ]
21397    }
21398
21399    fn retry_activity_options() -> ActivityOptions {
21400        ActivityOptions::new()
21401            .task_queue("critical-activities")
21402            .retry_policy(
21403                ActivityRetryPolicy::new(3)
21404                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
21405                    .non_retryable_error_type("PermanentError"),
21406            )
21407            .start_to_close_timeout(Duration::from_secs(30))
21408            .schedule_to_start_timeout(Duration::from_secs(5))
21409            .schedule_to_close_timeout(Duration::from_secs(90))
21410            .heartbeat_timeout(Duration::from_secs(10))
21411    }
21412
21413    #[test]
21414    fn fixed_avro_value_round_trips_json_values() {
21415        let value = json!({"greeting": "hello", "count": 3, "ok": true});
21416        let envelope = PayloadEnvelope::avro(&value).expect("encode");
21417        assert_eq!(envelope.codec, DEFAULT_CODEC);
21418        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
21419    }
21420
21421    #[tokio::test]
21422    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
21423        let client = Client::new("http://127.0.0.1:8080").expect("client");
21424        let mut worker = Worker::new(client, "rust-workers");
21425        worker.register_typed_workflow(
21426            "typed.contract.workflow",
21427            |_ctx, input: TypedContract| async move { Ok(input) },
21428        );
21429        worker.register_typed_activity(
21430            "typed.contract.activity",
21431            |_ctx, input: TypedContract| async move { Ok(input) },
21432        );
21433
21434        let expected = typed_contract();
21435        let arguments = AvroValue::Array(vec![
21436            AvroValue::from_serialize(&expected).expect("typed request")
21437        ]);
21438        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
21439        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
21440        workflow.arguments = Some(envelope.clone());
21441        let commands = worker
21442            .execute_workflow_task(workflow)
21443            .expect("typed workflow task");
21444        let workflow_result: TypedContract =
21445            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21446                .expect("workflow result envelope")
21447                .deserialize()
21448                .expect("workflow result type");
21449        assert_eq!(workflow_result, expected);
21450
21451        let activity = ActivityTask {
21452            task_id: "typed-contract-activity".to_string(),
21453            workflow_id: None,
21454            run_id: None,
21455            activity_execution_id: None,
21456            observability_context: None,
21457            dispatch_observability_context: None,
21458            observability_links: None,
21459            activity_attempt_id: Some("typed-contract-attempt".to_string()),
21460            attempt_id: None,
21461            activity_type: "typed.contract.activity".to_string(),
21462            payload_codec: DEFAULT_CODEC.to_string(),
21463            arguments: Some(envelope),
21464            attempt_number: 1,
21465            lease_owner: Some("rust-worker".to_string()),
21466        };
21467        let activity_result: TypedContract = worker
21468            .execute_activity_task(activity)
21469            .await
21470            .expect("typed activity task")
21471            .deserialize()
21472            .expect("activity result type");
21473        assert_eq!(activity_result, expected);
21474    }
21475
21476    #[test]
21477    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
21478        let calls = Arc::new(AtomicUsize::new(0));
21479        let observed = Arc::clone(&calls);
21480        let client = Client::new("http://127.0.0.1:8080").expect("client");
21481        let mut worker = Worker::new(client.clone(), "rust-workers");
21482        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
21483            observed.fetch_add(1, Ordering::SeqCst);
21484            async move { Ok(input) }
21485        });
21486        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
21487        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
21488        let original = task.clone();
21489        let error = worker
21490            .execute_workflow_task(task)
21491            .expect_err("incompatible entry must refuse the task, not fail the run");
21492        assert_eq!(calls.load(Ordering::SeqCst), 0);
21493        assert!(error
21494            .to_string()
21495            .contains("workflow_entry_arguments_mismatch:"));
21496        assert!(!error.to_string().contains("private-original-value"));
21497
21498        let mut compatible = Worker::new(client, "rust-workers");
21499        compatible
21500            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
21501        let commands = compatible
21502            .execute_workflow_task(original)
21503            .expect("same recorded input");
21504        assert_eq!(commands[0]["type"], "complete_workflow");
21505        assert_eq!(
21506            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
21507            json!("private-original-value")
21508        );
21509    }
21510
21511    #[test]
21512    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
21513        let factories = Arc::new(AtomicUsize::new(0));
21514        let observed = Arc::clone(&factories);
21515        let client = Client::new("http://127.0.0.1:8080").expect("client");
21516        let mut worker = Worker::new(client, "rust-workers");
21517        worker.register_typed_replayed_workflow(
21518            "entry.replayed",
21519            move || {
21520                observed.fetch_add(1, Ordering::SeqCst);
21521                ()
21522            },
21523            |_ctx, _input: i64, _state| async move {
21524                panic!("body must not start");
21525                #[allow(unreachable_code)]
21526                Ok(0_i64)
21527            },
21528        );
21529        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
21530        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
21531        let error = worker
21532            .execute_workflow_task(task)
21533            .expect_err("entry refusal");
21534        assert_eq!(factories.load(Ordering::SeqCst), 0);
21535        assert!(error
21536            .to_string()
21537            .contains("workflow_entry_arguments_mismatch:"));
21538        assert!(!error.to_string().contains("private-replayed-value"));
21539
21540        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
21541        let Err(error) = replay(
21542            workflow_context(Vec::new()),
21543            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
21544        ) else {
21545            panic!("query replay must refuse before creating application state");
21546        };
21547        assert_eq!(factories.load(Ordering::SeqCst), 0);
21548        assert!(!error.to_string().contains("private-replayed-value"));
21549    }
21550
21551    #[test]
21552    fn typed_entry_deserializes_once_before_entering_application_code() {
21553        static DECODES: AtomicUsize = AtomicUsize::new(0);
21554        struct Counted(i64);
21555        impl<'de> Deserialize<'de> for Counted {
21556            fn deserialize<D: Deserializer<'de>>(
21557                deserializer: D,
21558            ) -> std::result::Result<Self, D::Error> {
21559                DECODES.fetch_add(1, Ordering::SeqCst);
21560                i64::deserialize(deserializer).map(Self)
21561            }
21562        }
21563        DECODES.store(0, Ordering::SeqCst);
21564        let client = Client::new("http://127.0.0.1:8080").expect("client");
21565        let mut worker = Worker::new(client, "rust-workers");
21566        worker.register_typed_workflow(
21567            "entry.once",
21568            |_ctx, input: Counted| async move { Ok(input.0) },
21569        );
21570        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
21571        task.arguments = Some(fixture_envelope(json!([7])));
21572        let commands = worker.execute_workflow_task(task).expect("typed result");
21573        assert_eq!(commands[0]["type"], "complete_workflow");
21574        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
21575    }
21576
21577    #[test]
21578    fn typed_entry_body_input_error_remains_a_business_failure() {
21579        let client = Client::new("http://127.0.0.1:8080").expect("client");
21580        let mut worker = Worker::new(client, "rust-workers");
21581        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
21582            Err::<i64, _>(handler_type_error::<i64>(
21583                HandlerKind::Workflow,
21584                "entry.body",
21585                HandlerValueKind::Input,
21586                "deliberate body error",
21587            ))
21588        });
21589        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
21590        task.arguments = Some(fixture_envelope(json!([7])));
21591        let commands = worker
21592            .execute_workflow_task(task)
21593            .expect("business failure command");
21594        assert_eq!(commands[0]["type"], "fail_workflow");
21595        assert!(commands[0]["message"]
21596            .as_str()
21597            .unwrap()
21598            .contains("deliberate body error"));
21599    }
21600
21601    #[test]
21602    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
21603        let client = Client::new("http://127.0.0.1:8080").expect("client");
21604        let mut worker = Worker::new(client, "rust-workers");
21605        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
21606            Err::<i64, _>(handler_type_error::<i64>(
21607                HandlerKind::Workflow,
21608                "entry.body.refusal",
21609                HandlerValueKind::Input,
21610                "workflow_entry_arguments_mismatch: deliberate body error",
21611            ))
21612        });
21613        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
21614        task.arguments = Some(fixture_envelope(json!([7])));
21615        let commands = worker
21616            .execute_workflow_task(task)
21617            .expect("business failure");
21618        assert_eq!(commands[0]["type"], "fail_workflow");
21619    }
21620
21621    #[tokio::test]
21622    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21623        let client = Client::new("http://127.0.0.1:8080").expect("client");
21624        let mut worker = Worker::new(client, "rust-workers");
21625        worker.register_typed_workflow(
21626            "typed.shape.workflow",
21627            |_ctx, input: TypedContract| async move { Ok(input) },
21628        );
21629        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21630            Ok(f64::NAN)
21631        });
21632
21633        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21634        workflow.arguments = Some(
21635            encode_typed_envelope(
21636                &AvroValue::Array(vec![
21637                    AvroValue::String("first".to_string()),
21638                    AvroValue::String("second".to_string()),
21639                ]),
21640                DEFAULT_CODEC,
21641            )
21642            .expect("malformed typed arguments"),
21643        );
21644        let error = worker
21645            .execute_workflow_task(workflow)
21646            .expect_err("entry shape mismatch refuses the task");
21647        let message = error.to_string();
21648        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21649        assert!(message.contains("typed.shape.workflow"));
21650        assert!(message.contains(type_name::<TypedContract>()));
21651
21652        let activity = ActivityTask {
21653            task_id: "typed-unsupported-activity".to_string(),
21654            workflow_id: None,
21655            run_id: None,
21656            activity_execution_id: None,
21657            observability_context: None,
21658            dispatch_observability_context: None,
21659            observability_links: None,
21660            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21661            attempt_id: None,
21662            activity_type: "typed.unsupported.activity".to_string(),
21663            payload_codec: DEFAULT_CODEC.to_string(),
21664            arguments: Some(
21665                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21666                    .expect("unit arguments"),
21667            ),
21668            attempt_number: 1,
21669            lease_owner: Some("rust-worker".to_string()),
21670        };
21671        let Error::HandlerType {
21672            handler_kind,
21673            handler_name,
21674            value_kind,
21675            rust_type,
21676            message,
21677        } = worker
21678            .execute_activity_task(activity)
21679            .await
21680            .expect_err("non-finite handler output must fail")
21681        else {
21682            panic!("expected contextual handler type failure");
21683        };
21684        assert_eq!(handler_kind, HandlerKind::Activity);
21685        assert_eq!(handler_name, "typed.unsupported.activity");
21686        assert_eq!(value_kind, HandlerValueKind::Result);
21687        assert_eq!(rust_type, type_name::<f64>());
21688        assert!(message.contains("non_finite_float"));
21689    }
21690
21691    #[tokio::test]
21692    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21693        #[derive(Clone, Default)]
21694        struct State {
21695            observed: Option<TypedContract>,
21696        }
21697
21698        let client = Client::new("http://127.0.0.1:8080").expect("client");
21699        let mut worker = Worker::new(client, "rust-workers");
21700        worker.register_typed_replayed_workflow(
21701            "typed.contract.replayed",
21702            State::default,
21703            |ctx, input: TypedContract, state| async move {
21704                let result: TypedContract =
21705                    ctx.activity_typed("typed.contract.activity", input).await?;
21706                state.update(|current| current.observed = Some(result.clone()))?;
21707                Ok(result)
21708            },
21709        );
21710        worker.register_replayed_query::<State, _, _>(
21711            "typed.contract.replayed",
21712            "observed",
21713            |_ctx, state, _args| async move {
21714                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21715            },
21716        );
21717
21718        let expected = typed_contract();
21719        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21720        let workflow_arguments =
21721            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21722                .expect("workflow arguments");
21723        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21724        let task = QueryTask {
21725            query_task_id: "typed-replay-query".to_string(),
21726            observability_context: None,
21727            dispatch_observability_context: None,
21728            observability_links: None,
21729            query_task_attempt: 1,
21730            lease_owner: Some("rust-worker".to_string()),
21731            workflow_id: Some("typed-replay".to_string()),
21732            run_id: Some("typed-replay-run".to_string()),
21733            workflow_type: "typed.contract.replayed".to_string(),
21734            query_name: "observed".to_string(),
21735            payload_codec: DEFAULT_CODEC.to_string(),
21736            workflow_arguments: Some(workflow_arguments),
21737            query_arguments: Some(
21738                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21739                    .expect("query arguments"),
21740            ),
21741            history_events: vec![
21742                history_event(
21743                    "ActivityScheduled",
21744                    json!({
21745                        "sequence": 1,
21746                        "activity_type": "typed.contract.activity"
21747                    }),
21748                ),
21749                history_event(
21750                    "ActivityCompleted",
21751                    json!({
21752                        "sequence": 1,
21753                        "activity_type": "typed.contract.activity",
21754                        "payload_codec": DEFAULT_CODEC,
21755                        "result": result
21756                    }),
21757                ),
21758            ],
21759            history_export: None,
21760            run_status: Some("completed".to_string()),
21761        };
21762
21763        assert_eq!(
21764            worker
21765                .execute_query_task(task)
21766                .await
21767                .expect("typed replay query")
21768                .deserialize::<i64>()
21769                .expect("query result"),
21770            expected.signed
21771        );
21772    }
21773
21774    #[tokio::test]
21775    async fn update_context_preserves_workflow_input_and_committed_signals() {
21776        let client = Client::new("http://127.0.0.1:8080").expect("client");
21777        let mut worker = Worker::new(client, "rust-workers");
21778        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21779        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21780        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21781        let expected_input = workflow_input.clone();
21782        let expected_signals = signal_arguments.clone();
21783        let handler = move |context: QueryContext, arguments: AvroValue| {
21784            let expected_input = expected_input.clone();
21785            let expected_signals = expected_signals.clone();
21786            async move {
21787                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21788                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21789                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21790                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21791                assert_eq!(
21792                    context.signals_avro_value("changed"),
21793                    vec![expected_signals.clone()]
21794                );
21795                assert_eq!(
21796                    context.signals("changed"),
21797                    vec![expected_signals
21798                        .into_iter()
21799                        .map(AvroValue::into_json)
21800                        .collect::<Result<Vec<_>>>()?]
21801                );
21802                assert_eq!(
21803                    context.signal_events()[0].id.as_deref(),
21804                    Some("signal-original")
21805                );
21806                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21807                Ok(arguments)
21808            }
21809        };
21810        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21811        worker.register_update_avro_value("snapshot", "inspect", handler);
21812        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21813        let update_envelope =
21814            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21815        let mut task = workflow_task(
21816            "snapshot",
21817            vec![
21818                history_event(
21819                    "SignalReceived",
21820                    json!({
21821                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21822                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21823                    }),
21824                ),
21825                history_event(
21826                    "UpdateAccepted",
21827                    json!({
21828                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21829                    }),
21830                ),
21831            ],
21832            DEFAULT_CODEC,
21833        );
21834        task.arguments =
21835            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21836        task.workflow_update_id = Some("update-original".into());
21837        task.update_name = Some("inspect".into());
21838        let query = QueryTask {
21839            query_task_id: "query-snapshot".into(),
21840            observability_context: None,
21841            dispatch_observability_context: None,
21842            observability_links: None,
21843            query_task_attempt: 1,
21844            lease_owner: None,
21845            workflow_id: task.workflow_id.clone(),
21846            run_id: task.run_id.clone(),
21847            workflow_type: task.workflow_type.clone(),
21848            query_name: "inspect".into(),
21849            payload_codec: DEFAULT_CODEC.into(),
21850            workflow_arguments: task.arguments.clone(),
21851            query_arguments: Some(update_envelope),
21852            history_events: task.history_events.clone(),
21853            history_export: None,
21854            run_status: Some("running".into()),
21855        };
21856        assert_eq!(
21857            worker
21858                .execute_query_task(query)
21859                .await
21860                .expect("query snapshot"),
21861            update_arguments
21862        );
21863        for _ in 0..2 {
21864            let commands = worker
21865                .execute_workflow_task(task.clone())
21866                .expect("cold update snapshot");
21867            assert_eq!(commands[0]["type"], "complete_update");
21868            assert_eq!(commands[0]["update_id"], "update-original");
21869            assert_eq!(
21870                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21871                    .expect("update result"),
21872                update_arguments
21873            );
21874        }
21875    }
21876
21877    #[test]
21878    fn committed_signal_snapshot_counts_identities_once() {
21879        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21880        let received = history_event(
21881            "SignalReceived",
21882            json!({
21883                "signal_id": "signal-first", "workflow_command_id": "command-first",
21884                "signal_name": "changed", "arguments": arguments.clone(),
21885            }),
21886        );
21887        let applied = history_event(
21888            "SignalApplied",
21889            json!({
21890                "signal_id": "signal-first", "workflow_command_id": "command-first",
21891                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21892            }),
21893        );
21894        let distinct = history_event(
21895            "SignalReceived",
21896            json!({
21897                "signal_id": "signal-second", "workflow_command_id": "command-second",
21898                "signal_name": "changed", "arguments": arguments,
21899            }),
21900        );
21901        let history = vec![received.clone(), applied.clone(), distinct];
21902        let signals =
21903            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21904        assert_eq!(signals.len(), 2);
21905        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21906        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21907        assert_eq!(signals[0].workflow_sequence, Some(1));
21908        assert_eq!(signals[0].arguments, signals[1].arguments);
21909        let mut command_only = received.clone();
21910        command_only
21911            .payload
21912            .as_object_mut()
21913            .expect("payload")
21914            .remove("signal_id");
21915        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21916            .expect("command identity");
21917        assert_eq!(signals.len(), 1);
21918        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21919        let mut conflicting = applied;
21920        conflicting.payload["value"] =
21921            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21922        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21923    }
21924
21925    #[test]
21926    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21927        for arguments in [
21928            vec![],
21929            vec![AvroValue::Array(vec![
21930                AvroValue::Long(1),
21931                AvroValue::Long(2),
21932            ])],
21933            vec![AvroValue::Bytes(vec![0, 255])],
21934            vec![AvroValue::Null],
21935            vec![AvroValue::Boolean(false)],
21936            vec![
21937                AvroValue::Long(1),
21938                AvroValue::Array(vec![AvroValue::Long(2)]),
21939            ],
21940        ] {
21941            let applied = match arguments.as_slice() {
21942                [] => AvroValue::Boolean(true),
21943                [value] => value.clone(),
21944                values => AvroValue::Array(values.to_vec()),
21945            };
21946            for applied in [applied, AvroValue::Array(arguments.clone())] {
21947                let events = vec![
21948                    history_event(
21949                        "SignalReceived",
21950                        json!({
21951                            "signal_id": "original", "signal_name": "changed",
21952                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
21953                        }),
21954                    ),
21955                    history_event(
21956                        "SignalApplied",
21957                        json!({
21958                            "signal_id": "original", "signal_name": "changed",
21959                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
21960                        }),
21961                    ),
21962                ];
21963                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
21964                    .expect("canonical signal snapshot");
21965                assert_eq!(signals.len(), 1);
21966                assert_eq!(signals[0].avro_arguments, arguments);
21967            }
21968        }
21969    }
21970
21971    #[tokio::test]
21972    async fn update_context_rejects_malformed_snapshot_before_handler() {
21973        let client = Client::new("http://127.0.0.1:8080").expect("client");
21974        let mut worker = Worker::new(client, "rust-workers");
21975        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21976        let calls = Arc::new(AtomicUsize::new(0));
21977        let observed = Arc::clone(&calls);
21978        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
21979            observed.fetch_add(1, Ordering::SeqCst);
21980            async { Ok(Value::Null) }
21981        });
21982        let mut task = workflow_task(
21983            "snapshot",
21984            vec![history_event(
21985                "UpdateAccepted",
21986                json!({
21987                    "update_id": "update-original", "update_name": "inspect",
21988                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
21989                }),
21990            )],
21991            DEFAULT_CODEC,
21992        );
21993        task.workflow_update_id = Some("update-original".into());
21994        task.update_name = Some("inspect".into());
21995        let mut bad_input = task.clone();
21996        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
21997        assert!(worker.execute_workflow_task(bad_input).is_err());
21998        task.history_events.insert(0, history_event("SignalReceived", json!({
21999            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
22000        })));
22001        assert!(worker.execute_workflow_task(task).is_err());
22002        assert_eq!(calls.load(Ordering::SeqCst), 0);
22003    }
22004
22005    #[tokio::test]
22006    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
22007        let client = Client::new("http://127.0.0.1:8080").expect("client");
22008        let mut worker = Worker::new(client, "rust-workers");
22009        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
22010        worker
22011            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
22012        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
22013            Ok(input)
22014        });
22015        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
22016            Ok(input)
22017        });
22018        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
22019            Ok(AvroValue::Array(
22020                ctx.wait_signal_avro_value("changed").await?,
22021            ))
22022        });
22023
22024        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
22025        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
22026
22027        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
22028        workflow.arguments = Some(envelope.clone());
22029        let commands = worker
22030            .execute_workflow_task(workflow)
22031            .expect("typed workflow task");
22032        assert_eq!(commands[0]["type"], "complete_workflow");
22033        assert_eq!(
22034            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22035                .expect("typed workflow result"),
22036            arguments
22037        );
22038
22039        let activity = ActivityTask {
22040            task_id: "activity-typed".to_string(),
22041            workflow_id: None,
22042            run_id: None,
22043            activity_execution_id: None,
22044            observability_context: None,
22045            dispatch_observability_context: None,
22046            observability_links: None,
22047            activity_attempt_id: Some("attempt-typed".to_string()),
22048            attempt_id: None,
22049            activity_type: "typed.activity".to_string(),
22050            payload_codec: DEFAULT_CODEC.to_string(),
22051            arguments: Some(envelope.clone()),
22052            attempt_number: 1,
22053            lease_owner: Some("rust-worker".to_string()),
22054        };
22055        assert_eq!(
22056            worker
22057                .execute_activity_task(activity)
22058                .await
22059                .expect("typed activity result"),
22060            arguments
22061        );
22062
22063        let query = QueryTask {
22064            query_task_id: "query-typed".to_string(),
22065            observability_context: None,
22066            dispatch_observability_context: None,
22067            observability_links: None,
22068            query_task_attempt: 1,
22069            lease_owner: Some("rust-worker".to_string()),
22070            workflow_id: Some("typed-1".to_string()),
22071            run_id: Some("run-typed".to_string()),
22072            workflow_type: "typed.echo".to_string(),
22073            query_name: "inspect".to_string(),
22074            payload_codec: DEFAULT_CODEC.to_string(),
22075            workflow_arguments: Some(
22076                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22077                    .expect("workflow input"),
22078            ),
22079            query_arguments: Some(envelope.clone()),
22080            history_events: Vec::new(),
22081            history_export: None,
22082            run_status: Some("running".to_string()),
22083        };
22084        assert_eq!(
22085            worker
22086                .execute_query_task(query)
22087                .await
22088                .expect("typed query result"),
22089            arguments
22090        );
22091
22092        let mut update = workflow_task(
22093            "typed.echo",
22094            vec![history_event(
22095                "UpdateAccepted",
22096                json!({
22097                    "update_id": "update-typed",
22098                    "update_name": "replace",
22099                    "arguments": envelope.clone(),
22100                }),
22101            )],
22102            DEFAULT_CODEC,
22103        );
22104        update.workflow_update_id = Some("update-typed".to_string());
22105        update.update_name = Some("replace".to_string());
22106        let commands = worker
22107            .execute_workflow_task(update)
22108            .expect("typed update task");
22109        assert_eq!(commands[0]["type"], "complete_update");
22110        assert_eq!(
22111            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22112                .expect("typed update result"),
22113            arguments
22114        );
22115
22116        let mut signal = workflow_task(
22117            "typed.signal",
22118            vec![history_event(
22119                "SignalReceived",
22120                json!({
22121                    "signal_id": "signal-typed",
22122                    "signal_name": "changed",
22123                    "arguments": envelope.clone(),
22124                }),
22125            )],
22126            DEFAULT_CODEC,
22127        );
22128        signal.workflow_signal_id = Some("signal-typed".to_string());
22129        signal.signal_name = Some("changed".to_string());
22130        signal.signal_arguments = Some(envelope);
22131        let commands = worker
22132            .execute_workflow_task(signal)
22133            .expect("typed signal resume");
22134        assert_eq!(
22135            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22136                .expect("typed signal result"),
22137            arguments
22138        );
22139    }
22140
22141    #[tokio::test]
22142    async fn typed_helpers_never_parse_json_inspection_projection() {
22143        let collision_values = projection_collision_probe();
22144        let expected = AvroValue::Array(collision_values.clone());
22145        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
22146
22147        let activity_context = workflow_context_with_codec(
22148            vec![history_event(
22149                "ActivityCompleted",
22150                json!({
22151                    "sequence": 1,
22152                    "activity_type": "collision.activity",
22153                    "payload_codec": DEFAULT_CODEC,
22154                    "result": envelope.clone(),
22155                }),
22156            )],
22157            DEFAULT_CODEC,
22158        );
22159        assert_eq!(
22160            activity_context
22161                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
22162                .await
22163                .expect("typed activity collision result"),
22164            expected
22165        );
22166
22167        let signal_context = workflow_context_with_codec(
22168            vec![
22169                history_event(
22170                    "SignalWaitOpened",
22171                    json!({"sequence": 1, "signal_name": "collision"}),
22172                ),
22173                history_event(
22174                    "SignalApplied",
22175                    json!({
22176                        "sequence": 1,
22177                        "signal_name": "collision",
22178                        "payload_codec": DEFAULT_CODEC,
22179                        "value": envelope.clone(),
22180                    }),
22181                ),
22182            ],
22183            DEFAULT_CODEC,
22184        );
22185        assert_eq!(
22186            signal_context
22187                .wait_signal_avro_value("collision")
22188                .await
22189                .expect("typed signal collision arguments"),
22190            collision_values
22191        );
22192
22193        let child_context = workflow_context_with_codec(
22194            vec![
22195                history_event(
22196                    "ChildWorkflowScheduled",
22197                    json!({
22198                        "sequence": 1,
22199                        "child_workflow_instance_id": "collision-child",
22200                        "child_workflow_run_id": "collision-run",
22201                        "child_workflow_type": "collision.child",
22202                    }),
22203                ),
22204                history_event(
22205                    "ChildRunCompleted",
22206                    json!({
22207                        "sequence": 1,
22208                        "child_workflow_instance_id": "collision-child",
22209                        "child_workflow_run_id": "collision-run",
22210                        "child_workflow_type": "collision.child",
22211                        "payload_codec": DEFAULT_CODEC,
22212                        "result": envelope,
22213                    }),
22214                ),
22215            ],
22216            DEFAULT_CODEC,
22217        );
22218        let child = child_context
22219            .start_child_workflow_avro_value(
22220                "collision.child",
22221                ChildWorkflowOptions::new("collision-workers"),
22222                AvroValue::Array(Vec::new()),
22223            )
22224            .await
22225            .expect("typed child collision result");
22226        assert_eq!(child.result, expected);
22227    }
22228
22229    #[tokio::test]
22230    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
22231        let client = Client::new("http://127.0.0.1:8080").expect("client");
22232        let mut worker = Worker::new(client, "rust-workers");
22233        worker.register_replayed_workflow_avro_value(
22234            "typed.replayed",
22235            || (),
22236            |_ctx, input, _state| async move { Ok(input) },
22237        );
22238        worker.register_replayed_query_avro_value::<(), _, _>(
22239            "typed.replayed",
22240            "inspect",
22241            |ctx, _state, args| async move {
22242                let mut signals = ctx.signals_avro_value("collision");
22243                let signal = signals
22244                    .pop()
22245                    .map(AvroValue::Array)
22246                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
22247                Ok(AvroValue::Array(vec![
22248                    ctx.workflow_input_avro_value().clone(),
22249                    signal,
22250                    args,
22251                ]))
22252            },
22253        );
22254        let arguments = AvroValue::Array(projection_collision_probe());
22255        let signal_arguments =
22256            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
22257        let task = QueryTask {
22258            query_task_id: "query-typed-replay".to_string(),
22259            observability_context: None,
22260            dispatch_observability_context: None,
22261            observability_links: None,
22262            query_task_attempt: 1,
22263            lease_owner: Some("rust-worker".to_string()),
22264            workflow_id: Some("typed-replay".to_string()),
22265            run_id: Some("run-typed-replay".to_string()),
22266            workflow_type: "typed.replayed".to_string(),
22267            query_name: "inspect".to_string(),
22268            payload_codec: DEFAULT_CODEC.to_string(),
22269            workflow_arguments: Some(
22270                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
22271            ),
22272            query_arguments: Some(
22273                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
22274            ),
22275            history_events: vec![history_event(
22276                "SignalReceived",
22277                json!({
22278                    "signal_id": "collision-signal",
22279                    "signal_name": "collision",
22280                    "workflow_sequence": 1,
22281                    "payload_codec": DEFAULT_CODEC,
22282                    "arguments": signal_arguments,
22283                }),
22284            )],
22285            history_export: None,
22286            run_status: Some("completed".to_string()),
22287        };
22288
22289        assert_eq!(
22290            worker
22291                .execute_query_task(task)
22292                .await
22293                .expect("typed replay query"),
22294            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
22295        );
22296    }
22297
22298    #[test]
22299    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
22300        let value = BTreeMap::from([(1_i32, "integer key")]);
22301        let error = PayloadEnvelope::avro(&value)
22302            .expect_err("integer map keys must fail")
22303            .to_string();
22304
22305        assert!(error.contains("invalid_map_key"));
22306    }
22307
22308    #[test]
22309    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
22310        let envelope = PayloadEnvelope {
22311            codec: "json".to_string(),
22312            blob: r#"{"greeting":"hello"}"#.to_string(),
22313        };
22314
22315        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
22316        let diagnostic = error.to_string();
22317        assert!(diagnostic.contains("unsupported_payload_codec"));
22318        assert!(diagnostic.contains("codec=\"avro\""));
22319        assert!(diagnostic.contains("HTTP document transport"));
22320    }
22321
22322    #[test]
22323    fn untagged_json_payload_value_fails_closed() {
22324        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
22325            .expect_err("untagged JSON payload values must fail");
22326        let diagnostic = error.to_string();
22327        assert!(diagnostic.contains("unsupported_payload_codec"));
22328        assert!(diagnostic.contains("untagged durable payload"));
22329        assert!(diagnostic.contains("HTTP document transport"));
22330    }
22331
22332    #[test]
22333    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
22334        let envelope = PayloadEnvelope {
22335            codec: DEFAULT_CODEC.to_string(),
22336            blob: BASE64.encode([0x01]),
22337        };
22338
22339        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
22340        assert!(error.to_string().contains("invalid_payload_framing"));
22341    }
22342
22343    #[tokio::test]
22344    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
22345        let server = MockWorkerServer::start();
22346        let client = Client::builder(server.base_url())
22347            .timeout(Duration::from_secs(2))
22348            .build()
22349            .expect("client");
22350        let invalid_commands = [
22351            json!({
22352                "type": "complete_workflow",
22353                "result": {"codec": "json", "blob": null}
22354            }),
22355            json!({
22356                "type": "schedule_activity",
22357                "arguments": {"codec": "yaml", "blob": "ignored"}
22358            }),
22359            json!({
22360                "type": "start_child_workflow",
22361                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
22362            }),
22363            json!({"type": "continue_as_new", "arguments": []}),
22364            json!({"type": "complete_update"}),
22365            json!({"type": "record_side_effect", "result": null}),
22366            json!({
22367                "type": "start_service_operation",
22368                "payload_codec": DEFAULT_CODEC,
22369                "request_payload": "raw-avro-bytes"
22370            }),
22371        ];
22372
22373        for command in invalid_commands {
22374            let error = client
22375                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
22376                .await
22377                .expect_err("invalid durable payload must fail locally");
22378            let diagnostic = error.to_string();
22379            assert!(
22380                diagnostic.contains("unsupported_payload_codec")
22381                    || diagnostic.contains("invalid_payload_envelope")
22382                    || diagnostic.contains("untagged durable payload"),
22383                "unexpected validation diagnostic: {diagnostic}"
22384            );
22385        }
22386
22387        assert_eq!(
22388            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
22389            0,
22390            "invalid command payloads must not reach HTTP transport"
22391        );
22392    }
22393
22394    #[test]
22395    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
22396        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
22397        let commands = [
22398            json!({"type": "complete_workflow", "result": envelope.clone()}),
22399            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
22400            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
22401            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
22402            json!({"type": "complete_update", "result": envelope.clone()}),
22403            json!({"type": "record_side_effect", "result": envelope.clone()}),
22404            json!({
22405                "type": "start_service_operation",
22406                "payload_codec": DEFAULT_CODEC,
22407                "request_payload": envelope.clone()
22408            }),
22409            json!({
22410                "type": "complete_workflow",
22411                "result": envelope,
22412                "metadata": {
22413                    "codec": "json",
22414                    "payload_codec": "customer-codec",
22415                    "result": {"codec": "yaml", "blob": null}
22416                }
22417            }),
22418        ];
22419
22420        validate_workflow_task_commands(&commands)
22421            .expect("customer metadata must not become a protocol codec declaration");
22422    }
22423
22424    #[test]
22425    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
22426        assert_eq!(
22427            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
22428            AvroValue::Array(Vec::new())
22429        );
22430        assert_eq!(
22431            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
22432            AvroValue::Array(Vec::new())
22433        );
22434
22435        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22436        signal.signal_name = Some("empty-signal".to_string());
22437        signal.signal_arguments = None;
22438        let decoded = decode_resume_signal(&signal)
22439            .expect("valid Avro signal")
22440            .expect("named signal resumes the workflow");
22441        assert!(decoded.arguments.is_empty());
22442    }
22443
22444    #[tokio::test]
22445    async fn malformed_task_level_codecs_become_pre_handler_failures() {
22446        let client = Client::new("http://127.0.0.1:8080").expect("client");
22447        let mut worker = Worker::new(client, "rust-workers");
22448        let handler_calls = Arc::new(AtomicUsize::new(0));
22449
22450        let calls = Arc::clone(&handler_calls);
22451        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22452            calls.fetch_add(1, Ordering::SeqCst);
22453            async move { Ok(Value::Null) }
22454        });
22455        let calls = Arc::clone(&handler_calls);
22456        worker.register_activity("codec.activity", move |_ctx, _args| {
22457            calls.fetch_add(1, Ordering::SeqCst);
22458            async move { Ok(Value::Null) }
22459        });
22460        let calls = Arc::clone(&handler_calls);
22461        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22462            calls.fetch_add(1, Ordering::SeqCst);
22463            async move { Ok(Value::Null) }
22464        });
22465
22466        let mut failures = Vec::new();
22467        for codec_case in [
22468            InvalidTaskPayloadCodec::Missing,
22469            InvalidTaskPayloadCodec::Null,
22470            InvalidTaskPayloadCodec::NonString,
22471        ] {
22472            let mut workflow = json!({
22473                "task_id": format!("workflow-{}", codec_case.label()),
22474                "workflow_type": "codec.workflow"
22475            });
22476            codec_case.apply(&mut workflow);
22477            match serde_json::from_value::<WorkflowTask>(workflow) {
22478                Ok(task) => match worker.execute_workflow_task(task) {
22479                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22480                    outcome => failures.push(format!(
22481                        "workflow {} codec returned {outcome:?}",
22482                        codec_case.label()
22483                    )),
22484                },
22485                Err(error) => failures.push(format!(
22486                    "workflow {} codec failed transport deserialization: {error}",
22487                    codec_case.label()
22488                )),
22489            }
22490
22491            let mut activity = json!({
22492                "task_id": format!("activity-{}", codec_case.label()),
22493                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
22494                "activity_type": "codec.activity",
22495                "attempt_number": 1
22496            });
22497            codec_case.apply(&mut activity);
22498            match serde_json::from_value::<ActivityTask>(activity) {
22499                Ok(task) => match worker.execute_activity_task(task).await {
22500                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22501                    outcome => failures.push(format!(
22502                        "activity {} codec returned {outcome:?}",
22503                        codec_case.label()
22504                    )),
22505                },
22506                Err(error) => failures.push(format!(
22507                    "activity {} codec failed transport deserialization: {error}",
22508                    codec_case.label()
22509                )),
22510            }
22511
22512            let mut query = json!({
22513                "query_task_id": format!("query-{}", codec_case.label()),
22514                "workflow_type": "codec.workflow",
22515                "query_name": "known"
22516            });
22517            codec_case.apply(&mut query);
22518            match serde_json::from_value::<QueryTask>(query) {
22519                Ok(task) => match worker.execute_query_task(task).await {
22520                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
22521                    outcome => failures.push(format!(
22522                        "query {} codec returned {outcome:?}",
22523                        codec_case.label()
22524                    )),
22525                },
22526                Err(error) => failures.push(format!(
22527                    "query {} codec failed transport deserialization: {error}",
22528                    codec_case.label()
22529                )),
22530            }
22531        }
22532
22533        assert!(failures.is_empty(), "{}", failures.join("\n"));
22534        assert_eq!(
22535            handler_calls.load(Ordering::SeqCst),
22536            0,
22537            "invalid task codecs must not invoke a handler"
22538        );
22539    }
22540
22541    #[tokio::test]
22542    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
22543        for codec_case in [
22544            InvalidTaskPayloadCodec::Missing,
22545            InvalidTaskPayloadCodec::Null,
22546            InvalidTaskPayloadCodec::NonString,
22547        ] {
22548            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
22549            let client = Client::builder(server.base_url())
22550                .timeout(Duration::from_secs(2))
22551                .build()
22552                .expect("client");
22553            let mut worker = Worker::new(client, "rust-workers")
22554                .worker_id("codec-worker")
22555                .poll_timeout(Duration::from_millis(10));
22556            let handler_calls = Arc::new(AtomicUsize::new(0));
22557
22558            let calls = Arc::clone(&handler_calls);
22559            worker.register_workflow("codec.workflow", move |_ctx, _args| {
22560                calls.fetch_add(1, Ordering::SeqCst);
22561                async move { Ok(Value::Null) }
22562            });
22563            let calls = Arc::clone(&handler_calls);
22564            worker.register_activity("codec.activity", move |_ctx, _args| {
22565                calls.fetch_add(1, Ordering::SeqCst);
22566                async move { Ok(Value::Null) }
22567            });
22568            let calls = Arc::clone(&handler_calls);
22569            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22570                calls.fetch_add(1, Ordering::SeqCst);
22571                async move { Ok(Value::Null) }
22572            });
22573
22574            assert_eq!(
22575                worker.run_once().await.expect("invalid tasks are settled"),
22576                3,
22577                "all {} codec tasks must be handled",
22578                codec_case.label()
22579            );
22580            assert_eq!(
22581                handler_calls.load(Ordering::SeqCst),
22582                0,
22583                "{} task codecs must fail before every handler",
22584                codec_case.label()
22585            );
22586
22587            for path in [
22588                "/api/worker/workflow-tasks/codec-workflow/fail",
22589                "/api/worker/activity-tasks/codec-activity/fail",
22590                "/api/worker/query-tasks/codec-query/fail",
22591            ] {
22592                let body = server.request_body(path);
22593                assert!(
22594                    body["failure"]["message"]
22595                        .as_str()
22596                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
22597                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
22598                    codec_case.label()
22599                );
22600            }
22601            assert_eq!(
22602                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
22603                    ["reason"],
22604                "query_payload_decode_failed"
22605            );
22606            for path in [
22607                "/api/worker/workflow-tasks/codec-workflow/complete",
22608                "/api/worker/activity-tasks/codec-activity/complete",
22609                "/api/worker/query-tasks/codec-query/complete",
22610            ] {
22611                assert_eq!(
22612                    server.request_count(path),
22613                    0,
22614                    "invalid {} codec task reached {path}",
22615                    codec_case.label()
22616                );
22617            }
22618        }
22619    }
22620
22621    #[tokio::test]
22622    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22623        let client = Client::new("http://127.0.0.1:8080").expect("client");
22624        let mut worker = Worker::new(client, "rust-workers");
22625        let handler_calls = Arc::new(AtomicUsize::new(0));
22626
22627        let calls = Arc::clone(&handler_calls);
22628        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22629            calls.fetch_add(1, Ordering::SeqCst);
22630            async move { Ok(Value::Null) }
22631        });
22632        let calls = Arc::clone(&handler_calls);
22633        worker.register_activity("codec.activity", move |_ctx, _args| {
22634            calls.fetch_add(1, Ordering::SeqCst);
22635            async move { Ok(Value::Null) }
22636        });
22637        let calls = Arc::clone(&handler_calls);
22638        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22639            calls.fetch_add(1, Ordering::SeqCst);
22640            async move { Ok(Value::Null) }
22641        });
22642        let calls = Arc::clone(&handler_calls);
22643        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22644            calls.fetch_add(1, Ordering::SeqCst);
22645            async move { Ok(Value::Null) }
22646        });
22647
22648        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22649        workflow.payload_codec = "json".to_string();
22650        workflow.arguments = None;
22651        let error = worker
22652            .execute_workflow_task(workflow)
22653            .expect_err("task codec must be checked before workflow invocation");
22654        assert!(error.to_string().contains("unsupported_payload_codec"));
22655
22656        let activity = ActivityTask {
22657            task_id: "activity-invalid-codec".to_string(),
22658            workflow_id: None,
22659            run_id: None,
22660            activity_execution_id: None,
22661            observability_context: None,
22662            dispatch_observability_context: None,
22663            observability_links: None,
22664            activity_attempt_id: None,
22665            attempt_id: None,
22666            activity_type: "codec.activity".to_string(),
22667            payload_codec: "unknown".to_string(),
22668            arguments: None,
22669            attempt_number: 1,
22670            lease_owner: None,
22671        };
22672        let error = worker
22673            .execute_activity_task(activity)
22674            .await
22675            .expect_err("task codec must be checked before activity invocation");
22676        assert!(error.to_string().contains("unsupported_payload_codec"));
22677
22678        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22679        update.workflow_update_id = Some("update-invalid-codec".to_string());
22680        update.update_name = Some("known".to_string());
22681        update.history_events.push(history_event(
22682            "UpdateAccepted",
22683            json!({
22684                "update_id": "update-invalid-codec",
22685                "update_name": "known",
22686                "arguments": {"codec": "json", "blob": null}
22687            }),
22688        ));
22689        let error = worker
22690            .execute_workflow_task(update)
22691            .expect_err("nested update codec must be checked before handler lookup");
22692        assert!(error.to_string().contains("unsupported_payload_codec"));
22693
22694        let query: QueryTask = serde_json::from_value(json!({
22695            "query_task_id": "query-invalid-codec",
22696            "workflow_type": "codec.workflow",
22697            "query_name": "known",
22698            "payload_codec": DEFAULT_CODEC,
22699            "workflow_arguments": null,
22700            "query_arguments": null,
22701            "history_export": {
22702                "payloads": {"codec": DEFAULT_CODEC},
22703                "signals": [{
22704                    "name": "empty",
22705                    "payload_codec": "json",
22706                    "arguments": null
22707                }]
22708            }
22709        }))
22710        .expect("query task");
22711        let failure = worker
22712            .execute_query_task(query)
22713            .await
22714            .expect_err("exported signal codec must be checked before query invocation");
22715        assert_eq!(failure.reason, "query_payload_decode_failed");
22716        assert!(failure.message.contains("unsupported_payload_codec"));
22717
22718        let exported_history: QueryTask = serde_json::from_value(json!({
22719            "query_task_id": "query-invalid-history-codec",
22720            "workflow_type": "codec.workflow",
22721            "query_name": "known",
22722            "payload_codec": DEFAULT_CODEC,
22723            "history_export": {
22724                "payloads": {"codec": DEFAULT_CODEC},
22725                "history_events": [{
22726                    "type": "ActivityCompleted",
22727                    "payload": {"payload_codec": "unknown", "result": null}
22728                }]
22729            }
22730        }))
22731        .expect("query task");
22732        let failure = worker
22733            .execute_query_task(exported_history)
22734            .await
22735            .expect_err("exported history codec must be checked before query invocation");
22736        assert_eq!(failure.reason, "query_payload_decode_failed");
22737        assert!(failure.message.contains("unsupported_payload_codec"));
22738        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22739
22740        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22741        unknown_workflow.arguments = None;
22742        unknown_workflow.history_events.push(history_event(
22743            "SignalReceived",
22744            json!({
22745                "signal_name": "empty",
22746                "payload_codec": "json",
22747                "arguments": null
22748            }),
22749        ));
22750        let error = worker
22751            .execute_workflow_task(unknown_workflow)
22752            .expect_err("history codec must precede unknown workflow outcome");
22753        assert!(error.to_string().contains("unsupported_payload_codec"));
22754
22755        let unknown_activity = ActivityTask {
22756            task_id: "activity-unknown".to_string(),
22757            workflow_id: None,
22758            run_id: None,
22759            activity_execution_id: None,
22760            observability_context: None,
22761            dispatch_observability_context: None,
22762            observability_links: None,
22763            activity_attempt_id: None,
22764            attempt_id: None,
22765            activity_type: "missing".to_string(),
22766            payload_codec: "json".to_string(),
22767            arguments: None,
22768            attempt_number: 1,
22769            lease_owner: None,
22770        };
22771        let error = worker
22772            .execute_activity_task(unknown_activity)
22773            .await
22774            .expect_err("codec must precede unknown activity outcome");
22775        assert!(error.to_string().contains("unsupported_payload_codec"));
22776
22777        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22778        unknown_update.payload_codec = "json".to_string();
22779        unknown_update.arguments = None;
22780        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22781        unknown_update.update_name = Some("missing".to_string());
22782        let error = worker
22783            .execute_workflow_task(unknown_update)
22784            .expect_err("codec must precede fail_update shortcut");
22785        assert!(error.to_string().contains("unsupported_payload_codec"));
22786
22787        let unknown_query: QueryTask = serde_json::from_value(json!({
22788            "query_task_id": "query-unknown",
22789            "workflow_type": "missing",
22790            "query_name": "missing",
22791            "payload_codec": "json",
22792            "workflow_arguments": null,
22793            "query_arguments": null
22794        }))
22795        .expect("query task");
22796        let failure = worker
22797            .execute_query_task(unknown_query)
22798            .await
22799            .expect_err("codec must precede unknown query outcome");
22800        assert_eq!(failure.reason, "query_payload_decode_failed");
22801        assert!(failure.message.contains("unsupported_payload_codec"));
22802    }
22803
22804    #[tokio::test]
22805    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22806        let client = Client::new("http://127.0.0.1:8080").expect("client");
22807        let worker = Worker::new(client, "rust-workers");
22808
22809        for event_type in ["SignalReceived", "SignalApplied"] {
22810            for (payload_field, codec) in [
22811                ("value", "json"),
22812                ("input", "unknown"),
22813                ("arguments", "json"),
22814            ] {
22815                let payload = json!({
22816                    "signal_name": "empty",
22817                    payload_field: {"codec": codec, "blob": null}
22818                });
22819                let workflow = workflow_task(
22820                    "missing",
22821                    vec![history_event(event_type, payload.clone())],
22822                    DEFAULT_CODEC,
22823                );
22824                let error = worker
22825                    .execute_workflow_task(workflow)
22826                    .expect_err("signal payload codec must precede unknown workflow outcome");
22827                assert!(
22828                    error.to_string().contains("unsupported_payload_codec"),
22829                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22830                );
22831
22832                let query: QueryTask = serde_json::from_value(json!({
22833                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22834                    "workflow_type": "missing",
22835                    "query_name": "missing",
22836                    "payload_codec": DEFAULT_CODEC,
22837                    "workflow_arguments": null,
22838                    "query_arguments": null,
22839                    "history_events": [{
22840                        "event_type": event_type,
22841                        "payload": payload
22842                    }]
22843                }))
22844                .expect("query task");
22845                let failure = worker
22846                    .execute_query_task(query)
22847                    .await
22848                    .expect_err("signal payload codec must precede unknown query outcome");
22849                assert_eq!(
22850                    failure.reason, "query_payload_decode_failed",
22851                    "{event_type}.{payload_field} returned an unrelated query outcome"
22852                );
22853                assert!(
22854                    failure.message.contains("unsupported_payload_codec"),
22855                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22856                    failure.message
22857                );
22858            }
22859        }
22860    }
22861
22862    #[test]
22863    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22864        let ctx = WorkflowContext {
22865            cancellation_scope_id: "root".into(),
22866            state: Arc::new(Mutex::new(
22867                WorkflowState::new_with_identity(
22868                    Vec::new(),
22869                    Some("wf-parent".to_string()),
22870                    Some("run-parent".to_string()),
22871                    "rust-workers".to_string(),
22872                    DEFAULT_CODEC.to_string(),
22873                    None,
22874                )
22875                .expect("workflow state"),
22876            )),
22877        };
22878
22879        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22880        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22881        assert!(matches!(
22882            call.as_mut().poll(&mut task_context),
22883            Poll::Pending
22884        ));
22885
22886        let commands = ctx.take_commands().expect("commands");
22887        assert_eq!(commands[0]["type"], "schedule_activity");
22888        assert_eq!(commands[0]["activity_type"], "hello.activity");
22889    }
22890
22891    #[test]
22892    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22893        let ctx = workflow_context(Vec::new());
22894        let options = ActivityOptions::new()
22895            .task_queue("payments")
22896            .retry_policy(
22897                ActivityRetryPolicy::new(4)
22898                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22899                    .non_retryable_error_type("ValidationError"),
22900            )
22901            .start_to_close_timeout(Duration::from_secs(120))
22902            .schedule_to_start_timeout(Duration::from_secs(10))
22903            .schedule_to_close_timeout(Duration::from_secs(300))
22904            .heartbeat_timeout(Duration::from_secs(15));
22905        let mut call = Box::pin(ctx.activity_with_options(
22906            "charge-card",
22907            options,
22908            json!([{"order_id": "o-1"}]),
22909        ));
22910        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22911
22912        assert!(matches!(
22913            call.as_mut().poll(&mut task_context),
22914            Poll::Pending
22915        ));
22916        assert!(matches!(
22917            call.as_mut().poll(&mut task_context),
22918            Poll::Pending
22919        ));
22920
22921        let commands = ctx.take_commands().expect("activity command");
22922        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22923        assert_eq!(commands[0]["queue"], "payments");
22924        assert_eq!(
22925            commands[0]["retry_policy"],
22926            json!({
22927                "max_attempts": 4,
22928                "backoff_seconds": [1, 3, 9],
22929                "non_retryable_error_types": ["ValidationError"],
22930            })
22931        );
22932        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22933        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22934        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22935        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22936    }
22937
22938    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22939        vec![
22940            history_event(
22941                "ActivityScheduled",
22942                json!({"sequence":1,"activity_type":"render",
22943                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22944            ),
22945            history_event(
22946                "ActivityCompleted",
22947                json!({"sequence":1,"activity_type":"render",
22948                "payload_codec":DEFAULT_CODEC,
22949                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
22950            ),
22951        ]
22952    }
22953
22954    #[test]
22955    fn worker_session_activity_routes_to_session_queue_once() {
22956        let ctx = workflow_context(Vec::new());
22957        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22958        let mut call = Box::pin(
22959            ctx.activity("render", json!([]))
22960                .in_worker_session(session.clone()),
22961        );
22962        let mut cx = TaskContext::from_waker(noop_waker_ref());
22963        assert!(call.as_mut().poll(&mut cx).is_pending());
22964        assert!(call.as_mut().poll(&mut cx).is_pending());
22965        let commands = ctx.take_commands().unwrap();
22966        assert_eq!(commands.len(), 1);
22967        assert_eq!(commands[0]["queue"], "gpu-workers");
22968        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
22969    }
22970
22971    #[tokio::test]
22972    async fn worker_session_cold_replay_uses_recorded_avro_result() {
22973        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22974        for _replacement in 0..2 {
22975            let ctx = workflow_context(completed_worker_session_history(&session));
22976            let result: i64 = ctx
22977                .activity("render", json!([]))
22978                .in_worker_session(session.clone())
22979                .typed()
22980                .await
22981                .unwrap();
22982            assert_eq!(result, 42);
22983            assert!(ctx.take_commands().unwrap().is_empty());
22984        }
22985    }
22986
22987    #[test]
22988    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
22989        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22990        for changed in [
22991            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
22992            Some(original.clone().ttl_seconds(60)),
22993            Some(original.clone().requirements(["gpu:l4"])),
22994            None,
22995        ] {
22996            let ctx = workflow_context(completed_worker_session_history(&original));
22997            let mut call = ctx.activity_with_options(
22998                "render",
22999                ActivityOptions::new().task_queue("gpu-workers"),
23000                json!([]),
23001            );
23002            if let Some(changed) = changed {
23003                call = call.in_worker_session(changed);
23004            }
23005            let mut call = Box::pin(call);
23006            let mut cx = TaskContext::from_waker(noop_waker_ref());
23007            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23008                call.as_mut().poll(&mut cx)
23009            else {
23010                panic!("changed session must fail replay");
23011            };
23012            assert_eq!(failure.reason, "activity_worker_session_mismatch");
23013            assert!(ctx.take_commands().unwrap().is_empty());
23014        }
23015    }
23016
23017    #[test]
23018    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
23019        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23020        let ctx = workflow_context(Vec::new());
23021        let mut local = Box::pin(
23022            ctx.local_activity("render", json!([]))
23023                .in_worker_session(session.clone()),
23024        );
23025        let mut cx = TaskContext::from_waker(noop_waker_ref());
23026        assert!(matches!(
23027            local.as_mut().poll(&mut cx),
23028            Poll::Ready(Err(Error::WorkerLoop(_)))
23029        ));
23030        assert!(ctx.take_commands().unwrap().is_empty());
23031        let mut remote = Box::pin(
23032            ctx.activity_with_options(
23033                "render",
23034                ActivityOptions::new().task_queue("other"),
23035                json!([]),
23036            )
23037            .in_worker_session(session),
23038        );
23039        assert!(matches!(
23040            remote.as_mut().poll(&mut cx),
23041            Poll::Ready(Err(Error::WorkerLoop(_)))
23042        ));
23043        assert!(ctx.take_commands().unwrap().is_empty());
23044    }
23045
23046    #[test]
23047    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
23048        let ctx = workflow_context(Vec::new());
23049        let options = ActivityOptions::new().retry_policy(
23050            ActivityRetryPolicy::new(3)
23051                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
23052        );
23053        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23054        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23055
23056        assert!(matches!(
23057            call.as_mut().poll(&mut task_context),
23058            Poll::Pending
23059        ));
23060        assert_eq!(
23061            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
23062            json!([1, 2])
23063        );
23064    }
23065
23066    #[test]
23067    fn activity_options_preserve_unused_explicit_backoff_entries() {
23068        for max_attempts in [1, 2, 10] {
23069            let ctx = workflow_context(Vec::new());
23070            let options =
23071                ActivityOptions::new()
23072                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
23073                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
23074                    ));
23075            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23076            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23077            assert!(matches!(
23078                call.as_mut().poll(&mut task_context),
23079                Poll::Pending
23080            ));
23081            let commands = ctx.take_commands().expect("command");
23082            assert_eq!(commands.len(), 1);
23083            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
23084            assert_eq!(
23085                commands[0]["retry_policy"]["backoff_seconds"],
23086                json!([1, 2, 5, 10, 15, 30, 60, 120])
23087            );
23088        }
23089        let default_options = ActivityOptions::new().validate().expect("default options");
23090        let default_policy = current_activity_retry_snapshot(&default_options);
23091        assert_eq!(
23092            default_policy.max_attempts,
23093            RecordedSnapshotValue::Known(Some(1))
23094        );
23095        assert_eq!(
23096            default_policy.backoff_seconds,
23097            RecordedSnapshotValue::Known(Vec::new())
23098        );
23099    }
23100
23101    #[test]
23102    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
23103        let fixture: Value = serde_json::from_str(include_str!(
23104            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
23105        ))
23106        .expect("published PHP fixture");
23107        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
23108            .expect("unchanged published history");
23109        let matching = ActivityOptions::new().task_queue("default").retry_policy(
23110            ActivityRetryPolicy::new(1)
23111                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
23112        );
23113        let mut changed_tail = matching.clone();
23114        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23115            [1, 2, 5, 10, 15, 30, 60, 121]
23116                .map(Duration::from_secs)
23117                .to_vec(),
23118        ));
23119        let mut changed_first = matching.clone();
23120        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23121            [2, 2, 5, 10, 15, 30, 60, 120]
23122                .map(Duration::from_secs)
23123                .to_vec(),
23124        ));
23125        let mut changed_attempts = matching.clone();
23126        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
23127        let mut changed_types = matching.clone();
23128        changed_types
23129            .retry_policy
23130            .as_mut()
23131            .unwrap()
23132            .non_retryable_error_types = vec!["ChangedError".into()];
23133        let mut changed_start = matching.clone();
23134        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
23135        let mut changed_schedule_start = matching.clone();
23136        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
23137        let mut changed_schedule_close = matching.clone();
23138        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
23139        let mut changed_heartbeat = matching;
23140        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
23141        let unchanged_defaults = ActivityOptions::new().task_queue("default");
23142        for options in [
23143            changed_tail,
23144            changed_first,
23145            changed_attempts,
23146            changed_types,
23147            changed_start,
23148            changed_schedule_start,
23149            changed_schedule_close,
23150            changed_heartbeat,
23151            unchanged_defaults,
23152        ] {
23153            let ctx = workflow_context(history.clone());
23154            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
23155            assert!(!ctx.patched("frozen-zero").unwrap());
23156            ctx.deprecate_patch("frozen-zero").unwrap();
23157            let mut call =
23158                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
23159            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23160            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23161                call.as_mut().poll(&mut task_context)
23162            else {
23163                panic!("changed explicit policy must fail replay")
23164            };
23165            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
23166            assert_eq!(failure.sequence, Some(2));
23167            assert!(ctx.take_commands().unwrap().is_empty());
23168        }
23169    }
23170
23171    #[test]
23172    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
23173        let cases = [
23174            (
23175                ActivityOptions::new().task_queue("  "),
23176                ActivityOptionsErrorKind::EmptyTaskQueue,
23177            ),
23178            (
23179                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
23180                ActivityOptionsErrorKind::EmptyRetryPolicy,
23181            ),
23182            (
23183                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
23184                ActivityOptionsErrorKind::InvalidMaxAttempts,
23185            ),
23186            (
23187                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
23188                    max_attempts: None,
23189                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
23190                    non_retryable_error_types: Vec::new(),
23191                }),
23192                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
23193            ),
23194            (
23195                ActivityOptions::new().retry_policy(
23196                    ActivityRetryPolicy::new(2).exponential_backoff(
23197                        Duration::from_secs(1),
23198                        0,
23199                        None,
23200                    ),
23201                ),
23202                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
23203            ),
23204            (
23205                ActivityOptions::new()
23206                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
23207                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
23208            ),
23209            (
23210                ActivityOptions::new().retry_policy(
23211                    ActivityRetryPolicy::new(10_002).exponential_backoff(
23212                        Duration::from_secs(1),
23213                        1,
23214                        None,
23215                    ),
23216                ),
23217                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
23218            ),
23219            (
23220                ActivityOptions::new().retry_policy(
23221                    ActivityRetryPolicy::new(2)
23222                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
23223                ),
23224                ActivityOptionsErrorKind::BackoffOverflow,
23225            ),
23226        ];
23227
23228        for (options, expected_kind) in cases {
23229            let ctx = workflow_context(Vec::new());
23230            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23231            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23232            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
23233                call.as_mut().poll(&mut task_context)
23234            else {
23235                panic!("expected typed activity validation error");
23236            };
23237            assert_eq!(error.kind, expected_kind);
23238            assert!(ctx.take_commands().expect("commands").is_empty());
23239        }
23240    }
23241
23242    #[test]
23243    fn activity_options_validate_positive_and_ordered_timeouts() {
23244        let zero_timeout_cases = [
23245            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
23246            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
23247            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
23248            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
23249        ];
23250        for options in zero_timeout_cases {
23251            assert_eq!(
23252                options.validate().expect_err("zero timeout").kind,
23253                ActivityOptionsErrorKind::TimeoutNotPositive
23254            );
23255        }
23256
23257        let ordering_cases = [
23258            ActivityOptions::new()
23259                .heartbeat_timeout(Duration::from_secs(11))
23260                .start_to_close_timeout(Duration::from_secs(10)),
23261            ActivityOptions::new()
23262                .start_to_close_timeout(Duration::from_secs(31))
23263                .schedule_to_close_timeout(Duration::from_secs(30)),
23264            ActivityOptions::new()
23265                .schedule_to_start_timeout(Duration::from_secs(31))
23266                .schedule_to_close_timeout(Duration::from_secs(30)),
23267        ];
23268        for options in ordering_cases {
23269            assert_eq!(
23270                options.validate().expect_err("timeout order").kind,
23271                ActivityOptionsErrorKind::TimeoutOrder
23272            );
23273        }
23274
23275        assert_eq!(
23276            ActivityOptions::new()
23277                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
23278                .validate()
23279                .expect_err("protocol integer overflow")
23280                .kind,
23281            ActivityOptionsErrorKind::TimeoutOverflow
23282        );
23283    }
23284
23285    #[test]
23286    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
23287        let ctx = workflow_context(completed_retry_activity_history());
23288        let mut call =
23289            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23290        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23291
23292        assert!(matches!(
23293            call.as_mut().poll(&mut task_context),
23294            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23295        ));
23296        assert!(ctx.take_commands().expect("commands").is_empty());
23297        ctx.ensure_history_consumed().expect("history consumed");
23298    }
23299
23300    #[test]
23301    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
23302        let mut options = retry_activity_options();
23303        options
23304            .retry_policy
23305            .as_mut()
23306            .expect("retry policy")
23307            .non_retryable_error_types
23308            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
23309
23310        let new_ctx = workflow_context(Vec::new());
23311        let mut new_call =
23312            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
23313        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23314        assert!(matches!(
23315            new_call.as_mut().poll(&mut task_context),
23316            Poll::Pending
23317        ));
23318        let commands = new_ctx.take_commands().expect("commands");
23319        assert_eq!(commands.len(), 1);
23320        assert_eq!(
23321            commands[0]["retry_policy"]["non_retryable_error_types"],
23322            json!(["PermanentError"])
23323        );
23324
23325        let replay_ctx = workflow_context(completed_retry_activity_history());
23326        let mut replay_call =
23327            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
23328        assert!(matches!(
23329            replay_call.as_mut().poll(&mut task_context),
23330            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23331        ));
23332        assert!(replay_ctx.take_commands().expect("commands").is_empty());
23333        replay_ctx
23334            .ensure_history_consumed()
23335            .expect("history consumed");
23336    }
23337
23338    #[test]
23339    fn replayed_intermediate_retry_remains_pending_across_restarts() {
23340        let history = completed_retry_activity_history()
23341            .into_iter()
23342            .take(3)
23343            .collect::<Vec<_>>();
23344
23345        for _restart in 0..2 {
23346            let ctx = workflow_context(history.clone());
23347            let mut call =
23348                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23349            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23350            assert!(matches!(
23351                call.as_mut().poll(&mut task_context),
23352                Poll::Pending
23353            ));
23354            assert!(ctx.take_commands().expect("commands").is_empty());
23355        }
23356    }
23357
23358    #[test]
23359    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
23360        let mut changed_queue = retry_activity_options();
23361        changed_queue.task_queue = Some("different-queue".to_string());
23362
23363        let mut changed_max_attempts = retry_activity_options();
23364        let retry_policy = changed_max_attempts
23365            .retry_policy
23366            .as_mut()
23367            .expect("retry policy");
23368        retry_policy.max_attempts = Some(4);
23369
23370        let mut changed_backoff = retry_activity_options();
23371        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
23372        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
23373            Duration::from_secs(3),
23374            Duration::from_secs(4),
23375        ]));
23376
23377        let mut changed_non_retryable_types = retry_activity_options();
23378        let retry_policy = changed_non_retryable_types
23379            .retry_policy
23380            .as_mut()
23381            .expect("retry policy");
23382        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
23383
23384        let mut changed_start_to_close = retry_activity_options();
23385        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
23386        let mut changed_schedule_to_start = retry_activity_options();
23387        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
23388        let mut changed_schedule_to_close = retry_activity_options();
23389        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
23390        let mut changed_heartbeat = retry_activity_options();
23391        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
23392
23393        let cases = [
23394            (changed_queue, "activity_task_queue_mismatch"),
23395            (changed_max_attempts, "activity_retry_policy_mismatch"),
23396            (changed_backoff, "activity_retry_policy_mismatch"),
23397            (
23398                changed_non_retryable_types,
23399                "activity_retry_policy_mismatch",
23400            ),
23401            (changed_start_to_close, "activity_retry_policy_mismatch"),
23402            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
23403            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
23404            (changed_heartbeat, "activity_retry_policy_mismatch"),
23405        ];
23406
23407        for (options, expected_reason) in cases {
23408            let ctx = workflow_context(completed_retry_activity_history());
23409            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
23410            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23411            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23412                call.as_mut().poll(&mut task_context)
23413            else {
23414                panic!("changed activity options must fail replay");
23415            };
23416            assert_eq!(failure.reason, expected_reason);
23417            assert_eq!(failure.sequence, Some(1));
23418            assert!(ctx.take_commands().expect("commands").is_empty());
23419        }
23420    }
23421
23422    #[test]
23423    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
23424        let cases = [
23425            (
23426                "execution_mode",
23427                json!("local"),
23428                "activity_execution_mode_mismatch",
23429            ),
23430            (
23431                "snapshot_version",
23432                json!(2),
23433                "activity_retry_policy_mismatch",
23434            ),
23435        ];
23436
23437        for (field, value, expected_reason) in cases {
23438            let mut history = completed_retry_activity_history();
23439            let activity = history[0].payload["activity"]
23440                .as_object_mut()
23441                .expect("activity snapshot");
23442            if field == "execution_mode" {
23443                activity.insert(field.to_string(), value);
23444            } else {
23445                activity["retry_policy"]
23446                    .as_object_mut()
23447                    .expect("retry snapshot")
23448                    .insert(field.to_string(), value);
23449            }
23450
23451            let ctx = workflow_context(history);
23452            let mut call =
23453                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23454            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23455            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23456                call.as_mut().poll(&mut task_context)
23457            else {
23458                panic!("changed {field} must fail replay");
23459            };
23460            assert_eq!(failure.reason, expected_reason);
23461            assert_eq!(failure.sequence, Some(1));
23462            assert!(ctx.take_commands().expect("commands").is_empty());
23463        }
23464    }
23465
23466    #[test]
23467    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
23468        for (nested, field, value, terminal_only) in [
23469            (false, "execution_mode", json!("local"), false),
23470            (false, "local_activity", json!(true), false),
23471            (true, "local_activity", json!(true), false),
23472            (false, "local_activity", json!(true), true),
23473        ] {
23474            let mut history = completed_retry_activity_history();
23475            history[0]
23476                .payload
23477                .as_object_mut()
23478                .unwrap()
23479                .remove("activity");
23480            let event = if terminal_only {
23481                history.last_mut().unwrap()
23482            } else {
23483                &mut history[0]
23484            };
23485            if nested {
23486                event.payload["activity"] = json!({(field): value});
23487            } else {
23488                event.payload[field] = value;
23489            }
23490            let ctx = workflow_context(history);
23491            let mut call =
23492                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23493            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23494            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23495                call.as_mut().poll(&mut task_context)
23496            else {
23497                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
23498            };
23499            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
23500            assert_eq!(failure.sequence, Some(1));
23501            assert!(ctx.take_commands().expect("commands").is_empty());
23502        }
23503    }
23504
23505    #[test]
23506    fn activity_history_rejects_conflicting_local_execution_markers() {
23507        let mut history = completed_retry_activity_history();
23508        history.last_mut().unwrap().payload["local_activity"] = json!(true);
23509        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
23510            .expect_err("remote schedule cannot become a local completion");
23511        assert!(
23512            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
23513            if reason == "activity_execution_mode_conflict")
23514        );
23515    }
23516
23517    #[test]
23518    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
23519        let mut history = completed_retry_activity_history();
23520        let activity = history[0].payload["activity"]
23521            .as_object_mut()
23522            .expect("activity snapshot");
23523        activity.remove("execution_mode");
23524        activity.remove("retry_policy");
23525
23526        let mut current = retry_activity_options();
23527        current.start_to_close_timeout = Some(Duration::from_secs(45));
23528        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
23529        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
23530        current.heartbeat_timeout = Some(Duration::from_secs(12));
23531
23532        let ctx = workflow_context(history);
23533        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
23534        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23535        assert!(matches!(
23536            call.as_mut().poll(&mut task_context),
23537            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23538        ));
23539        assert!(ctx.take_commands().expect("commands").is_empty());
23540        ctx.ensure_history_consumed().expect("history consumed");
23541    }
23542
23543    #[test]
23544    fn terminal_activity_failed_after_start_returns_typed_failure() {
23545        let history = vec![
23546            history_event(
23547                "ActivityScheduled",
23548                json!({
23549                    "sequence": 1,
23550                    "activity_type": "flaky",
23551                    "activity_execution_id": "act-terminal",
23552                    "activity": {
23553                        "id": "act-terminal",
23554                        "sequence": 1,
23555                        "type": "flaky",
23556                        "queue": "critical-activities",
23557                        "retry_policy": {
23558                            "snapshot_version": 1,
23559                            "max_attempts": 3,
23560                            "backoff_seconds": [2, 4],
23561                            "non_retryable_error_types": ["PermanentError"]
23562                        }
23563                    }
23564                }),
23565            ),
23566            history_event(
23567                "ActivityStarted",
23568                json!({
23569                    "sequence": 1,
23570                    "activity_type": "flaky",
23571                    "activity_execution_id": "act-terminal",
23572                    "activity_attempt_id": "attempt-1",
23573                    "attempt_number": 1
23574                }),
23575            ),
23576            history_event(
23577                "ActivityFailed",
23578                json!({
23579                    "sequence": 1,
23580                    "activity_type": "flaky",
23581                    "activity_execution_id": "act-terminal",
23582                    "activity_attempt_id": "attempt-1",
23583                    "attempt_number": 1,
23584                    "failure_id": "failure-terminal",
23585                    "failure_category": "activity",
23586                    "exception_type": "PermanentError",
23587                    "message": "cannot retry",
23588                    "non_retryable": true
23589                }),
23590            ),
23591        ];
23592        let ctx = workflow_context(history);
23593        let mut call =
23594            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23595        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23596
23597        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23598            call.as_mut().poll(&mut task_context)
23599        else {
23600            panic!("terminal ActivityFailed must settle the activity future");
23601        };
23602        assert_eq!(failure.kind, ActivityFailureKind::Failed);
23603        assert_eq!(
23604            failure.activity_execution_id.as_deref(),
23605            Some("act-terminal")
23606        );
23607        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
23608        assert!(failure.non_retryable);
23609        assert!(ctx.take_commands().expect("commands").is_empty());
23610        ctx.ensure_history_consumed().expect("history consumed");
23611    }
23612
23613    #[test]
23614    fn activity_terminal_events_return_machine_readable_failures() {
23615        let cases = [
23616            (
23617                "ActivityFailed",
23618                json!({
23619                    "sequence": 1,
23620                    "activity_type": "charge-card",
23621                    "activity_execution_id": "act-1",
23622                    "activity_attempt_id": "attempt-2",
23623                    "attempt_number": 2,
23624                    "failure_id": "failure-1",
23625                    "failure_category": "activity",
23626                    "exception_type": "PaymentDeclined",
23627                    "exception_class": "payments.PaymentDeclined",
23628                    "message": "card declined",
23629                    "non_retryable": true
23630                }),
23631                ActivityFailureKind::Failed,
23632                "activity",
23633            ),
23634            (
23635                "ActivityCancelled",
23636                json!({
23637                    "sequence": 1,
23638                    "activity_type": "charge-card",
23639                    "activity_execution_id": "act-1",
23640                    "activity_attempt_id": "attempt-1"
23641                }),
23642                ActivityFailureKind::Cancelled,
23643                "cancelled",
23644            ),
23645        ];
23646
23647        for (event_type, payload, expected_kind, expected_reason) in cases {
23648            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23649            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23650            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23651            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23652                call.as_mut().poll(&mut task_context)
23653            else {
23654                panic!("expected terminal activity failure");
23655            };
23656            assert_eq!(failure.kind, expected_kind);
23657            assert_eq!(failure.reason, expected_reason);
23658            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23659            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23660        }
23661    }
23662
23663    #[test]
23664    fn every_activity_timeout_class_is_typed() {
23665        for timeout_kind in [
23666            "start_to_close",
23667            "schedule_to_start",
23668            "schedule_to_close",
23669            "heartbeat",
23670        ] {
23671            let ctx = workflow_context(vec![history_event(
23672                "ActivityTimedOut",
23673                json!({
23674                    "sequence": 1,
23675                    "activity_type": "slow",
23676                    "activity_execution_id": "act-timeout",
23677                    "activity_attempt_id": "attempt-timeout",
23678                    "failure_category": "timeout",
23679                    "timeout_kind": timeout_kind,
23680                    "message": "deadline expired"
23681                }),
23682            )]);
23683            let mut call = Box::pin(ctx.activity("slow", json!([])));
23684            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23685            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23686                call.as_mut().poll(&mut task_context)
23687            else {
23688                panic!("expected timeout failure");
23689            };
23690            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23691            assert_eq!(failure.reason, timeout_kind);
23692            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23693            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23694        }
23695    }
23696
23697    #[test]
23698    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23699        let ctx = workflow_context(Vec::new());
23700        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23701        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23702
23703        assert!(matches!(
23704            sleep.as_mut().poll(&mut task_context),
23705            Poll::Pending
23706        ));
23707        assert!(matches!(
23708            sleep.as_mut().poll(&mut task_context),
23709            Poll::Pending
23710        ));
23711
23712        let commands = ctx.take_commands().expect("timer command");
23713        assert_eq!(
23714            commands,
23715            vec![json!({
23716                "type": "start_timer",
23717                "delay_seconds": 2,
23718            })]
23719        );
23720    }
23721
23722    #[test]
23723    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23724        let history = vec![
23725            history_event(
23726                "TimerScheduled",
23727                json!({
23728                    "sequence": 1,
23729                    "timer_id": "timer-1",
23730                    "delay_seconds": 5,
23731                    "fire_at": "2026-07-11T12:00:05Z",
23732                }),
23733            ),
23734            history_event(
23735                "TimerFired",
23736                json!({
23737                    "sequence": 1,
23738                    "timer_id": "timer-1",
23739                    "delay_seconds": 5,
23740                    "fire_at": "2026-07-11T12:00:05Z",
23741                    "fired_at": "2026-07-11T12:00:05Z",
23742                }),
23743            ),
23744        ];
23745
23746        for _restart in 0..2 {
23747            let ctx = workflow_context(history.clone());
23748            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23749            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23750            assert!(matches!(
23751                sleep.as_mut().poll(&mut task_context),
23752                Poll::Ready(Ok(()))
23753            ));
23754            assert!(ctx.take_commands().expect("commands").is_empty());
23755            ctx.ensure_history_consumed().expect("history consumed");
23756        }
23757    }
23758
23759    #[test]
23760    fn workflow_sleep_rejects_changed_delay_during_replay() {
23761        let ctx = workflow_context(vec![
23762            history_event(
23763                "TimerScheduled",
23764                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23765            ),
23766            history_event(
23767                "TimerFired",
23768                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23769            ),
23770        ]);
23771        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23772        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23773
23774        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23775            sleep.as_mut().poll(&mut task_context)
23776        else {
23777            panic!("changed timer delay must be rejected");
23778        };
23779        assert_eq!(failure.reason, "timer_delay_mismatch");
23780        assert_eq!(failure.sequence, Some(1));
23781    }
23782
23783    #[test]
23784    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23785        let ctx = workflow_context(Vec::new());
23786        let mut wait = Box::pin(
23787            ctx.wait_condition(
23788                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23789                    .timeout(Duration::from_millis(60_001)),
23790                || Ok(false),
23791            ),
23792        );
23793        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23794
23795        assert!(matches!(
23796            wait.as_mut().poll(&mut task_context),
23797            Poll::Pending
23798        ));
23799        assert!(matches!(
23800            wait.as_mut().poll(&mut task_context),
23801            Poll::Pending
23802        ));
23803        assert_eq!(
23804            ctx.take_commands().expect("condition command"),
23805            vec![json!({
23806                "type": "open_condition_wait",
23807                "condition_wait_occurrence_id": "rust:condition-wait:0",
23808                "condition_key": "approval.ready",
23809                "condition_definition_fingerprint": "sha256:approval-v1",
23810                "timeout_seconds": 61,
23811            })]
23812        );
23813    }
23814
23815    #[test]
23816    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23817        let ctx = workflow_context(Vec::new());
23818        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23819        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23820        assert!(matches!(
23821            satisfied.as_mut().poll(&mut task_context),
23822            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23823        ));
23824
23825        let mut timed_out = Box::pin(wait_condition!(
23826            ctx,
23827            "no-wait",
23828            timeout: Duration::ZERO,
23829            || Ok(false),
23830        ));
23831        assert!(matches!(
23832            timed_out.as_mut().poll(&mut task_context),
23833            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23834        ));
23835        assert!(ctx.take_commands().expect("commands").is_empty());
23836    }
23837
23838    #[test]
23839    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23840        let signal_history = vec![
23841            history_event(
23842                "ConditionWaitOpened",
23843                json!({
23844                    "sequence": 4,
23845                    "condition_wait_id": "condition:4",
23846                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23847                    "condition_key": "approval",
23848                    "condition_definition_fingerprint": "sha256:approval-v1",
23849                    "timeout_seconds": 30,
23850                }),
23851            ),
23852            history_event(
23853                "SignalReceived",
23854                json!({
23855                    "workflow_sequence": 4,
23856                    "signal_name": "approve",
23857                    "arguments": fixture_envelope(json!(["Ada"])),
23858                }),
23859            ),
23860        ];
23861        for _worker_before_or_after_restart in 0..2 {
23862            let ctx = workflow_context(signal_history.clone());
23863            let predicate_ctx = ctx.clone();
23864            let mut wait = Box::pin(
23865                ctx.wait_condition(
23866                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23867                        .timeout(Duration::from_secs(30)),
23868                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23869                ),
23870            );
23871            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23872            assert!(matches!(
23873                wait.as_mut().poll(&mut task_context),
23874                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23875            ));
23876            assert!(ctx.take_commands().expect("commands").is_empty());
23877            ctx.ensure_history_consumed().expect("condition consumed");
23878        }
23879
23880        let update_history = vec![
23881            history_event(
23882                "ConditionWaitOpened",
23883                json!({
23884                    "sequence": 7,
23885                    "condition_wait_id": "condition:7",
23886                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23887                    "condition_key": "update-approval",
23888                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23889                }),
23890            ),
23891            history_event(
23892                "UpdateApplied",
23893                json!({
23894                    "sequence": 7,
23895                    "update_id": "update-1",
23896                    "update_name": "approve",
23897                    "arguments": fixture_envelope(json!([true])),
23898                }),
23899            ),
23900        ];
23901        let ctx = workflow_context(update_history);
23902        let predicate_ctx = ctx.clone();
23903        let mut wait = Box::pin(ctx.wait_condition(
23904            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23905            move || {
23906                Ok(predicate_ctx
23907                    .updates("approve")?
23908                    .first()
23909                    .and_then(|arguments| arguments.first())
23910                    .and_then(Value::as_bool)
23911                    == Some(true))
23912            },
23913        ));
23914        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23915        assert!(matches!(
23916            wait.as_mut().poll(&mut task_context),
23917            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23918        ));
23919        assert!(ctx.take_commands().expect("commands").is_empty());
23920        ctx.ensure_history_consumed().expect("condition consumed");
23921    }
23922
23923    #[test]
23924    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23925        let open_history = vec![
23926            history_event(
23927                "ConditionWaitOpened",
23928                json!({
23929                    "sequence": 3,
23930                    "condition_wait_id": "condition:3",
23931                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23932                    "condition_key": "two-votes",
23933                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23934                    "timeout_seconds": 120,
23935                }),
23936            ),
23937            history_event(
23938                "SignalReceived",
23939                json!({
23940                    "workflow_sequence": 3,
23941                    "signal_name": "vote",
23942                    "arguments": fixture_envelope(json!(["first"])),
23943                }),
23944            ),
23945        ];
23946        for _worker_before_or_after_restart in 0..2 {
23947            let ctx = workflow_context(open_history.clone());
23948            let predicate_ctx = ctx.clone();
23949            let mut wait = Box::pin(
23950                ctx.wait_condition(
23951                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23952                        .timeout(Duration::from_secs(120)),
23953                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23954                ),
23955            );
23956            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23957            assert!(matches!(
23958                wait.as_mut().poll(&mut task_context),
23959                Poll::Pending
23960            ));
23961            assert_eq!(
23962                ctx.take_commands().expect("reopened condition"),
23963                vec![json!({
23964                    "type": "open_condition_wait",
23965                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23966                    "condition_key": "two-votes",
23967                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23968                    "timeout_seconds": 120,
23969                })]
23970            );
23971        }
23972
23973        let satisfied_ctx = workflow_context(vec![
23974            history_event(
23975                "ConditionWaitOpened",
23976                json!({
23977                    "sequence": 5,
23978                    "condition_wait_id": "condition:5",
23979                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23980                    "condition_key": "approval",
23981                    "condition_definition_fingerprint": "sha256:approval-v1",
23982                }),
23983            ),
23984            history_event(
23985                "ConditionWaitSatisfied",
23986                json!({
23987                    "sequence": 5,
23988                    "condition_wait_id": "condition:5",
23989                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23990                    "condition_key": "approval",
23991                    "condition_definition_fingerprint": "sha256:approval-v1",
23992                }),
23993            ),
23994        ]);
23995        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
23996            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
23997            || Ok(false),
23998        ));
23999        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24000        assert!(matches!(
24001            satisfied.as_mut().poll(&mut task_context),
24002            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24003        ));
24004
24005        let timed_out_ctx = workflow_context(vec![
24006            history_event(
24007                "ConditionWaitOpened",
24008                json!({
24009                    "sequence": 8,
24010                    "condition_wait_id": "condition:8",
24011                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24012                    "condition_key": "approval-timeout",
24013                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
24014                    "timeout_seconds": 5,
24015                }),
24016            ),
24017            history_event(
24018                "TimerScheduled",
24019                json!({
24020                    "sequence": 9,
24021                    "timer_id": "condition-timer:9",
24022                    "timer_kind": "condition_timeout",
24023                    "condition_wait_id": "condition:8",
24024                    "delay_seconds": 5,
24025                }),
24026            ),
24027            history_event(
24028                "TimerFired",
24029                json!({
24030                    "sequence": 9,
24031                    "timer_id": "condition-timer:9",
24032                    "timer_kind": "condition_timeout",
24033                    "condition_wait_id": "condition:8",
24034                    "delay_seconds": 5,
24035                }),
24036            ),
24037        ]);
24038        let mut timed_out = Box::pin(
24039            timed_out_ctx.wait_condition(
24040                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
24041                    .timeout(Duration::from_secs(5)),
24042                || Ok(true),
24043            ),
24044        );
24045        assert!(matches!(
24046            timed_out.as_mut().poll(&mut task_context),
24047            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24048        ));
24049    }
24050
24051    #[test]
24052    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
24053        let ctx = workflow_context(reopened_selection_condition_history());
24054        {
24055            let state = ctx.state.lock().unwrap();
24056            assert!(matches!(
24057                selection_member_recorded_command(&state, 2),
24058                Some(RecordedCommand::ConditionWait {
24059                    sequence: 3,
24060                    result: None,
24061                    ..
24062                })
24063            ));
24064        }
24065        let mut selected = Box::pin(ctx.select_keyed(vec![
24066            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24067            (
24068                "votes",
24069                ParallelOperation::condition(
24070                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24071                    || Ok(true),
24072                ),
24073            ),
24074        ]));
24075        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24076        assert!(selected.as_mut().poll(&mut task_context).is_pending());
24077        assert!(
24078            ctx.take_commands().unwrap().is_empty(),
24079            "true predicate must not reopen the recorded wait"
24080        );
24081        ctx.ensure_history_consumed()
24082            .expect("physical reopens are consumed while canonical selection is pending");
24083    }
24084
24085    #[test]
24086    fn reopened_selection_condition_replays_its_latest_physical_winner() {
24087        for (terminal_type, acknowledge_timeout) in [
24088            ("ConditionWaitSatisfied", false),
24089            ("ConditionWaitTimedOut", false),
24090            ("TimerFired", false),
24091            ("TimerFired", true),
24092        ] {
24093            let mut history = reopened_selection_condition_history();
24094            let original_identity = history[1].payload["condition_wait_id"].clone();
24095            let uses_timer = terminal_type == "TimerFired";
24096            let mut resolution_payload = history[3].payload.clone();
24097            if uses_timer {
24098                for event in &mut history[1..] {
24099                    event.payload["timeout_seconds"] = json!(3);
24100                }
24101                resolution_payload = history[3].payload.clone();
24102                resolution_payload["timer_kind"] = json!("condition_timeout");
24103                resolution_payload["timer_id"] = json!("condition-timeout-3");
24104                resolution_payload["delay_seconds"] = json!(3);
24105                history.push(history_event("TimerScheduled", resolution_payload.clone()));
24106            }
24107            let mut resolution = history_event(terminal_type, resolution_payload.clone());
24108            resolution
24109                .raw
24110                .insert("id".into(), json!("latest-condition-resolution"));
24111            history.push(resolution);
24112            history.push(history_event(
24113                "SelectionResolved",
24114                json!({
24115                    "selection_group_id": "select-calls:1:2",
24116                    "selection_group_base_sequence": 1,
24117                    "selection_group_size": 2,
24118                    "member_key": "votes",
24119                    "member_index": 1,
24120                    "member_base_sequence": 2,
24121                    "member_size": 1,
24122                    "operation_kind": "condition",
24123                    "operation_identity": original_identity,
24124                    "outcome": "completed",
24125                    "resolution_event_id": "latest-condition-resolution",
24126                    "resolution_event_type": terminal_type,
24127                }),
24128            ));
24129            if acknowledge_timeout {
24130                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
24131            }
24132            let ctx = workflow_context(history);
24133            let mut selected = Box::pin(ctx.select_keyed(vec![
24134                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24135                (
24136                    "votes",
24137                    ParallelOperation::condition(
24138                        if uses_timer {
24139                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24140                                .timeout(Duration::from_secs(3))
24141                        } else {
24142                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24143                        },
24144                        || Ok(true),
24145                    ),
24146                ),
24147            ]));
24148            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24149            match selected.as_mut().poll(&mut task_context) {
24150                Poll::Ready(Ok(result)) => {
24151                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
24152                    let expected = if terminal_type == "ConditionWaitSatisfied" {
24153                        ConditionWaitResult::Satisfied
24154                    } else {
24155                        ConditionWaitResult::TimedOut
24156                    };
24157                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
24158                }
24159                other => panic!("latest physical winner must replay: {other:?}"),
24160            }
24161            assert!(ctx.take_commands().unwrap().is_empty());
24162            ctx.ensure_history_consumed()
24163                .expect("winner history consumed");
24164        }
24165    }
24166
24167    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
24168        let fixture: Value = serde_json::from_str(include_str!(
24169            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24170        ))
24171        .expect("grouped condition fixture");
24172        fixture["history"]
24173            .as_array()
24174            .unwrap()
24175            .iter()
24176            .map(|event| {
24177                let mut payload = event["payload"].clone();
24178                let index = payload["parallel_group_index"].as_u64().unwrap();
24179                payload["parallel_group_id"] = json!("select-calls:1:2");
24180                payload["parallel_group_mode"] = json!("select");
24181                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
24182                payload["selection_member_index"] = json!(index);
24183                payload["selection_member_base_sequence"] = json!(index + 1);
24184                payload["selection_member_size"] = json!(1);
24185                payload["selection_member_kind"] =
24186                    json!(if index == 0 { "timer" } else { "condition" });
24187                history_event(event["event_type"].as_str().unwrap(), payload)
24188            })
24189            .collect()
24190    }
24191
24192    #[test]
24193    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
24194        let fixture: Value = serde_json::from_str(include_str!(
24195            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24196        ))
24197        .expect("grouped condition fixture");
24198        let original = fixture["history"].as_array().expect("fixture history");
24199        let decode = |events: &[Value]| {
24200            let history = events
24201                .iter()
24202                .map(|event| {
24203                    history_event(
24204                        event["event_type"].as_str().unwrap(),
24205                        event["payload"].clone(),
24206                    )
24207                })
24208                .collect::<Vec<_>>();
24209            recorded_commands(
24210                &history,
24211                DEFAULT_CODEC,
24212                WorkflowIdentity {
24213                    workflow_id: None,
24214                    run_id: None,
24215                },
24216            )
24217        };
24218        assert!(decode(original).is_ok());
24219        for field in [
24220            "condition_wait_occurrence_id",
24221            "condition_key",
24222            "condition_definition_fingerprint",
24223            "timeout_seconds",
24224            "parallel_group_id",
24225            "parallel_group_size",
24226            "parallel_group_index",
24227        ] {
24228            let mut changed = original.clone();
24229            changed[3]["payload"][field] = match field {
24230                "timeout_seconds" | "parallel_group_size" => json!(30),
24231                "parallel_group_index" => json!(0),
24232                _ => json!("changed"),
24233            };
24234            assert!(
24235                decode(&changed).is_err(),
24236                "reopen must reject changed {field}"
24237            );
24238        }
24239        let mut unsettled = original.clone();
24240        unsettled.remove(2);
24241        assert!(
24242            decode(&unsettled).is_err(),
24243            "physical predecessor must be resolved"
24244        );
24245        let mut timed_out = original.clone();
24246        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
24247        assert!(decode(&timed_out).is_err(), "timeout is terminal");
24248        let mut late_resolution = original.clone();
24249        late_resolution.swap(2, 3);
24250        assert!(
24251            decode(&late_resolution).is_err(),
24252            "later history cannot authorize a reopen"
24253        );
24254    }
24255
24256    #[test]
24257    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
24258        let history = vec![
24259            history_event(
24260                "ConditionWaitOpened",
24261                json!({
24262                    "sequence": 3,
24263                    "condition_wait_id": "condition:3",
24264                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24265                    "condition_key": "two-votes",
24266                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24267                }),
24268            ),
24269            history_event(
24270                "SignalReceived",
24271                json!({
24272                    "workflow_sequence": 3,
24273                    "signal_name": "vote",
24274                    "arguments": fixture_envelope(json!(["first"])),
24275                }),
24276            ),
24277            history_event(
24278                "ConditionWaitSatisfied",
24279                json!({
24280                    "sequence": 3,
24281                    "condition_wait_id": "condition:3",
24282                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24283                    "condition_key": "two-votes",
24284                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24285                }),
24286            ),
24287            history_event(
24288                "ConditionWaitOpened",
24289                json!({
24290                    "sequence": 5,
24291                    "condition_wait_id": "condition:5",
24292                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24293                    "condition_key": "two-votes",
24294                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24295                }),
24296            ),
24297            history_event(
24298                "SignalReceived",
24299                json!({
24300                    "workflow_sequence": 5,
24301                    "signal_name": "vote",
24302                    "arguments": fixture_envelope(json!(["second"])),
24303                }),
24304            ),
24305            history_event(
24306                "ConditionWaitSatisfied",
24307                json!({
24308                    "sequence": 5,
24309                    "condition_wait_id": "condition:5",
24310                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24311                    "condition_key": "two-votes",
24312                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24313                }),
24314            ),
24315        ];
24316        for _cold_worker_or_restart in 0..2 {
24317            let ctx = workflow_context(history.clone());
24318            let predicate_ctx = ctx.clone();
24319            let mut wait = Box::pin(ctx.wait_condition(
24320                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24321                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24322            ));
24323            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24324
24325            assert!(matches!(
24326                wait.as_mut().poll(&mut task_context),
24327                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24328            ));
24329            assert!(ctx.take_commands().expect("commands").is_empty());
24330            ctx.ensure_history_consumed()
24331                .expect("every physical wait-open is consumed");
24332        }
24333    }
24334
24335    #[test]
24336    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
24337        let history = vec![
24338            history_event(
24339                "ConditionWaitOpened",
24340                json!({
24341                    "sequence": 3,
24342                    "condition_wait_id": "condition:3",
24343                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24344                    "condition_key": "approved",
24345                    "condition_definition_fingerprint": "sha256:approved-v1",
24346                }),
24347            ),
24348            history_event(
24349                "UpdateApplied",
24350                json!({
24351                    "sequence": 3,
24352                    "update_id": "update-1",
24353                    "update_name": "approve",
24354                    "arguments": fixture_envelope(json!([false])),
24355                }),
24356            ),
24357            history_event(
24358                "ConditionWaitOpened",
24359                json!({
24360                    "sequence": 5,
24361                    "condition_wait_id": "condition:5",
24362                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24363                    "condition_key": "approved",
24364                    "condition_definition_fingerprint": "sha256:approved-v1",
24365                }),
24366            ),
24367            history_event(
24368                "UpdateApplied",
24369                json!({
24370                    "sequence": 5,
24371                    "update_id": "update-2",
24372                    "update_name": "approve",
24373                    "arguments": fixture_envelope(json!([true])),
24374                }),
24375            ),
24376        ];
24377
24378        for _cold_worker_or_restart in 0..2 {
24379            let ctx = workflow_context(history.clone());
24380            let predicate_ctx = ctx.clone();
24381            let mut wait = Box::pin(ctx.wait_condition(
24382                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
24383                move || {
24384                    Ok(predicate_ctx
24385                        .updates("approve")?
24386                        .last()
24387                        .and_then(|arguments| arguments.first())
24388                        .and_then(Value::as_bool)
24389                        == Some(true))
24390                },
24391            ));
24392            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24393
24394            assert!(matches!(
24395                wait.as_mut().poll(&mut task_context),
24396                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24397            ));
24398            assert!(ctx.take_commands().expect("commands").is_empty());
24399            ctx.ensure_history_consumed()
24400                .expect("every update-driven reopen is consumed");
24401        }
24402    }
24403
24404    #[test]
24405    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
24406        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
24407            ("shared", "sha256:first", "shared", "sha256:second"),
24408            ("first", "sha256:shared", "second", "sha256:shared"),
24409            ("shared", "sha256:shared", "shared", "sha256:shared"),
24410            ("first", "sha256:first", "second", "sha256:second"),
24411        ] {
24412            let history = vec![
24413                history_event(
24414                    "ConditionWaitOpened",
24415                    json!({
24416                        "sequence": 3,
24417                        "condition_wait_id": "condition:3",
24418                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24419                        "condition_key": first_key,
24420                        "condition_definition_fingerprint": first_fingerprint,
24421                    }),
24422                ),
24423                history_event(
24424                    "ConditionWaitSatisfied",
24425                    json!({
24426                        "sequence": 3,
24427                        "condition_wait_id": "condition:3",
24428                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24429                        "condition_key": first_key,
24430                        "condition_definition_fingerprint": first_fingerprint,
24431                    }),
24432                ),
24433                history_event(
24434                    "ConditionWaitOpened",
24435                    json!({
24436                        "sequence": 4,
24437                        "condition_wait_id": "condition:4",
24438                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24439                        "condition_key": second_key,
24440                        "condition_definition_fingerprint": second_fingerprint,
24441                    }),
24442                ),
24443                history_event(
24444                    "ConditionWaitSatisfied",
24445                    json!({
24446                        "sequence": 4,
24447                        "condition_wait_id": "condition:4",
24448                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24449                        "condition_key": second_key,
24450                        "condition_definition_fingerprint": second_fingerprint,
24451                    }),
24452                ),
24453            ];
24454            for _cold_worker_or_restart in 0..2 {
24455                let ctx = workflow_context(history.clone());
24456                let mut task_context = TaskContext::from_waker(noop_waker_ref());
24457                let mut first = Box::pin(ctx.wait_condition(
24458                    ConditionWaitOptions::new(first_key, first_fingerprint),
24459                    || Ok(false),
24460                ));
24461                assert!(matches!(
24462                    first.as_mut().poll(&mut task_context),
24463                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24464                ));
24465
24466                let mut second = Box::pin(ctx.wait_condition(
24467                    ConditionWaitOptions::new(second_key, second_fingerprint),
24468                    || Ok(false),
24469                ));
24470                assert!(matches!(
24471                    second.as_mut().poll(&mut task_context),
24472                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24473                ));
24474                assert!(ctx.take_commands().expect("commands").is_empty());
24475                ctx.ensure_history_consumed()
24476                    .expect("each authored wait consumes one occurrence");
24477            }
24478        }
24479    }
24480
24481    #[test]
24482    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
24483        fn worker() -> Worker {
24484            let client = Client::new("http://127.0.0.1:8080").expect("client");
24485            let mut worker = Worker::new(client, "rust-workers");
24486            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
24487                let mut outcomes = Vec::new();
24488                for _ in 0..2 {
24489                    outcomes.push(
24490                        ctx.wait_condition(
24491                            ConditionWaitOptions::new("shared", "sha256:shared"),
24492                            || Ok(false),
24493                        )
24494                        .await?,
24495                    );
24496                }
24497                Ok(json!(outcomes))
24498            });
24499            worker
24500        }
24501
24502        let task = workflow_task(
24503            "rust.condition-loop",
24504            vec![
24505                history_event(
24506                    "ConditionWaitOpened",
24507                    json!({
24508                        "sequence": 1,
24509                        "condition_wait_id": "condition:1",
24510                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24511                        "condition_key": "shared",
24512                        "condition_definition_fingerprint": "sha256:shared",
24513                    }),
24514                ),
24515                history_event(
24516                    "ConditionWaitSatisfied",
24517                    json!({
24518                        "sequence": 1,
24519                        "condition_wait_id": "condition:1",
24520                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24521                        "condition_key": "shared",
24522                        "condition_definition_fingerprint": "sha256:shared",
24523                    }),
24524                ),
24525                history_event(
24526                    "ConditionWaitOpened",
24527                    json!({
24528                        "sequence": 2,
24529                        "condition_wait_id": "condition:2",
24530                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24531                        "condition_key": "shared",
24532                        "condition_definition_fingerprint": "sha256:shared",
24533                    }),
24534                ),
24535                history_event(
24536                    "ConditionWaitSatisfied",
24537                    json!({
24538                        "sequence": 2,
24539                        "condition_wait_id": "condition:2",
24540                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24541                        "condition_key": "shared",
24542                        "condition_definition_fingerprint": "sha256:shared",
24543                    }),
24544                ),
24545            ],
24546            DEFAULT_CODEC,
24547        );
24548
24549        for _cold_worker_or_restart in 0..2 {
24550            let commands = worker()
24551                .execute_workflow_task(task.clone())
24552                .expect("adjacent loop waits replay deterministically");
24553            assert_eq!(commands.len(), 1);
24554            assert_eq!(commands[0]["type"], "complete_workflow");
24555            assert_eq!(
24556                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24557                json!(["satisfied", "satisfied"])
24558            );
24559        }
24560    }
24561
24562    #[test]
24563    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
24564        let history = vec![history_event(
24565            "ConditionWaitOpened",
24566            json!({
24567                "sequence": 12,
24568                "condition_wait_id": "condition:12",
24569                "condition_wait_occurrence_id": "rust:condition-wait:0",
24570                "condition_key": "approval",
24571                "condition_definition_fingerprint": "sha256:approval-v1",
24572                "timeout_seconds": 30,
24573            }),
24574        )];
24575        for (options, expected_reason) in [
24576            (
24577                ConditionWaitOptions::new("changed", "sha256:approval-v1")
24578                    .timeout(Duration::from_secs(30)),
24579                "condition_wait_key_mismatch",
24580            ),
24581            (
24582                ConditionWaitOptions::new("approval", "sha256:approval-v2")
24583                    .timeout(Duration::from_secs(30)),
24584                "condition_wait_predicate_mismatch",
24585            ),
24586            (
24587                ConditionWaitOptions::new("approval", "sha256:approval-v1")
24588                    .timeout(Duration::from_secs(29)),
24589                "condition_wait_timeout_mismatch",
24590            ),
24591        ] {
24592            let ctx = workflow_context(history.clone());
24593            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
24594            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24595            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24596                wait.as_mut().poll(&mut task_context)
24597            else {
24598                panic!("changed condition definition must fail replay");
24599            };
24600            assert_eq!(failure.reason, expected_reason);
24601            assert_eq!(failure.sequence, Some(12));
24602        }
24603    }
24604
24605    #[test]
24606    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
24607        let error = WorkflowState::new(
24608            vec![history_event(
24609                "ConditionWaitOpened",
24610                json!({
24611                    "sequence": 12,
24612                    "condition_wait_id": "condition:12",
24613                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24614                    "condition_key": "approval",
24615                }),
24616            )],
24617            "rust-workers".to_string(),
24618            DEFAULT_CODEC.to_string(),
24619            None,
24620        )
24621        .expect_err("condition history without a predicate fingerprint must fail");
24622
24623        assert!(matches!(
24624            error,
24625            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24626                if reason == "condition_wait_predicate_fingerprint_missing"
24627        ));
24628    }
24629
24630    #[test]
24631    fn condition_wait_history_requires_authored_occurrence_identity() {
24632        let error = WorkflowState::new(
24633            vec![history_event(
24634                "ConditionWaitOpened",
24635                json!({
24636                    "sequence": 12,
24637                    "condition_wait_id": "condition:12",
24638                    "condition_key": "approval",
24639                    "condition_definition_fingerprint": "sha256:approval-v1",
24640                }),
24641            )],
24642            "rust-workers".to_string(),
24643            DEFAULT_CODEC.to_string(),
24644            None,
24645        )
24646        .expect_err("condition history without occurrence identity must fail");
24647
24648        assert!(matches!(
24649            error,
24650            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24651                if reason == "condition_wait_occurrence_id_missing"
24652        ));
24653    }
24654
24655    #[test]
24656    fn typed_search_attribute_updates_validate_emit_and_replay() {
24657        let update = SearchAttributeUpdate::new()
24658            .keyword("OrderStatus", " waiting ")
24659            .expect("keyword")
24660            .int("Attempt", 3)
24661            .expect("int")
24662            .bool("Escalated", false)
24663            .expect("bool")
24664            .keyword_list("Regions", ["us-east", "eu-west"])
24665            .expect("list")
24666            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24667            .expect("datetime")
24668            .delete("LegacyStatus")
24669            .expect("delete");
24670        let ctx = workflow_context(Vec::new());
24671        ctx.upsert_search_attributes(update.clone())
24672            .expect("typed update");
24673        assert_eq!(
24674            ctx.take_commands().expect("search-attribute command"),
24675            vec![json!({
24676                "type": "upsert_search_attributes",
24677                "attributes": {
24678                    "Attempt": 3,
24679                    "Escalated": false,
24680                    "LegacyStatus": null,
24681                    "OrderStatus": "waiting",
24682                    "Regions": ["us-east", "eu-west"],
24683                    "UpdatedAt": "2026-08-22T04:00:00Z",
24684                },
24685                "attribute_types": {
24686                    "Attempt": "int",
24687                    "Escalated": "bool",
24688                    "OrderStatus": "keyword",
24689                    "Regions": "keyword_list",
24690                    "UpdatedAt": "datetime",
24691                },
24692            })]
24693        );
24694
24695        let replay = workflow_context(vec![history_event(
24696            "SearchAttributesUpserted",
24697            json!({
24698                "sequence": 6,
24699                "attributes": {
24700                    "Attempt": 3,
24701                    "Escalated": false,
24702                    "LegacyStatus": null,
24703                    "OrderStatus": "waiting",
24704                    "Regions": ["us-east", "eu-west"],
24705                    "UpdatedAt": "2026-08-22T04:00:00Z",
24706                },
24707                "attribute_types": {
24708                    "Attempt": "int",
24709                    "Escalated": "bool",
24710                    "OrderStatus": "keyword",
24711                    "Regions": "keyword_list",
24712                    "UpdatedAt": "datetime",
24713                },
24714                "merged": {},
24715            }),
24716        )]);
24717        replay
24718            .upsert_search_attributes(update)
24719            .expect("matching update replays");
24720        assert!(replay.take_commands().expect("commands").is_empty());
24721        replay.ensure_history_consumed().expect("history consumed");
24722
24723        let type_drift = workflow_context(vec![history_event(
24724            "SearchAttributesUpserted",
24725            json!({
24726                "sequence": 7,
24727                "attributes": {"OrderStatus": "waiting"},
24728                "attribute_types": {"OrderStatus": "keyword"},
24729                "merged": {"OrderStatus": "waiting"},
24730            }),
24731        )]);
24732        let error = type_drift
24733            .upsert_search_attributes(
24734                SearchAttributeUpdate::new()
24735                    .string("OrderStatus", "waiting")
24736                    .expect("string update"),
24737            )
24738            .expect_err("same JSON value with a changed type must fail replay");
24739        assert!(matches!(
24740            error,
24741            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24742                if reason == "search_attribute_type_mismatch"
24743        ));
24744
24745        let malformed_types = WorkflowState::new(
24746            vec![history_event(
24747                "SearchAttributesUpserted",
24748                json!({
24749                    "sequence": 8,
24750                    "attributes": {"OrderStatus": "waiting"},
24751                    "attribute_types": {"OrderStatus": "unsupported"},
24752                    "merged": {"OrderStatus": "waiting"},
24753                }),
24754            )],
24755            "rust-workers".to_string(),
24756            DEFAULT_CODEC.to_string(),
24757            None,
24758        )
24759        .expect_err("unsupported search-attribute type metadata must fail");
24760        assert!(matches!(
24761            malformed_types,
24762            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24763                if reason == "search_attribute_types_malformed"
24764        ));
24765
24766        assert!(matches!(
24767            SearchAttributeUpdate::new().keyword("bad key", "value"),
24768            Err(SearchAttributeUpdateError::InvalidKey(_))
24769        ));
24770        assert!(matches!(
24771            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24772            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24773        ));
24774        assert!(matches!(
24775            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24776            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24777        ));
24778        assert!(matches!(
24779            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24780            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24781        ));
24782        assert!(matches!(
24783            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24784            Err(Error::InvalidSearchAttributeUpdate(
24785                SearchAttributeUpdateError::Empty
24786            ))
24787        ));
24788    }
24789
24790    #[test]
24791    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24792        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24793        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24794
24795        assert!(SearchAttributeUpdate::new()
24796            .string("AsciiDescription", ascii)
24797            .is_ok());
24798        assert!(SearchAttributeUpdate::new()
24799            .string("Utf8Description", utf8)
24800            .is_ok());
24801        assert!(matches!(
24802            SearchAttributeUpdate::new().string(
24803                "TooLongDescription",
24804                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24805            ),
24806            Err(SearchAttributeUpdateError::ValueTooLong {
24807                kind: "string",
24808                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24809                ..
24810            })
24811        ));
24812    }
24813
24814    #[test]
24815    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24816        let lone_fire = WorkflowState::new(
24817            vec![history_event(
24818                "TimerFired",
24819                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24820            )],
24821            "rust-workers".to_string(),
24822            DEFAULT_CODEC.to_string(),
24823            None,
24824        )
24825        .expect_err("TimerFired requires TimerScheduled");
24826        assert!(matches!(
24827            lone_fire,
24828            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24829                if reason == "timer_schedule_missing_or_duplicate"
24830        ));
24831
24832        let wrong_identity = WorkflowState::new(
24833            vec![
24834                history_event(
24835                    "TimerScheduled",
24836                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24837                ),
24838                history_event(
24839                    "TimerFired",
24840                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24841                ),
24842            ],
24843            "rust-workers".to_string(),
24844            DEFAULT_CODEC.to_string(),
24845            None,
24846        )
24847        .expect_err("fire must match scheduled timer identity");
24848        assert!(matches!(
24849            wrong_identity,
24850            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24851                if reason == "timer_identity_mismatch"
24852        ));
24853
24854        let duplicate_fire = WorkflowState::new(
24855            vec![
24856                history_event(
24857                    "TimerScheduled",
24858                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24859                ),
24860                history_event(
24861                    "TimerFired",
24862                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24863                ),
24864                history_event(
24865                    "TimerFired",
24866                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24867                ),
24868            ],
24869            "rust-workers".to_string(),
24870            DEFAULT_CODEC.to_string(),
24871            None,
24872        )
24873        .expect_err("a durable timer cannot fire twice");
24874        assert!(matches!(
24875            duplicate_fire,
24876            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24877                if reason == "duplicate_timer_fire"
24878        ));
24879
24880        let wrong_fired_delay = WorkflowState::new(
24881            vec![
24882                history_event(
24883                    "TimerScheduled",
24884                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24885                ),
24886                history_event(
24887                    "TimerFired",
24888                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24889                ),
24890            ],
24891            "rust-workers".to_string(),
24892            DEFAULT_CODEC.to_string(),
24893            None,
24894        )
24895        .expect_err("timer schedule and fire delays must agree");
24896        assert!(matches!(
24897            wrong_fired_delay,
24898            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24899                if reason == "timer_history_delay_mismatch"
24900        ));
24901    }
24902
24903    #[test]
24904    fn replay_rejects_activity_moved_before_recorded_timer() {
24905        let ctx = workflow_context(vec![
24906            history_event(
24907                "TimerScheduled",
24908                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24909            ),
24910            history_event(
24911                "TimerFired",
24912                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24913            ),
24914            history_event(
24915                "ActivityCompleted",
24916                json!({
24917                    "sequence": 2,
24918                    "activity_type": "after-timer",
24919                    "payload_codec": DEFAULT_CODEC,
24920                    "result": fixture_envelope(json!("done")),
24921                }),
24922            ),
24923        ]);
24924        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24925        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24926
24927        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24928            activity.as_mut().poll(&mut task_context)
24929        else {
24930            panic!("reordered durable command must be rejected");
24931        };
24932        assert_eq!(failure.reason, "recorded_command_mismatch");
24933        assert_eq!(failure.sequence, Some(1));
24934        assert_eq!(failure.expected.as_deref(), Some("timer"));
24935        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24936    }
24937
24938    #[test]
24939    fn workflow_context_emits_a_typed_named_signal_wait() {
24940        let ctx = workflow_context(Vec::new());
24941        let mut signal = Box::pin(ctx.wait_signal("finish"));
24942        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24943
24944        assert!(matches!(
24945            signal.as_mut().poll(&mut task_context),
24946            Poll::Pending
24947        ));
24948        assert_eq!(
24949            ctx.take_commands().expect("signal-wait command"),
24950            vec![json!({
24951                "type": "open_signal_wait",
24952                "signal_name": "finish",
24953            })]
24954        );
24955    }
24956
24957    #[test]
24958    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
24959        let ctx = workflow_context(Vec::new());
24960        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
24961        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24962
24963        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
24964        else {
24965            panic!("runtime-reserved signal should be rejected");
24966        };
24967        assert!(message.contains("reserved by the workflow runtime"));
24968        assert!(ctx.take_commands().expect("commands").is_empty());
24969    }
24970
24971    #[tokio::test]
24972    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
24973        let client = Client::builder("http://127.0.0.1:9")
24974            .build()
24975            .expect("client");
24976        let error = client
24977            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
24978            .await
24979            .expect_err("runtime-reserved signal should be rejected before transport");
24980
24981        assert!(
24982            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
24983        );
24984    }
24985
24986    #[test]
24987    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
24988        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24989            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24990                value.to_string(),
24991            )]))
24992            .expect("message payload");
24993            json!({
24994                "schema": MESSAGE_STREAM_SCHEMA,
24995                "stream_name": "orders",
24996                "message_id": message_id,
24997                "position": position,
24998                "payload_envelope": payload,
24999            })
25000        }
25001
25002        fn opened(sequence: u64) -> HistoryEvent {
25003            history_event(
25004                "SignalWaitOpened",
25005                json!({
25006                    "sequence": sequence,
25007                    "signal_name": MESSAGE_STREAM_SIGNAL,
25008                }),
25009            )
25010        }
25011
25012        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25013            history_event(
25014                "SignalApplied",
25015                json!({
25016                    "sequence": sequence,
25017                    "signal_name": MESSAGE_STREAM_SIGNAL,
25018                    "value": fixture_envelope(json!([delivery])),
25019                }),
25020            )
25021        }
25022
25023        fn received(delivery: Value) -> HistoryEvent {
25024            history_event(
25025                "SignalReceived",
25026                json!({
25027                    "signal_name": MESSAGE_STREAM_SIGNAL,
25028                    "arguments": fixture_envelope(json!([delivery])),
25029                    "payload_codec": DEFAULT_CODEC,
25030                }),
25031            )
25032        }
25033
25034        let client = Client::new("http://127.0.0.1:8080").expect("client");
25035        let mut worker = Worker::new(client, "rust-workers");
25036        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
25037            let messages = ctx.message_stream("orders")?.receive(2).await?;
25038            Ok(json!(messages
25039                .into_iter()
25040                .map(|message| message.message_id)
25041                .collect::<Vec<_>>()))
25042        });
25043
25044        let first = delivery("message-1", 1, "one");
25045        let second = delivery("message-2", 2, "two");
25046        let batch = worker
25047            .execute_workflow_task_decision(workflow_task(
25048                "rust.message-stream-batch",
25049                vec![
25050                    opened(1),
25051                    received(first.clone()),
25052                    applied(1, first.clone()),
25053                    received(first.clone()),
25054                    received(second),
25055                ],
25056                DEFAULT_CODEC,
25057            ))
25058            .expect("worker task consumes the available batch");
25059
25060        assert_eq!(batch.commands.len(), 1);
25061        assert_eq!(batch.commands[0]["type"], "complete_workflow");
25062        assert_eq!(
25063            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
25064                .expect("workflow result"),
25065            json!(["message-1", "message-2"])
25066        );
25067        assert_eq!(
25068            batch.message_stream_cursors,
25069            vec![json!({"stream_name": "orders", "through_position": 2})]
25070        );
25071        assert!(batch.message_stream_waits.is_empty());
25072
25073        let partial = worker
25074            .execute_workflow_task_decision(workflow_task(
25075                "rust.message-stream-batch",
25076                vec![opened(1), received(first.clone()), applied(1, first)],
25077                DEFAULT_CODEC,
25078            ))
25079            .expect("worker task returns without waiting for a missing second item");
25080        assert_eq!(partial.commands.len(), 1);
25081        assert_eq!(partial.commands[0]["type"], "complete_workflow");
25082        assert_eq!(
25083            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
25084                .expect("workflow result"),
25085            json!(["message-1"])
25086        );
25087        assert_eq!(
25088            partial.message_stream_cursors,
25089            vec![json!({"stream_name": "orders", "through_position": 1})]
25090        );
25091        assert!(partial.message_stream_waits.is_empty());
25092    }
25093
25094    #[test]
25095    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
25096        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25097            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25098                value.to_string(),
25099            )]))
25100            .expect("message payload");
25101            json!({
25102                "schema": MESSAGE_STREAM_SCHEMA,
25103                "stream_name": "orders",
25104                "message_id": message_id,
25105                "position": position,
25106                "payload_envelope": payload,
25107            })
25108        }
25109
25110        fn opened(sequence: u64) -> HistoryEvent {
25111            history_event(
25112                "SignalWaitOpened",
25113                json!({
25114                    "sequence": sequence,
25115                    "signal_name": MESSAGE_STREAM_SIGNAL,
25116                }),
25117            )
25118        }
25119
25120        fn received(delivery: Value) -> HistoryEvent {
25121            history_event(
25122                "SignalReceived",
25123                json!({
25124                    "signal_name": MESSAGE_STREAM_SIGNAL,
25125                    "arguments": fixture_envelope(json!([delivery])),
25126                    "payload_codec": DEFAULT_CODEC,
25127                }),
25128            )
25129        }
25130
25131        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25132            history_event(
25133                "SignalApplied",
25134                json!({
25135                    "sequence": sequence,
25136                    "signal_name": MESSAGE_STREAM_SIGNAL,
25137                    "value": fixture_envelope(json!([delivery])),
25138                }),
25139            )
25140        }
25141
25142        let client = Client::new("http://127.0.0.1:8080").expect("client");
25143        let mut worker = Worker::new(client, "rust-workers");
25144        worker.register_workflow(
25145            "rust.message-stream-partial-batches",
25146            |ctx, _input| async move {
25147                let stream = ctx.message_stream("orders")?;
25148                let first = stream.receive(10).await?;
25149                let second = stream.receive(10).await?;
25150                Ok(json!([
25151                    first
25152                        .into_iter()
25153                        .map(|message| message.message_id)
25154                        .collect::<Vec<_>>(),
25155                    second
25156                        .into_iter()
25157                        .map(|message| message.message_id)
25158                        .collect::<Vec<_>>(),
25159                ]))
25160            },
25161        );
25162
25163        let first = delivery("message-1", 1, "one");
25164        let second = delivery("message-2", 2, "two");
25165        let decision = worker
25166            .execute_workflow_task_decision(workflow_task(
25167                "rust.message-stream-partial-batches",
25168                vec![
25169                    opened(1),
25170                    received(first.clone()),
25171                    applied(1, first),
25172                    opened(2),
25173                    received(second.clone()),
25174                    applied(2, second),
25175                ],
25176                DEFAULT_CODEC,
25177            ))
25178            .expect("cold replay preserves both authored receive boundaries");
25179
25180        assert_eq!(decision.commands.len(), 1);
25181        assert_eq!(decision.commands[0]["type"], "complete_workflow");
25182        assert_eq!(
25183            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
25184                .expect("workflow result"),
25185            json!([["message-1"], ["message-2"]])
25186        );
25187        assert_eq!(
25188            decision.message_stream_cursors,
25189            vec![json!({"stream_name": "orders", "through_position": 2})]
25190        );
25191        assert!(decision.message_stream_waits.is_empty());
25192    }
25193
25194    #[test]
25195    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
25196        let ctx = workflow_context(Vec::new());
25197        let stream = ctx.message_stream("orders").expect("message stream");
25198        let mut receive = Box::pin(stream.receive(10));
25199        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25200
25201        assert!(matches!(
25202            receive.as_mut().poll(&mut task_context),
25203            Poll::Pending
25204        ));
25205        assert_eq!(
25206            ctx.take_commands().expect("message-stream wait command"),
25207            vec![json!({
25208                "type": "open_signal_wait",
25209                "signal_name": MESSAGE_STREAM_SIGNAL,
25210            })]
25211        );
25212        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25213        assert!(cursors.is_empty());
25214        assert_eq!(
25215            waits,
25216            vec![json!({"stream_name": "orders", "after_position": 0})]
25217        );
25218    }
25219
25220    #[test]
25221    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
25222        let ctx = workflow_context(vec![history_event(
25223            "SignalReceived",
25224            json!({
25225                "signal_name": MESSAGE_STREAM_SIGNAL,
25226                "arguments": fixture_envelope(json!([{
25227                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
25228                    "stream_name": "orders",
25229                    "through_position": 2,
25230                }])),
25231                "payload_codec": DEFAULT_CODEC,
25232            }),
25233        )]);
25234        let stream = ctx.message_stream("orders").expect("message stream");
25235        let mut receive = Box::pin(stream.receive(10));
25236        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25237
25238        assert!(matches!(
25239            receive.as_mut().poll(&mut task_context),
25240            Poll::Pending
25241        ));
25242        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25243        assert_eq!(
25244            cursors,
25245            vec![json!({"stream_name": "orders", "through_position": 2})]
25246        );
25247        assert_eq!(
25248            waits,
25249            vec![json!({"stream_name": "orders", "after_position": 2})]
25250        );
25251    }
25252
25253    #[test]
25254    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
25255        let mut empty_map = BTreeMap::new();
25256        let mut nested = BTreeMap::new();
25257        nested.insert(
25258            "value".to_string(),
25259            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
25260        );
25261        let values = vec![
25262            AvroValue::Bytes(vec![0, 255]),
25263            AvroValue::Long(1),
25264            AvroValue::Double(1.0),
25265            AvroValue::Array(Vec::new()),
25266            AvroValue::Map(std::mem::take(&mut empty_map)),
25267            AvroValue::Map(nested),
25268        ];
25269        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
25270        let transport = vec![json!({
25271            "schema": MESSAGE_STREAM_SCHEMA,
25272            "stream_name": "orders",
25273            "message_id": "message-1",
25274            "position": 1,
25275            "payload_envelope": payload,
25276        })];
25277
25278        for _ in 0..2 {
25279            let Some(MessageStreamDelivery::Message(message)) =
25280                decode_message_stream_delivery(transport.clone()).expect("delivery")
25281            else {
25282                panic!("message delivery expected");
25283            };
25284            assert_eq!(message.arguments, values);
25285            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
25286            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
25287        }
25288    }
25289
25290    #[test]
25291    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
25292        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25293            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25294                value.to_string(),
25295            )]))
25296            .expect("message payload");
25297            json!({
25298                "schema": MESSAGE_STREAM_SCHEMA,
25299                "stream_name": "orders",
25300                "message_id": message_id,
25301                "position": position,
25302                "payload_envelope": payload,
25303            })
25304        }
25305
25306        fn opened(sequence: u64) -> HistoryEvent {
25307            history_event(
25308                "SignalWaitOpened",
25309                json!({
25310                    "sequence": sequence,
25311                    "signal_name": MESSAGE_STREAM_SIGNAL,
25312                }),
25313            )
25314        }
25315
25316        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25317            history_event(
25318                "SignalApplied",
25319                json!({
25320                    "sequence": sequence,
25321                    "signal_name": MESSAGE_STREAM_SIGNAL,
25322                    "value": fixture_envelope(json!([delivery])),
25323                }),
25324            )
25325        }
25326
25327        fn worker() -> Worker {
25328            let client = Client::new("http://127.0.0.1:8080").expect("client");
25329            let mut worker = Worker::new(client, "rust-workers");
25330            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
25331                let stream = ctx.message_stream("orders")?;
25332                let first = stream.receive_one().await?;
25333                let second = stream.receive_one().await?;
25334                Ok(json!([first.message_id, second.message_id]))
25335            });
25336            worker
25337        }
25338
25339        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
25340            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
25341            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
25342            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
25343            task
25344        }
25345
25346        let waiting = worker()
25347            .execute_workflow_task_decision(workflow_task(
25348                "rust.message-stream",
25349                Vec::new(),
25350                DEFAULT_CODEC,
25351            ))
25352            .expect("first worker opens the stream wait");
25353        assert_eq!(
25354            waiting.commands,
25355            vec![json!({
25356                "type": "open_signal_wait",
25357                "signal_name": MESSAGE_STREAM_SIGNAL,
25358            })]
25359        );
25360        assert!(waiting.message_stream_cursors.is_empty());
25361        assert_eq!(
25362            waiting.message_stream_waits,
25363            vec![json!({"stream_name": "orders", "after_position": 0})]
25364        );
25365
25366        let first_delivery = delivery("message-1", 1, "one");
25367        let first_arrival = worker()
25368            .execute_workflow_task_decision(task_with_resume(
25369                vec![opened(1)],
25370                first_delivery.clone(),
25371            ))
25372            .expect("replacement worker consumes the first arrival");
25373        assert_eq!(
25374            first_arrival.commands,
25375            vec![json!({
25376                "type": "open_signal_wait",
25377                "signal_name": MESSAGE_STREAM_SIGNAL,
25378            })]
25379        );
25380        assert_eq!(
25381            first_arrival.message_stream_cursors,
25382            vec![json!({"stream_name": "orders", "through_position": 1})]
25383        );
25384        assert_eq!(
25385            first_arrival.message_stream_waits,
25386            vec![json!({"stream_name": "orders", "after_position": 1})]
25387        );
25388
25389        let second_delivery = delivery("message-2", 2, "two");
25390        let first_applied = applied(1, first_delivery);
25391        let completed = worker()
25392            .execute_workflow_task_decision(task_with_resume(
25393                vec![opened(1), first_applied.clone(), opened(2)],
25394                second_delivery.clone(),
25395            ))
25396            .expect("next replacement worker consumes the second arrival");
25397        assert_eq!(completed.commands.len(), 1);
25398        assert_eq!(completed.commands[0]["type"], "complete_workflow");
25399        assert_eq!(
25400            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
25401                .expect("workflow result"),
25402            json!(["message-1", "message-2"])
25403        );
25404        assert_eq!(
25405            completed.message_stream_cursors,
25406            vec![json!({"stream_name": "orders", "through_position": 2})]
25407        );
25408        assert!(completed.message_stream_waits.is_empty());
25409
25410        let replay_history = vec![
25411            opened(1),
25412            first_applied,
25413            opened(2),
25414            applied(2, second_delivery),
25415        ];
25416        for _cold_worker_or_restart in 0..2 {
25417            let replayed = worker()
25418                .execute_workflow_task_decision(workflow_task(
25419                    "rust.message-stream",
25420                    replay_history.clone(),
25421                    DEFAULT_CODEC,
25422                ))
25423                .expect("cold worker replays each logical message exactly once");
25424            assert_eq!(replayed.commands.len(), 1);
25425            assert_eq!(
25426                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
25427                    .expect("replayed workflow result"),
25428                json!(["message-1", "message-2"])
25429            );
25430            assert_eq!(
25431                replayed.message_stream_cursors,
25432                vec![json!({"stream_name": "orders", "through_position": 2})]
25433            );
25434            assert!(replayed.message_stream_waits.is_empty());
25435        }
25436    }
25437
25438    #[test]
25439    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
25440        assert!(!worker_protocol_supports_message_streams("1.14"));
25441        assert!(worker_protocol_supports_message_streams("1.15"));
25442        assert!(worker_protocol_supports_message_streams("1.16"));
25443        assert!(worker_protocol_supports_message_streams(
25444            WORKER_PROTOCOL_VERSION
25445        ));
25446        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
25447    }
25448
25449    #[test]
25450    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
25451        let ctx = workflow_context(vec![
25452            history_event(
25453                "ConditionWaitOpened",
25454                json!({
25455                    "sequence": 1,
25456                    "condition_wait_id": "condition:1",
25457                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25458                    "condition_key": "signal:finish",
25459                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25460                }),
25461            ),
25462            history_event(
25463                "ConditionWaitSatisfied",
25464                json!({
25465                    "sequence": 1,
25466                    "condition_wait_id": "condition:1",
25467                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25468                    "condition_key": "signal:finish",
25469                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25470                }),
25471            ),
25472            history_event(
25473                "SignalReceived",
25474                json!({"signal_name": "finish", "arguments": []}),
25475            ),
25476        ]);
25477        let mut signal = Box::pin(ctx.wait_signal("finish"));
25478        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25479
25480        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25481            signal.as_mut().poll(&mut task_context)
25482        else {
25483            panic!("condition history must not resolve as a typed signal wait");
25484        };
25485        assert_eq!(failure.reason, "recorded_command_mismatch");
25486        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
25487    }
25488
25489    #[test]
25490    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
25491        let signal_then_timer = vec![
25492            history_event(
25493                "SignalWaitOpened",
25494                json!({"sequence": 1, "signal_name": "go"}),
25495            ),
25496            history_event(
25497                "SignalApplied",
25498                json!({
25499                    "sequence": 1,
25500                    "signal_name": "go",
25501                    "value": fixture_envelope(json!(["now"])),
25502                }),
25503            ),
25504            history_event(
25505                "TimerScheduled",
25506                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25507            ),
25508            history_event(
25509                "TimerFired",
25510                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25511            ),
25512        ];
25513
25514        let ctx = workflow_context(signal_then_timer.clone());
25515        let mut signal = Box::pin(ctx.wait_signal("go"));
25516        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25517        assert!(matches!(
25518            signal.as_mut().poll(&mut task_context),
25519            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
25520        ));
25521        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
25522        assert!(matches!(
25523            timer.as_mut().poll(&mut task_context),
25524            Poll::Ready(Ok(()))
25525        ));
25526        ctx.ensure_history_consumed()
25527            .expect("signal and timer history consumed in order");
25528
25529        let reordered = workflow_context(signal_then_timer);
25530        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
25531        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25532            timer_first.as_mut().poll(&mut task_context)
25533        else {
25534            panic!("timer cannot consume signal-wait-first history");
25535        };
25536        assert_eq!(failure.reason, "recorded_command_mismatch");
25537        assert_eq!(failure.sequence, Some(1));
25538        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
25539
25540        let timer_then_signal = vec![
25541            history_event(
25542                "TimerScheduled",
25543                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25544            ),
25545            history_event(
25546                "TimerFired",
25547                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25548            ),
25549            history_event(
25550                "SignalWaitOpened",
25551                json!({"sequence": 2, "signal_name": "go"}),
25552            ),
25553            history_event(
25554                "SignalApplied",
25555                json!({
25556                    "sequence": 2,
25557                    "signal_name": "go",
25558                    "value": fixture_envelope(json!([])),
25559                }),
25560            ),
25561        ];
25562        let reordered = workflow_context(timer_then_signal);
25563        let mut signal_first = Box::pin(reordered.wait_signal("go"));
25564        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25565            signal_first.as_mut().poll(&mut task_context)
25566        else {
25567            panic!("signal wait cannot consume timer-first history");
25568        };
25569        assert_eq!(failure.reason, "recorded_command_mismatch");
25570        assert_eq!(failure.sequence, Some(1));
25571        assert_eq!(failure.expected.as_deref(), Some("timer"));
25572    }
25573
25574    #[test]
25575    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
25576        let duplicate_timer = WorkflowState::new(
25577            vec![
25578                history_event(
25579                    "TimerScheduled",
25580                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25581                ),
25582                history_event(
25583                    "TimerScheduled",
25584                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
25585                ),
25586            ],
25587            "rust-workers".to_string(),
25588            DEFAULT_CODEC.to_string(),
25589            None,
25590        )
25591        .expect_err("one workflow sequence cannot schedule two timers");
25592        assert!(matches!(
25593            duplicate_timer,
25594            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25595                if reason == "timer_schedule_missing_or_duplicate"
25596        ));
25597
25598        let colliding_kinds = WorkflowState::new(
25599            vec![
25600                history_event(
25601                    "TimerScheduled",
25602                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25603                ),
25604                history_event(
25605                    "ActivityCompleted",
25606                    json!({"sequence": 1, "activity_type": "same-sequence"}),
25607                ),
25608            ],
25609            "rust-workers".to_string(),
25610            DEFAULT_CODEC.to_string(),
25611            None,
25612        )
25613        .expect_err("one workflow sequence cannot identify two command kinds");
25614        assert!(matches!(
25615            colliding_kinds,
25616            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25617                if reason == "durable_command_sequence_collision"
25618        ));
25619
25620        let duplicate_signal_wait = WorkflowState::new(
25621            vec![
25622                history_event(
25623                    "SignalWaitOpened",
25624                    json!({"sequence": 1, "signal_name": "go"}),
25625                ),
25626                history_event(
25627                    "SignalWaitOpened",
25628                    json!({"sequence": 1, "signal_name": "go"}),
25629                ),
25630            ],
25631            "rust-workers".to_string(),
25632            DEFAULT_CODEC.to_string(),
25633            None,
25634        )
25635        .expect_err("one workflow sequence cannot open two signal waits");
25636        assert!(matches!(
25637            duplicate_signal_wait,
25638            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25639                if reason == "signal_wait_open_missing_or_duplicate"
25640        ));
25641    }
25642
25643    #[test]
25644    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25645        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25646            .expect("side-effect result");
25647        let ctx = workflow_context(vec![history_event(
25648            "SideEffectRecorded",
25649            json!({"sequence": 99, "result": result}),
25650        )]);
25651
25652        let replayed: Value = ctx
25653            .side_effect(|| panic!("recorded side effect must not run"))
25654            .expect("positive global workflow sequence is valid");
25655        assert_eq!(replayed, json!({"captured": true}));
25656        ctx.ensure_history_consumed().expect("history consumed");
25657    }
25658
25659    #[test]
25660    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25661        let result =
25662            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25663        let zero = WorkflowState::new(
25664            vec![history_event(
25665                "SideEffectRecorded",
25666                json!({"sequence": 0, "result": result.clone()}),
25667            )],
25668            "rust-workers".to_string(),
25669            DEFAULT_CODEC.to_string(),
25670            None,
25671        )
25672        .expect_err("durable command sequences must be positive");
25673        assert!(matches!(
25674            zero,
25675            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25676                if reason == "durable_command_sequence_invalid"
25677        ));
25678
25679        let descending = WorkflowState::new(
25680            vec![
25681                history_event(
25682                    "SideEffectRecorded",
25683                    json!({"sequence": 3, "result": result}),
25684                ),
25685                history_event(
25686                    "VersionMarkerRecorded",
25687                    json!({
25688                        "sequence": 2,
25689                        "change_id": "descending-marker",
25690                        "version": 1,
25691                        "min_supported": 1,
25692                        "max_supported": 1,
25693                    }),
25694                ),
25695            ],
25696            "rust-workers".to_string(),
25697            DEFAULT_CODEC.to_string(),
25698            None,
25699        )
25700        .expect_err("new durable commands must remain strictly ordered");
25701        let Error::NonDeterministicReplay(failure) = descending else {
25702            panic!("expected typed replay failure");
25703        };
25704        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25705        assert_eq!(failure.sequence, Some(2));
25706        assert_eq!(
25707            failure.expected.as_deref(),
25708            Some("workflow sequence greater than 3")
25709        );
25710        assert_eq!(failure.actual.as_deref(), Some("2"));
25711    }
25712
25713    #[test]
25714    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25715        fn worker() -> Worker {
25716            let client = Client::new("http://127.0.0.1:8080").expect("client");
25717            let mut worker = Worker::new(client, "rust-workers");
25718            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25719                ctx.wait_signal("finish").await?;
25720                let marker: String =
25721                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25722                assert_eq!(marker, "after-finish");
25723                Ok(json!("finished"))
25724            });
25725            worker
25726        }
25727
25728        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25729            .expect("side-effect result");
25730        let task = workflow_task(
25731            "rust.finish-after-gaps",
25732            vec![
25733                history_event(
25734                    "SignalWaitOpened",
25735                    json!({"sequence": 1, "signal_name": "finish"}),
25736                ),
25737                history_event(
25738                    "SignalReceived",
25739                    json!({
25740                        "signal_id": "increment-3",
25741                        "signal_name": "increment",
25742                        "workflow_sequence": 2,
25743                        "payload_codec": DEFAULT_CODEC,
25744                        "arguments": fixture_envelope(json!([3])),
25745                    }),
25746                ),
25747                history_event(
25748                    "SignalReceived",
25749                    json!({
25750                        "signal_id": "increment-5",
25751                        "signal_name": "increment",
25752                        "workflow_sequence": 3,
25753                        "payload_codec": DEFAULT_CODEC,
25754                        "arguments": fixture_envelope(json!([5])),
25755                    }),
25756                ),
25757                history_event(
25758                    "SignalReceived",
25759                    json!({
25760                        "signal_id": "finish",
25761                        "signal_name": "finish",
25762                        "workflow_sequence": 4,
25763                        "payload_codec": DEFAULT_CODEC,
25764                        "arguments": fixture_envelope(json!([])),
25765                    }),
25766                ),
25767                history_event(
25768                    "SignalApplied",
25769                    json!({
25770                        "sequence": 1,
25771                        "signal_id": "finish",
25772                        "signal_name": "finish",
25773                        "payload_codec": DEFAULT_CODEC,
25774                        "value": fixture_envelope(json!([])),
25775                    }),
25776                ),
25777                history_event(
25778                    "SideEffectRecorded",
25779                    json!({"sequence": 5, "result": marker}),
25780                ),
25781            ],
25782            DEFAULT_CODEC,
25783        );
25784
25785        for _original_or_cold_worker in 0..2 {
25786            let commands = worker()
25787                .execute_workflow_task(task.clone())
25788                .expect("signal gaps preserve deterministic replay");
25789            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25790            assert_eq!(commands[0]["type"], "complete_workflow");
25791            assert_eq!(
25792                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25793                json!("finished")
25794            );
25795        }
25796    }
25797
25798    #[test]
25799    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25800        let ctx = workflow_context(Vec::new());
25801        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25802        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25803        assert!(matches!(
25804            sleep.as_mut().poll(&mut task_context),
25805            Poll::Ready(Err(Error::TimerDurationOverflow))
25806        ));
25807        assert!(ctx.take_commands().expect("commands").is_empty());
25808    }
25809
25810    #[test]
25811    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25812        let entries = AvroValue::Map(BTreeMap::from([
25813            ("text".to_string(), AvroValue::String("same".to_string())),
25814            (
25815                "nested".to_string(),
25816                AvroValue::Map(BTreeMap::from([
25817                    ("beta".to_string(), AvroValue::Long(2)),
25818                    ("alpha".to_string(), AvroValue::Long(1)),
25819                ])),
25820            ),
25821            ("long".to_string(), AvroValue::Long(7)),
25822            ("double".to_string(), AvroValue::Double(7.0)),
25823            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25824        ]));
25825        let ctx = workflow_context(Vec::new());
25826        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25827        let commands = ctx.take_commands().expect("commands");
25828
25829        assert_eq!(commands.len(), 1);
25830        assert_eq!(commands[0]["type"], "upsert_memo");
25831        let server_entries = json!({
25832            "codec": "avro",
25833            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25834        });
25835        assert_eq!(
25836            commands[0]["entries"]
25837                .as_object()
25838                .expect("entries envelope")
25839                .keys()
25840                .collect::<Vec<_>>(),
25841            vec!["blob", "codec"]
25842        );
25843        assert_eq!(commands[0]["entries"], server_entries);
25844        let wire_entries =
25845            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25846        assert_eq!(wire_entries, entries);
25847
25848        let history = vec![history_event(
25849            "MemoUpserted",
25850            json!({
25851                "sequence": 1,
25852                "entries": server_entries.clone(),
25853                "merged": server_entries,
25854            }),
25855        )];
25856        let replay = workflow_context(history.clone());
25857        replay
25858            .upsert_memo(entries.clone())
25859            .expect("matching replay identity");
25860        assert!(replay.take_commands().expect("replay commands").is_empty());
25861
25862        let changed_types = AvroValue::Map(BTreeMap::from([
25863            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25864            (
25865                "nested".to_string(),
25866                AvroValue::Map(BTreeMap::from([
25867                    ("alpha".to_string(), AvroValue::Long(1)),
25868                    ("beta".to_string(), AvroValue::Long(2)),
25869                ])),
25870            ),
25871            ("long".to_string(), AvroValue::Double(7.0)),
25872            ("double".to_string(), AvroValue::Long(7)),
25873            ("binary".to_string(), AvroValue::String("same".to_string())),
25874        ]));
25875        let error = workflow_context(history)
25876            .upsert_memo(changed_types)
25877            .expect_err("memo replay identity must preserve Avro value types");
25878        assert!(matches!(
25879            error,
25880            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25881        ));
25882    }
25883
25884    #[test]
25885    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25886        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25887            .expect("memo envelope");
25888        let replay = workflow_context(vec![history_event(
25889            "MemoUpserted",
25890            json!({
25891                "sequence": 1,
25892                "entries": original.clone(),
25893                "merged": original
25894            }),
25895        )]);
25896        let error = replay
25897            .upsert_memo(json!({"stage": "changed"}))
25898            .expect_err("changed memo update must fail replay");
25899        assert!(matches!(
25900            error,
25901            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25902        ));
25903
25904        let invalid = workflow_context(Vec::new())
25905            .upsert_memo(
25906                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25907            )
25908            .expect_err("oversized key");
25909        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25910    }
25911
25912    #[test]
25913    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25914        let negative_zero = AvroValue::Map(BTreeMap::from([(
25915            "reading".to_string(),
25916            AvroValue::Double(-0.0),
25917        )]));
25918        let negative_zero_envelope =
25919            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25920        let history = vec![history_event(
25921            "MemoUpserted",
25922            json!({
25923                "sequence": 1,
25924                "entries": negative_zero_envelope.clone(),
25925                "merged": negative_zero_envelope,
25926            }),
25927        )];
25928
25929        workflow_context(history.clone())
25930            .upsert_memo(negative_zero)
25931            .expect("matching negative-zero history identity");
25932
25933        let error = workflow_context(history)
25934            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25935                "reading".to_string(),
25936                AvroValue::Double(0.0),
25937            )])))
25938            .expect_err("positive zero must not consume negative-zero memo history");
25939        assert!(matches!(
25940            error,
25941            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25942        ));
25943    }
25944
25945    #[test]
25946    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
25947        let supported = json!({
25948            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
25949            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
25950        });
25951        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
25952        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
25953            "workflow_memo_updates": {"supported": false},
25954            "supported_workflow_task_commands": ["upsert_memo"]
25955        }))));
25956        assert!(commands_use_workflow_memo_updates(&[json!({
25957            "type": "upsert_memo",
25958            "entries": {"stage": "processing"}
25959        })]));
25960    }
25961
25962    #[test]
25963    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
25964        let client = Client::new("http://127.0.0.1:8080").expect("client");
25965        let mut worker = Worker::new(client, "rust-workers");
25966        worker.register_workflow("rust.timer", |ctx, _input| async move {
25967            ctx.sleep(Duration::from_secs(5)).await?;
25968            ctx.activity("after-timer", json!([])).await
25969        });
25970
25971        let task = |history_events| WorkflowTask {
25972            task_id: "wft-rust-timer-1".to_string(),
25973            observability_context: None,
25974            dispatch_observability_context: None,
25975            observability_links: None,
25976            workflow_command_id: None,
25977            workflow_id: Some("wf-rust-timer".to_string()),
25978            run_id: Some("run-rust-timer".to_string()),
25979            workflow_type: "rust.timer".to_string(),
25980            cancel_requested: false,
25981            payload_codec: DEFAULT_CODEC.to_string(),
25982            arguments: Some(
25983                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25984            ),
25985            history_events,
25986            total_history_events: None,
25987            history_size_bytes: None,
25988            continue_as_new_recommended: None,
25989            history_budget_pressure: None,
25990            next_history_page_token: None,
25991            workflow_task_attempt: 1,
25992            workflow_signal_id: None,
25993            signal_name: None,
25994            signal_arguments: None,
25995            workflow_update_id: None,
25996            update_name: None,
25997            lease_owner: Some("rust-worker".to_string()),
25998        };
25999
26000        let initial = worker
26001            .execute_workflow_task(task(Vec::new()))
26002            .expect("initial timer task");
26003        assert_eq!(
26004            initial,
26005            vec![json!({"type": "start_timer", "delay_seconds": 5})]
26006        );
26007
26008        let activity_result =
26009            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
26010        let replayed = worker
26011            .execute_workflow_task(task(vec![
26012                history_event(
26013                    "TimerScheduled",
26014                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26015                ),
26016                history_event(
26017                    "TimerFired",
26018                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26019                ),
26020                history_event(
26021                    "ActivityCompleted",
26022                    json!({
26023                        "sequence": 2,
26024                        "activity_type": "after-timer",
26025                        "payload_codec": DEFAULT_CODEC,
26026                        "result": activity_result,
26027                    }),
26028                ),
26029            ]))
26030            .expect("replayed workflow task");
26031        assert_eq!(replayed.len(), 1);
26032        assert_eq!(replayed[0]["type"], "complete_workflow");
26033        assert_eq!(
26034            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
26035            json!("done")
26036        );
26037    }
26038
26039    #[test]
26040    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
26041        let client = Client::new("http://127.0.0.1:8080").expect("client");
26042        let mut worker = Worker::new(client, "rust-workers");
26043        worker.register_workflow("rust.continue", |ctx, _input| async move {
26044            ctx.continue_as_new_with_options(
26045                ContinueAsNewOptions::new()
26046                    .workflow_type("rust.next")
26047                    .task_queue("next-workers"),
26048                json!([2, {"cursor": "next"}]),
26049            )
26050        });
26051
26052        let commands = worker
26053            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
26054            .expect("continue-as-new command");
26055
26056        assert_eq!(commands.len(), 1);
26057        assert_eq!(commands[0]["type"], "continue_as_new");
26058        assert_eq!(commands[0]["workflow_type"], "rust.next");
26059        assert_eq!(commands[0]["queue"], "next-workers");
26060        assert_eq!(
26061            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
26062                .expect("continue-as-new arguments"),
26063            json!([2, {"cursor": "next"}])
26064        );
26065    }
26066
26067    #[test]
26068    fn continue_as_new_preserves_typed_arguments() {
26069        let client = Client::new("http://127.0.0.1:8080").expect("client");
26070        let mut worker = Worker::new(client, "rust-workers");
26071        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
26072            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
26073            unreachable!("continue-as-new returns a control-flow error")
26074        });
26075
26076        let commands = worker
26077            .execute_workflow_task(workflow_task(
26078                "rust.typed-continue",
26079                Vec::new(),
26080                DEFAULT_CODEC,
26081            ))
26082            .expect("typed continue-as-new command");
26083
26084        assert_eq!(commands[0]["type"], "continue_as_new");
26085        assert_eq!(
26086            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
26087                .expect("typed continue arguments"),
26088            AvroValue::Array(vec![typed_fidelity_probe()])
26089        );
26090    }
26091
26092    #[test]
26093    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
26094        let client = Client::new("http://127.0.0.1:8080").expect("client");
26095        let mut worker = Worker::new(client, "rust-workers");
26096        worker.register_workflow("rust.continue", |ctx, _input| async move {
26097            ctx.continue_as_new(json!([2]))
26098        });
26099        let task = workflow_task(
26100            "rust.continue",
26101            vec![history_event(
26102                "WorkflowContinuedAsNew",
26103                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
26104            )],
26105            DEFAULT_CODEC,
26106        );
26107
26108        for _worker_restart_or_redelivery in 0..2 {
26109            let commands = worker
26110                .execute_workflow_task(task.clone())
26111                .expect("recorded transition replays");
26112            assert!(
26113                commands.is_empty(),
26114                "replay must not emit another successor"
26115            );
26116        }
26117    }
26118
26119    #[test]
26120    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
26121        let ctx = workflow_context(Vec::new());
26122        let error = ctx
26123            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
26124            .expect_err("blank queue must be rejected");
26125
26126        let Error::InvalidContinueAsNewOptions(error) = error else {
26127            panic!("expected typed continue-as-new validation error");
26128        };
26129        assert_eq!(error.field, "task_queue");
26130        assert!(ctx.take_commands().expect("commands").is_empty());
26131    }
26132
26133    #[test]
26134    fn workflow_context_exposes_server_history_budget() {
26135        let client = Client::new("http://127.0.0.1:8080").expect("client");
26136        let mut worker = Worker::new(client, "rust-workers");
26137        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
26138            let budget = ctx.history_budget()?;
26139            Ok(json!({
26140                "events": budget.event_count,
26141                "bytes": budget.size_bytes,
26142                "recommended": budget.continue_as_new_recommended,
26143                "pressure": budget.pressure,
26144            }))
26145        });
26146        let task: WorkflowTask = serde_json::from_value(json!({
26147            "task_id": "task-history-budget",
26148            "workflow_type": "rust.history-budget",
26149            "payload_codec": DEFAULT_CODEC,
26150            "history_events": [],
26151            "total_history_events": 480,
26152            "history_size_bytes": 1_048_576,
26153            "continue_as_new_recommended": true,
26154            "history_budget_pressure": "continue_as_new_recommended",
26155        }))
26156        .expect("published workflow task");
26157
26158        let commands = worker
26159            .execute_workflow_task(task)
26160            .expect("history-budget workflow");
26161        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
26162        assert_eq!(result["events"], 480);
26163        assert_eq!(result["bytes"], 1_048_576);
26164        assert_eq!(result["recommended"], true);
26165        assert_eq!(result["pressure"], "continue_as_new_recommended");
26166    }
26167
26168    #[test]
26169    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
26170        let client = Client::new("http://127.0.0.1:8080").expect("client");
26171        let mut worker = Worker::new(client, "rust-workers");
26172        worker.register_workflow("rust.failing", |_ctx, _input| async move {
26173            Err(Error::Codec("rust_conformance_failure".to_string()))
26174        });
26175        let task = WorkflowTask {
26176            task_id: "wft-rust-failing-1".to_string(),
26177            observability_context: None,
26178            dispatch_observability_context: None,
26179            observability_links: None,
26180            workflow_command_id: None,
26181            workflow_id: Some("wf-rust-failing".to_string()),
26182            run_id: Some("run-rust-failing".to_string()),
26183            workflow_type: "rust.failing".to_string(),
26184            cancel_requested: false,
26185            payload_codec: DEFAULT_CODEC.to_string(),
26186            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26187            history_events: Vec::new(),
26188            total_history_events: Some(0),
26189            history_size_bytes: None,
26190            continue_as_new_recommended: None,
26191            history_budget_pressure: None,
26192            next_history_page_token: None,
26193            workflow_task_attempt: 1,
26194            workflow_signal_id: None,
26195            signal_name: None,
26196            signal_arguments: None,
26197            workflow_update_id: None,
26198            update_name: None,
26199            lease_owner: Some("rust-worker".to_string()),
26200        };
26201
26202        let commands = worker
26203            .execute_workflow_task(task)
26204            .expect("handler failure becomes a workflow command");
26205
26206        assert_eq!(commands.len(), 1);
26207        assert_eq!(commands[0]["type"], "fail_workflow");
26208        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
26209        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
26210        assert_eq!(commands[0]["non_retryable"], false);
26211        assert_eq!(
26212            commands[0]["message"],
26213            "codec error: rust_conformance_failure"
26214        );
26215        assert_eq!(
26216            commands[0]["exception"]["message"],
26217            "codec error: rust_conformance_failure"
26218        );
26219    }
26220
26221    #[test]
26222    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
26223        let client = Client::new("http://127.0.0.1:8080").expect("client");
26224        let mut worker = Worker::new(client, "rust-workers");
26225        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
26226            let _: String = ctx.side_effect(|| "captured".to_string())?;
26227            Err(Error::WorkerLoop("application failure".to_string()))
26228        });
26229
26230        let commands = worker
26231            .execute_workflow_task(workflow_task(
26232                "rust.failing-after-side-effect",
26233                Vec::new(),
26234                DEFAULT_CODEC,
26235            ))
26236            .expect("ordinary failure remains a workflow decision");
26237
26238        assert_eq!(commands.len(), 2);
26239        assert_eq!(commands[0]["type"], "record_side_effect");
26240        assert_eq!(commands[1]["type"], "fail_workflow");
26241    }
26242
26243    #[test]
26244    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
26245        let client = Client::new("http://127.0.0.1:8080").expect("client");
26246        let mut worker = Worker::new(client, "rust-workers");
26247        worker.register_workflow("rust.redrive", |ctx, _input| async move {
26248            ctx.activity("greet", json!([])).await?;
26249            Ok(Value::Null)
26250        });
26251        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
26252            match ctx.activity("greet", json!([])).await {
26253                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
26254                result => result,
26255            }
26256        });
26257
26258        let failed = history_event(
26259            "ActivityFailed",
26260            json!({
26261                "sequence": 1,
26262                "activity_type": "greet",
26263                "activity_execution_id": "activity-1",
26264                "message": "failed"
26265            }),
26266        );
26267        let commands = worker
26268            .execute_workflow_task(workflow_task(
26269                "rust.redrive",
26270                vec![failed.clone()],
26271                DEFAULT_CODEC,
26272            ))
26273            .expect("recorded failure becomes a workflow command");
26274        assert_eq!(commands[0]["type"], "fail_workflow");
26275        assert_eq!(commands[0]["failed_step_sequence"], 1);
26276        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
26277
26278        let translated = worker
26279            .execute_workflow_task(workflow_task(
26280                "rust.redrive-translated",
26281                vec![failed],
26282                DEFAULT_CODEC,
26283            ))
26284            .expect("translated failure becomes a workflow command");
26285        assert_eq!(translated[0]["type"], "fail_workflow");
26286        assert!(translated[0].get("failed_step_sequence").is_none());
26287        assert!(translated[0].get("failed_activity_execution_id").is_none());
26288
26289        let without_identity = worker
26290            .execute_workflow_task(workflow_task(
26291                "rust.redrive",
26292                vec![history_event(
26293                    "ActivityFailed",
26294                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
26295                )],
26296                DEFAULT_CODEC,
26297            ))
26298            .expect("incomplete identity still fails the workflow");
26299        assert!(without_identity[0].get("failed_step_sequence").is_none());
26300
26301        let timed_out = worker
26302            .execute_workflow_task(workflow_task(
26303                "rust.redrive",
26304                vec![history_event(
26305                    "ActivityTimedOut",
26306                    json!({
26307                        "sequence": 1,
26308                        "activity_type": "greet",
26309                        "activity_execution_id": "activity-timeout",
26310                    }),
26311                )],
26312                DEFAULT_CODEC,
26313            ))
26314            .expect("timeout still fails the workflow");
26315        assert!(timed_out[0].get("failed_step_sequence").is_none());
26316    }
26317
26318    #[test]
26319    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
26320        let client = Client::new("http://127.0.0.1:8080").expect("client");
26321        let mut worker = Worker::new(client, "rust-workers");
26322        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
26323            let first = ctx.activity("first", json!([])).await?;
26324            let second = ctx.activity("second", json!([first.clone()])).await?;
26325            Ok(json!({"first": first, "second": second}))
26326        });
26327        let first = history_event(
26328            "ActivityCompleted",
26329            json!({
26330                "sequence": 1,
26331                "activity_type": "first",
26332                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
26333                "payload_codec": DEFAULT_CODEC,
26334                "reused_from_run_id": "failed-run",
26335                "reused_activity_execution_id": "original-first",
26336            }),
26337        );
26338
26339        let retry = worker
26340            .execute_workflow_task(workflow_task(
26341                "rust.redrive-successor",
26342                vec![first.clone()],
26343                DEFAULT_CODEC,
26344            ))
26345            .expect("reused result replays before failed step");
26346        assert_eq!(retry.len(), 1);
26347        assert_eq!(retry[0]["type"], "schedule_activity");
26348        assert_eq!(retry[0]["activity_type"], "second");
26349        assert_eq!(
26350            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
26351            json!(["recorded"]),
26352        );
26353
26354        let second = history_event(
26355            "ActivityCompleted",
26356            json!({
26357                "sequence": 2,
26358                "activity_type": "second",
26359                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
26360                "payload_codec": DEFAULT_CODEC,
26361            }),
26362        );
26363        let completed = worker
26364            .execute_workflow_task(workflow_task(
26365                "rust.redrive-successor",
26366                vec![first, second],
26367                DEFAULT_CODEC,
26368            ))
26369            .expect("retried step completes the successor");
26370        assert_eq!(completed.len(), 1);
26371        assert_eq!(completed[0]["type"], "complete_workflow");
26372        assert_eq!(
26373            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
26374            json!({"first": "recorded", "second": "retried"}),
26375        );
26376    }
26377
26378    #[test]
26379    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
26380        let client = Client::new("http://127.0.0.1:8080").expect("client");
26381        let mut worker = Worker::new(client, "rust-workers");
26382        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
26383            Err(Error::WorkerLoop("application failure".to_string()))
26384        });
26385        let result =
26386            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
26387
26388        let error = worker
26389            .execute_workflow_task(workflow_task(
26390                "rust.removed-side-effect",
26391                vec![history_event(
26392                    "SideEffectRecorded",
26393                    json!({"sequence": 1, "result": result}),
26394                )],
26395                DEFAULT_CODEC,
26396            ))
26397            .expect_err("removed committed history must not become fail_workflow");
26398
26399        let Error::NonDeterministicReplay(failure) = error else {
26400            panic!("expected typed replay failure");
26401        };
26402        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26403        assert_eq!(failure.sequence, Some(1));
26404        assert_eq!(failure.expected.as_deref(), Some("side effect"));
26405    }
26406
26407    #[test]
26408    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
26409        let client = Client::new("http://127.0.0.1:8080").expect("client");
26410        let mut worker = Worker::new(client, "rust-workers");
26411        worker.register_workflow(
26412            "rust.side-effect-before-marker-error",
26413            |ctx, _input| async move {
26414                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
26415                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
26416                ctx.get_version("restart-safe", 2, 2)?;
26417                Ok(Value::Null)
26418            },
26419        );
26420
26421        let error = worker
26422            .execute_workflow_task(workflow_task(
26423                "rust.side-effect-before-marker-error",
26424                vec![history_event(
26425                    "VersionMarkerRecorded",
26426                    json!({
26427                        "sequence": 1,
26428                        "change_id": "restart-safe",
26429                        "version": 1,
26430                        "min_supported": 1,
26431                        "max_supported": 1,
26432                    }),
26433                )],
26434                DEFAULT_CODEC,
26435            ))
26436            .expect_err("replay error must return no queued workflow commands");
26437
26438        let Error::NonDeterministicReplay(failure) = error else {
26439            panic!("expected typed replay failure");
26440        };
26441        assert_eq!(failure.reason, "version_marker_incompatible_range");
26442        assert_eq!(failure.sequence, Some(1));
26443    }
26444
26445    #[test]
26446    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
26447        let client = Client::new("http://127.0.0.1:8080").expect("client");
26448        let mut worker = Worker::new(client, "rust-workers");
26449        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
26450            ctx.sleep(Duration::from_secs(5)).await?;
26451            Ok(json!({"status": "timer fired"}))
26452        });
26453
26454        let task = WorkflowTask {
26455            task_id: "wft-rust-timer-pending".to_string(),
26456            observability_context: None,
26457            dispatch_observability_context: None,
26458            observability_links: None,
26459            workflow_command_id: None,
26460            workflow_id: Some("wf-rust-timer".to_string()),
26461            run_id: Some("run-rust-timer".to_string()),
26462            workflow_type: "rust.timer.pending".to_string(),
26463            cancel_requested: false,
26464            payload_codec: DEFAULT_CODEC.to_string(),
26465            arguments: Some(
26466                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26467            ),
26468            history_events: vec![history_event(
26469                "TimerScheduled",
26470                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26471            )],
26472            total_history_events: Some(1),
26473            history_size_bytes: None,
26474            continue_as_new_recommended: None,
26475            history_budget_pressure: None,
26476            next_history_page_token: None,
26477            workflow_task_attempt: 1,
26478            workflow_signal_id: None,
26479            signal_name: None,
26480            signal_arguments: None,
26481            workflow_update_id: None,
26482            update_name: None,
26483            lease_owner: Some("rust-worker".to_string()),
26484        };
26485
26486        for _redelivery_or_restart in 0..2 {
26487            let commands = worker
26488                .execute_workflow_task(task.clone())
26489                .expect("recorded timer remains pending");
26490            assert!(
26491                commands.is_empty(),
26492                "recorded timer must not be rescheduled"
26493            );
26494        }
26495    }
26496
26497    #[test]
26498    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
26499        let client = Client::new("http://127.0.0.1:8080").expect("client");
26500        let mut worker = Worker::new(client, "rust-workers");
26501        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
26502            Ok(json!({"status": "completed"}))
26503        });
26504        let task = WorkflowTask {
26505            task_id: "wft-rust-timer-removed".to_string(),
26506            observability_context: None,
26507            dispatch_observability_context: None,
26508            observability_links: None,
26509            workflow_command_id: None,
26510            workflow_id: Some("wf-rust-timer".to_string()),
26511            run_id: Some("run-rust-timer".to_string()),
26512            workflow_type: "rust.timer.removed".to_string(),
26513            cancel_requested: false,
26514            payload_codec: DEFAULT_CODEC.to_string(),
26515            arguments: Some(
26516                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26517            ),
26518            history_events: vec![
26519                history_event(
26520                    "TimerScheduled",
26521                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26522                ),
26523                history_event(
26524                    "TimerFired",
26525                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26526                ),
26527            ],
26528            total_history_events: Some(2),
26529            history_size_bytes: None,
26530            continue_as_new_recommended: None,
26531            history_budget_pressure: None,
26532            next_history_page_token: None,
26533            workflow_task_attempt: 1,
26534            workflow_signal_id: None,
26535            signal_name: None,
26536            signal_arguments: None,
26537            workflow_update_id: None,
26538            update_name: None,
26539            lease_owner: Some("rust-worker".to_string()),
26540        };
26541
26542        let Error::NonDeterministicReplay(failure) = worker
26543            .execute_workflow_task(task)
26544            .expect_err("removed timer must fail replay")
26545        else {
26546            panic!("expected typed replay failure");
26547        };
26548        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26549        assert_eq!(failure.sequence, Some(1));
26550    }
26551
26552    #[test]
26553    fn workflow_context_emits_explicit_child_workflow_contract() {
26554        let ctx = WorkflowContext {
26555            cancellation_scope_id: "root".into(),
26556            state: Arc::new(Mutex::new(
26557                WorkflowState::new_with_identity(
26558                    Vec::new(),
26559                    Some("wf-parent".to_string()),
26560                    Some("run-parent".to_string()),
26561                    "parent-workers".to_string(),
26562                    DEFAULT_CODEC.to_string(),
26563                    None,
26564                )
26565                .expect("workflow state"),
26566            )),
26567        };
26568        let options = ChildWorkflowOptions::new("python-workers")
26569            .parent_close_policy(ParentClosePolicy::RequestCancel)
26570            .retry_policy(ChildWorkflowRetryPolicy {
26571                max_attempts: Some(3),
26572                backoff_seconds: vec![1, 5],
26573                non_retryable_error_types: vec!["ValidationError".to_string()],
26574            })
26575            .execution_timeout_seconds(600)
26576            .run_timeout_seconds(120);
26577        let mut call = Box::pin(ctx.start_child_workflow(
26578            "python.fulfil-order",
26579            options,
26580            json!([{"order_id": "order-42"}]),
26581        ));
26582        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26583
26584        assert!(matches!(
26585            call.as_mut().poll(&mut task_context),
26586            Poll::Pending
26587        ));
26588        let commands = ctx.take_commands().expect("commands");
26589        assert_eq!(commands.len(), 1);
26590        let command = &commands[0];
26591        assert_eq!(command["type"], "start_child_workflow");
26592        assert_eq!(command["workflow_type"], "python.fulfil-order");
26593        assert_eq!(command["queue"], "python-workers");
26594        assert_eq!(command["parent_close_policy"], "request_cancel");
26595        assert_eq!(command["retry_policy"]["max_attempts"], 3);
26596        assert_eq!(command["execution_timeout_seconds"], 600);
26597        assert_eq!(command["run_timeout_seconds"], 120);
26598        assert_eq!(
26599            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
26600            json!([{"order_id": "order-42"}])
26601        );
26602    }
26603
26604    fn child_parent_worker() -> Worker {
26605        let client = Client::new("http://127.0.0.1:8080").expect("client");
26606        let mut worker = Worker::new(client, "rust-parent-workers");
26607        worker.register_workflow("rust.parent", |ctx, _input| async move {
26608            let child = ctx
26609                .start_child_workflow(
26610                    "python.child",
26611                    ChildWorkflowOptions::new("python-child-workers")
26612                        .parent_close_policy(ParentClosePolicy::Terminate),
26613                    json!([{"codec_probe": [1, true, "rust"]}]),
26614                )
26615                .await?;
26616            Ok(json!({
26617                "parent_workflow_id": child.parent.workflow_id,
26618                "parent_run_id": child.parent.run_id,
26619                "child_workflow_id": child.child.workflow_id,
26620                "child_run_id": child.child.run_id,
26621                "child_workflow_type": child.child_workflow_type,
26622                "result": child.result,
26623            }))
26624        });
26625        worker
26626    }
26627
26628    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26629        WorkflowTask {
26630            task_id: "wft-child-parent".to_string(),
26631            observability_context: None,
26632            dispatch_observability_context: None,
26633            observability_links: None,
26634            workflow_command_id: None,
26635            workflow_id: Some("wf-parent".to_string()),
26636            run_id: Some("run-parent".to_string()),
26637            workflow_type: "rust.parent".to_string(),
26638            cancel_requested: false,
26639            payload_codec: DEFAULT_CODEC.to_string(),
26640            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26641            history_events: vec![
26642                HistoryEvent {
26643                    event_type: "ChildWorkflowScheduled".to_string(),
26644                    payload: json!({
26645                        "sequence": 1,
26646                        "child_call_id": "call-child",
26647                        "child_workflow_instance_id": "wf-child",
26648                        "child_workflow_run_id": "run-child",
26649                        "child_workflow_type": "python.child",
26650                        "parent_close_policy": "terminate",
26651                    }),
26652                    raw: HashMap::new(),
26653                },
26654                HistoryEvent {
26655                    event_type: event_type.to_string(),
26656                    payload,
26657                    raw: HashMap::new(),
26658                },
26659            ],
26660            total_history_events: Some(2),
26661            history_size_bytes: None,
26662            continue_as_new_recommended: None,
26663            history_budget_pressure: None,
26664            next_history_page_token: None,
26665            workflow_task_attempt: 1,
26666            workflow_signal_id: None,
26667            signal_name: None,
26668            signal_arguments: None,
26669            workflow_update_id: None,
26670            update_name: None,
26671            lease_owner: Some("rust-worker".to_string()),
26672        }
26673    }
26674
26675    #[test]
26676    fn committed_child_result_replays_without_starting_a_duplicate() {
26677        let worker = child_parent_worker();
26678        let task = child_parent_task(
26679            "ChildRunCompleted",
26680            json!({
26681                "sequence": 1,
26682                "child_call_id": "call-child",
26683                "child_workflow_instance_id": "wf-child",
26684                "child_workflow_run_id": "run-child",
26685                "child_workflow_type": "python.child",
26686                "payload_codec": DEFAULT_CODEC,
26687                "result": fixture_envelope(json!({"from":"python","ok":true})),
26688            }),
26689        );
26690
26691        for _restart in 0..2 {
26692            let commands = worker
26693                .execute_workflow_task(task.clone())
26694                .expect("replayed parent task");
26695            assert_eq!(commands.len(), 1);
26696            assert_eq!(commands[0]["type"], "complete_workflow");
26697            assert!(!commands
26698                .iter()
26699                .any(|command| command["type"] == "start_child_workflow"));
26700            let output =
26701                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26702            assert_eq!(output["parent_workflow_id"], "wf-parent");
26703            assert_eq!(output["parent_run_id"], "run-parent");
26704            assert_eq!(output["child_workflow_id"], "wf-child");
26705            assert_eq!(output["child_run_id"], "run-child");
26706            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26707        }
26708    }
26709
26710    #[test]
26711    fn typed_child_arguments_and_results_survive_replay() {
26712        let client = Client::new("http://127.0.0.1:8080").expect("client");
26713        let mut worker = Worker::new(client, "rust-parent-workers");
26714        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26715            let child = ctx
26716                .start_child_workflow_avro_value(
26717                    "python.typed-child",
26718                    ChildWorkflowOptions::new("python-workers"),
26719                    AvroValue::Array(vec![typed_fidelity_probe()]),
26720                )
26721                .await?;
26722            Ok(child.result)
26723        });
26724
26725        let initial = worker
26726            .execute_workflow_task(workflow_task(
26727                "rust.typed-parent",
26728                Vec::new(),
26729                DEFAULT_CODEC,
26730            ))
26731            .expect("typed child start");
26732        assert_eq!(initial[0]["type"], "start_child_workflow");
26733        assert_eq!(
26734            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26735                .expect("typed child arguments"),
26736            AvroValue::Array(vec![typed_fidelity_probe()])
26737        );
26738
26739        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26740            .expect("typed child result");
26741        let task = workflow_task(
26742            "rust.typed-parent",
26743            vec![
26744                history_event(
26745                    "ChildWorkflowScheduled",
26746                    json!({
26747                        "sequence": 1,
26748                        "child_call_id": "call-typed",
26749                        "child_workflow_instance_id": "wf-child",
26750                        "child_workflow_run_id": "run-child",
26751                        "child_workflow_type": "python.typed-child",
26752                    }),
26753                ),
26754                history_event(
26755                    "ChildRunCompleted",
26756                    json!({
26757                        "sequence": 1,
26758                        "child_call_id": "call-typed",
26759                        "child_workflow_instance_id": "wf-child",
26760                        "child_workflow_run_id": "run-child",
26761                        "child_workflow_type": "python.typed-child",
26762                        "payload_codec": DEFAULT_CODEC,
26763                        "result": result,
26764                    }),
26765                ),
26766            ],
26767            DEFAULT_CODEC,
26768        );
26769
26770        let commands = worker
26771            .execute_workflow_task(task)
26772            .expect("typed child replay");
26773        assert_eq!(commands[0]["type"], "complete_workflow");
26774        assert_eq!(
26775            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26776                .expect("typed parent result"),
26777            typed_fidelity_probe()
26778        );
26779    }
26780
26781    #[test]
26782    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26783        let worker = child_parent_worker();
26784        let mut task = child_parent_task("unused", Value::Null);
26785        task.history_events.truncate(1);
26786        task.total_history_events = Some(1);
26787
26788        for _redelivery_or_restart in 0..2 {
26789            let commands = worker
26790                .execute_workflow_task(task.clone())
26791                .expect("recorded child remains pending");
26792            assert!(
26793                commands.is_empty(),
26794                "recorded pending child must not be started again"
26795            );
26796        }
26797    }
26798
26799    #[test]
26800    fn child_cancellation_becomes_stable_parent_failure_command() {
26801        let worker = child_parent_worker();
26802        let task = child_parent_task(
26803            "ChildRunCancelled",
26804            json!({
26805                "sequence": 1,
26806                "child_workflow_instance_id": "wf-child",
26807                "child_workflow_run_id": "run-child",
26808                "child_workflow_type": "python.child",
26809                "failure_id": "failure-child",
26810                "failure_category": "cancelled",
26811                "message": "cancelled by parent-close policy",
26812            }),
26813        );
26814
26815        let commands = worker
26816            .execute_workflow_task(task)
26817            .expect("parent settlement");
26818        assert_eq!(commands.len(), 1);
26819        assert_eq!(commands[0]["type"], "fail_workflow");
26820        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26821        assert_eq!(
26822            commands[0]["exception"]["properties"]["reason"],
26823            "cancelled"
26824        );
26825        assert_eq!(
26826            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26827            "run-child"
26828        );
26829    }
26830
26831    #[test]
26832    fn workflow_can_handle_typed_child_failure() {
26833        let client = Client::new("http://127.0.0.1:8080").expect("client");
26834        let mut worker = Worker::new(client, "rust-parent-workers");
26835        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26836            match ctx
26837                .start_child_workflow(
26838                    "python.child",
26839                    ChildWorkflowOptions::new("python-child-workers"),
26840                    json!([]),
26841                )
26842                .await
26843            {
26844                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26845                    "reason": failure.reason,
26846                    "failure_id": failure.failure_id,
26847                    "exception_class": failure.exception_class,
26848                    "child_run_id": failure.child_workflow_run_id,
26849                })),
26850                Err(error) => Err(error),
26851                Ok(_) => Err(Error::WorkerLoop(
26852                    "child unexpectedly succeeded".to_string(),
26853                )),
26854            }
26855        });
26856        let mut task = child_parent_task(
26857            "ChildRunFailed",
26858            json!({
26859                "sequence": 1,
26860                "child_workflow_instance_id": "wf-child",
26861                "child_workflow_run_id": "run-child",
26862                "child_workflow_type": "python.child",
26863                "failure_id": "failure-child",
26864                "failure_category": "child_workflow",
26865                "message": "payment rejected",
26866                "exception": {
26867                    "type": "PaymentRejected",
26868                    "class": "payments.PaymentRejected",
26869                    "message": "payment rejected"
26870                }
26871            }),
26872        );
26873        task.workflow_type = "rust.handled-parent".to_string();
26874        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26875
26876        let commands = worker.execute_workflow_task(task).expect("handled failure");
26877        assert_eq!(commands[0]["type"], "complete_workflow");
26878        let output =
26879            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26880        assert_eq!(output["reason"], "child_workflow");
26881        assert_eq!(output["failure_id"], "failure-child");
26882        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26883        assert_eq!(output["child_run_id"], "run-child");
26884    }
26885
26886    #[test]
26887    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26888        let client = Client::new("http://127.0.0.1:8080").expect("client");
26889        let mut worker = Worker::new(client, "rust-workers");
26890
26891        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26892            let signal = ctx.wait_signal("start").await?;
26893            let name = signal
26894                .first()
26895                .and_then(|value| value.as_str())
26896                .unwrap_or("world");
26897            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26898            Ok(json!({
26899                "greeting": greeting,
26900                "language": "rust"
26901            }))
26902        });
26903
26904        let signal_arguments =
26905            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26906        let task = WorkflowTask {
26907            task_id: "wft-rust-signal-1".to_string(),
26908            observability_context: None,
26909            dispatch_observability_context: None,
26910            observability_links: None,
26911            workflow_command_id: None,
26912            workflow_id: Some("wf-rust-hello".to_string()),
26913            run_id: Some("run-rust-hello".to_string()),
26914            workflow_type: "rust.hello_workflow".to_string(),
26915            cancel_requested: false,
26916            payload_codec: DEFAULT_CODEC.to_string(),
26917            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26918            history_events: vec![HistoryEvent {
26919                event_type: "SignalReceived".to_string(),
26920                payload: json!({
26921                    "signal_id": "sig-rust-1",
26922                    "signal_name": "start"
26923                }),
26924                raw: HashMap::new(),
26925            }],
26926            total_history_events: Some(1),
26927            history_size_bytes: None,
26928            continue_as_new_recommended: None,
26929            history_budget_pressure: None,
26930            next_history_page_token: None,
26931            workflow_task_attempt: 1,
26932            workflow_signal_id: Some("sig-rust-1".to_string()),
26933            signal_name: Some("start".to_string()),
26934            signal_arguments: Some(signal_arguments),
26935            workflow_update_id: None,
26936            update_name: None,
26937            lease_owner: Some("rust-worker".to_string()),
26938        };
26939
26940        let commands = worker.execute_workflow_task(task).expect("workflow task");
26941
26942        assert_eq!(commands.len(), 1);
26943        assert_eq!(commands[0]["type"], "schedule_activity");
26944        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26945        assert_eq!(
26946            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
26947            json!(["Rust"])
26948        );
26949    }
26950
26951    #[test]
26952    fn workflow_task_appends_paginated_history_events() {
26953        let mut task = WorkflowTask {
26954            task_id: "wft-rust-pages-1".to_string(),
26955            observability_context: None,
26956            dispatch_observability_context: None,
26957            observability_links: None,
26958            workflow_command_id: None,
26959            workflow_id: Some("wf-rust-pages".to_string()),
26960            run_id: Some("run-rust-pages".to_string()),
26961            workflow_type: "rust.hello_workflow".to_string(),
26962            cancel_requested: false,
26963            payload_codec: DEFAULT_CODEC.to_string(),
26964            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26965            history_events: vec![HistoryEvent {
26966                event_type: "WorkflowStarted".to_string(),
26967                payload: json!({}),
26968                raw: HashMap::new(),
26969            }],
26970            total_history_events: Some(3),
26971            history_size_bytes: None,
26972            continue_as_new_recommended: None,
26973            history_budget_pressure: None,
26974            next_history_page_token: Some("MQ==".to_string()),
26975            workflow_task_attempt: 1,
26976            workflow_signal_id: None,
26977            signal_name: None,
26978            signal_arguments: None,
26979            workflow_update_id: None,
26980            update_name: None,
26981            lease_owner: Some("rust-worker".to_string()),
26982        };
26983
26984        task.append_history_page(WorkflowTaskHistoryPage {
26985            history_events: vec![
26986                HistoryEvent {
26987                    event_type: "SignalReceived".to_string(),
26988                    payload: json!({
26989                        "signal_id": "sig-rust-1",
26990                        "signal_name": "start",
26991                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
26992                            .expect("signal arguments")
26993                    }),
26994                    raw: HashMap::new(),
26995                },
26996                HistoryEvent {
26997                    event_type: "MarkerRecorded".to_string(),
26998                    payload: json!({"sequence": 3}),
26999                    raw: HashMap::new(),
27000                },
27001            ],
27002            total_history_events: Some(3),
27003            next_history_page_token: None,
27004        });
27005
27006        assert_eq!(task.history_events.len(), 3);
27007        assert_eq!(task.total_history_events, Some(3));
27008        assert_eq!(task.next_history_page_token, None);
27009
27010        let signal = task
27011            .history_events
27012            .iter()
27013            .find(|event| event.event_type == "SignalReceived")
27014            .expect("signal event");
27015        assert_eq!(
27016            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
27017            vec![AvroValue::String("Rust".to_string())]
27018        );
27019    }
27020
27021    #[tokio::test]
27022    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
27023        let client = Client::new("http://127.0.0.1:8080").expect("client");
27024        let mut worker = Worker::new(client, "rust-workers");
27025        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27026        worker.register_query("counter", "current", |ctx, _args| async move {
27027            let mut count = 0_i64;
27028            for signal in ctx.signal_events() {
27029                let value = signal
27030                    .arguments
27031                    .first()
27032                    .and_then(Value::as_i64)
27033                    .unwrap_or_default();
27034                match signal.name.as_str() {
27035                    "increment" => count += value,
27036                    "set" => count = value,
27037                    _ => {}
27038                }
27039            }
27040            Ok(json!(count))
27041        });
27042
27043        let task = QueryTask {
27044            query_task_id: "query-rust-counter".to_string(),
27045            observability_context: None,
27046            dispatch_observability_context: None,
27047            observability_links: None,
27048            query_task_attempt: 1,
27049            lease_owner: Some("rust-worker".to_string()),
27050            workflow_id: Some("counter-1".to_string()),
27051            run_id: Some("run-counter-1".to_string()),
27052            workflow_type: "counter".to_string(),
27053            query_name: "current".to_string(),
27054            payload_codec: DEFAULT_CODEC.to_string(),
27055            workflow_arguments: Some(
27056                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27057            ),
27058            query_arguments: Some(
27059                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
27060            ),
27061            history_events: vec![
27062                HistoryEvent {
27063                    event_type: "SignalReceived".to_string(),
27064                    payload: json!({
27065                        "signal_id": "php-signal-1",
27066                        "signal_name": "increment",
27067                        "workflow_sequence": 1,
27068                        "payload_codec": DEFAULT_CODEC,
27069                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
27070                    }),
27071                    raw: HashMap::new(),
27072                },
27073                HistoryEvent {
27074                    event_type: "SignalReceived".to_string(),
27075                    payload: json!({
27076                        "signal_id": "python-signal-2",
27077                        "signal_name": "increment",
27078                        "workflow_sequence": 2,
27079                        "payload_codec": DEFAULT_CODEC,
27080                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
27081                    }),
27082                    raw: HashMap::new(),
27083                },
27084                HistoryEvent {
27085                    event_type: "SignalReceived".to_string(),
27086                    payload: json!({
27087                        "signal_id": "rust-signal-3",
27088                        "signal_name": "set",
27089                        "workflow_sequence": 3,
27090                        "payload_codec": DEFAULT_CODEC,
27091                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
27092                    }),
27093                    raw: HashMap::new(),
27094                },
27095            ],
27096            history_export: None,
27097            run_status: Some("completed".to_string()),
27098        };
27099
27100        let result = worker.execute_query_task(task).await.expect("query result");
27101        assert_eq!(result.into_json().expect("query projection"), json!(0));
27102    }
27103
27104    #[tokio::test]
27105    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
27106        let worker = replay_counter_worker();
27107        let running_history = json!([
27108            {
27109                "type": "ActivityCompleted",
27110                "payload": {
27111                    "sequence": 1,
27112                    "activity_type": "load-counter",
27113                    "payload_codec": DEFAULT_CODEC,
27114                    "result": fixture_envelope(json!("loaded"))
27115                }
27116            },
27117            {
27118                "type": "SignalWaitOpened",
27119                "payload": {
27120                    "sequence": 3,
27121                    "signal_name": "increment"
27122                }
27123            },
27124            {
27125                "type": "SignalReceived",
27126                "payload": {
27127                    "signal_id": "signal-3",
27128                    "signal_name": "increment",
27129                    "workflow_sequence": 2,
27130                    "payload_codec": DEFAULT_CODEC,
27131                    "arguments": fixture_envelope(json!([3]))
27132                }
27133            },
27134            {
27135                "type": "SignalApplied",
27136                "payload": {
27137                    "sequence": 3,
27138                    "signal_id": "signal-3",
27139                    "signal_name": "increment",
27140                    "payload_codec": DEFAULT_CODEC,
27141                    "value": fixture_envelope(json!([3]))
27142                }
27143            }
27144        ]);
27145
27146        let running = worker
27147            .execute_query_task(replay_counter_query(
27148                "current",
27149                running_history.clone(),
27150                "running",
27151            ))
27152            .await
27153            .expect("running replay query");
27154        assert_eq!(
27155            running.clone().into_json().expect("query projection"),
27156            json!({"loaded": "loaded", "count": 3, "finished": false})
27157        );
27158
27159        let detached = worker
27160            .execute_query_task(replay_counter_query(
27161                "detached-mutation",
27162                running_history.clone(),
27163                "running",
27164            ))
27165            .await
27166            .expect("query mutates only its detached state clone");
27167        assert_eq!(detached.into_json().expect("query projection"), json!(999));
27168        let failed = worker
27169            .execute_query_task(replay_counter_query(
27170                "failed-mutation",
27171                running_history.clone(),
27172                "running",
27173            ))
27174            .await
27175            .expect_err("failed query");
27176        assert_eq!(failed.reason, "query_rejected");
27177        let unchanged = worker
27178            .execute_query_task(replay_counter_query("current", running_history, "running"))
27179            .await
27180            .expect("later query reconstructs unchanged state");
27181        assert_eq!(unchanged, running);
27182
27183        let restarted_worker = replay_counter_worker();
27184        let empty_arguments = fixture_envelope(json!([]));
27185        let loaded_result = fixture_envelope(json!("loaded"));
27186        let signal_three = fixture_blob(json!([3]));
27187        let signal_five = fixture_blob(json!([5]));
27188        let restarted_task: QueryTask = serde_json::from_value(json!({
27189            "query_task_id": "query-after-restart",
27190            "workflow_id": "counter-1",
27191            "run_id": "run-counter-1",
27192            "workflow_type": "replay-counter",
27193            "query_name": "current",
27194            "payload_codec": DEFAULT_CODEC,
27195            "workflow_arguments": empty_arguments.clone(),
27196            "query_arguments": empty_arguments,
27197            "history_events": [],
27198            "history_export": {
27199                "payloads": {"codec": DEFAULT_CODEC},
27200                "history_events": [
27201                    {
27202                        "type": "ActivityCompleted",
27203                        "payload": {
27204                            "sequence": 1,
27205                            "activity_type": "load-counter",
27206                            "payload_codec": DEFAULT_CODEC,
27207                            "result": null
27208                        }
27209                    },
27210                    {
27211                        "type": "SignalWaitOpened",
27212                        "payload": {
27213                            "sequence": 3,
27214                            "signal_name": "increment"
27215                        }
27216                    },
27217                    {
27218                        "type": "SignalReceived",
27219                        "payload": {
27220                            "signal_id": "signal-3",
27221                            "signal_name": "increment",
27222                            "workflow_sequence": 2
27223                        }
27224                    },
27225                    {
27226                        "type": "SignalApplied",
27227                        "payload": {
27228                            "sequence": 3,
27229                            "signal_id": "signal-3",
27230                            "signal_name": "increment"
27231                        }
27232                    },
27233                    {
27234                        "type": "SignalWaitOpened",
27235                        "payload": {
27236                            "sequence": 5,
27237                            "signal_name": "increment"
27238                        }
27239                    },
27240                    {
27241                        "type": "SignalReceived",
27242                        "payload": {
27243                            "signal_id": "signal-5",
27244                            "signal_name": "increment",
27245                            "workflow_sequence": 4
27246                        }
27247                    },
27248                    {
27249                        "type": "SignalApplied",
27250                        "payload": {
27251                            "sequence": 5,
27252                            "signal_id": "signal-5",
27253                            "signal_name": "increment"
27254                        }
27255                    }
27256                ],
27257                "activities": [{
27258                    "sequence": 1,
27259                    "activity_type": "load-counter",
27260                    "payload_codec": DEFAULT_CODEC,
27261                    "result": loaded_result
27262                }],
27263                "signals": [
27264                    {
27265                        "id": "signal-3",
27266                        "name": "increment",
27267                        "workflow_sequence": 2,
27268                        "payload_codec": DEFAULT_CODEC,
27269                        "arguments": signal_three
27270                    },
27271                    {
27272                        "id": "signal-5",
27273                        "name": "increment",
27274                        "workflow_sequence": 4,
27275                        "payload_codec": DEFAULT_CODEC,
27276                        "arguments": signal_five
27277                    }
27278                ]
27279            },
27280            "run_status": "completed"
27281        }))
27282        .expect("cold replay query task");
27283        let completed = restarted_worker
27284            .execute_query_task(restarted_task)
27285            .await
27286            .expect("completed cold replay query");
27287        assert_eq!(
27288            completed.into_json().expect("query projection"),
27289            json!({"loaded": "loaded", "count": 8, "finished": true})
27290        );
27291    }
27292
27293    #[tokio::test]
27294    async fn replayed_query_replay_failures_are_machine_readable() {
27295        let worker = replay_counter_worker();
27296        let task = replay_counter_query(
27297            "current",
27298            json!([{
27299                "type": "ActivityCompleted",
27300                "payload": {
27301                    "sequence": 1,
27302                    "payload_codec": DEFAULT_CODEC,
27303                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
27304                }
27305            }]),
27306            "running",
27307        );
27308        let failure = worker
27309            .execute_query_task(task)
27310            .await
27311            .expect_err("invalid replay history payload");
27312        assert_eq!(failure.reason, "query_payload_decode_failed");
27313        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
27314        assert!(failure.message.contains("invalid_payload_framing"));
27315    }
27316
27317    #[tokio::test]
27318    async fn query_task_restores_compact_history_from_export() {
27319        let client = Client::new("http://127.0.0.1:8080").expect("client");
27320        let mut worker = Worker::new(client, "rust-workers");
27321        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27322        worker.register_query("counter", "current", |ctx, _args| async move {
27323            Ok(json!(ctx.signals("increment")[0][0]))
27324        });
27325        let empty_arguments = fixture_envelope(json!([]));
27326        let exported_signal = fixture_blob(json!([9]));
27327        let task: QueryTask = serde_json::from_value(json!({
27328            "query_task_id": "query-export",
27329            "workflow_type": "counter",
27330            "query_name": "current",
27331            "payload_codec": DEFAULT_CODEC,
27332            "workflow_arguments": empty_arguments.clone(),
27333            "query_arguments": empty_arguments,
27334            "history_events": [],
27335            "history_export": {
27336                "payloads": {"codec": DEFAULT_CODEC},
27337                "history_events": [{
27338                    "type": "SignalReceived",
27339                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
27340                }],
27341                "signals": [{
27342                    "id": "signal-export",
27343                    "name": "increment",
27344                    "status": "applied",
27345                    "workflow_sequence": 1,
27346                    "payload_codec": DEFAULT_CODEC,
27347                    "arguments": exported_signal
27348                }]
27349            }
27350        }))
27351        .expect("query task");
27352
27353        let result = worker.execute_query_task(task).await.expect("query result");
27354        assert_eq!(result.into_json().expect("query projection"), json!(9));
27355    }
27356
27357    #[tokio::test]
27358    async fn query_task_failures_have_stable_reasons() {
27359        let client = Client::new("http://127.0.0.1:8080").expect("client");
27360        let mut worker = Worker::new(client, "rust-workers");
27361        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27362        worker.register_query(
27363            "counter",
27364            "current",
27365            |_ctx, _args| async move { Ok(json!(0)) },
27366        );
27367
27368        let base_task = QueryTask {
27369            query_task_id: "query-errors".to_string(),
27370            observability_context: None,
27371            dispatch_observability_context: None,
27372            observability_links: None,
27373            query_task_attempt: 1,
27374            lease_owner: None,
27375            workflow_id: Some("counter-errors".to_string()),
27376            run_id: Some("run-errors".to_string()),
27377            workflow_type: "counter".to_string(),
27378            query_name: "missing".to_string(),
27379            payload_codec: DEFAULT_CODEC.to_string(),
27380            workflow_arguments: Some(fixture_envelope(json!([]))),
27381            query_arguments: Some(fixture_envelope(json!([]))),
27382            history_events: Vec::new(),
27383            history_export: None,
27384            run_status: Some("running".to_string()),
27385        };
27386
27387        let unknown = worker
27388            .execute_query_task(base_task.clone())
27389            .await
27390            .expect_err("unknown query");
27391        assert_eq!(unknown.reason, "rejected_unknown_query");
27392
27393        let mut malformed = base_task;
27394        malformed.query_name = "current".to_string();
27395        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
27396        let malformed = worker
27397            .execute_query_task(malformed)
27398            .await
27399            .expect_err("malformed payload");
27400        assert_eq!(malformed.reason, "query_payload_decode_failed");
27401
27402        let client = Client::new("http://127.0.0.1:8080").expect("client");
27403        let mut unavailable_worker = Worker::new(client, "rust-workers");
27404        unavailable_worker
27405            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27406        let empty_arguments = fixture_envelope(json!([]));
27407        let unavailable_task: QueryTask = serde_json::from_value(json!({
27408            "query_task_id": "query-unavailable",
27409            "workflow_type": "counter",
27410            "query_name": "current",
27411            "payload_codec": DEFAULT_CODEC,
27412            "workflow_arguments": empty_arguments.clone(),
27413            "query_arguments": empty_arguments
27414        }))
27415        .expect("query task");
27416        let unavailable = unavailable_worker
27417            .execute_query_task(unavailable_task)
27418            .await
27419            .expect_err("query handler unavailable");
27420        assert_eq!(unavailable.reason, "query_handler_unavailable");
27421    }
27422
27423    #[tokio::test]
27424    async fn client_query_decodes_result_and_typed_failure() {
27425        let server = MockWorkerServer::start();
27426        let client = Client::builder(server.base_url())
27427            .timeout(Duration::from_secs(2))
27428            .build()
27429            .expect("client");
27430
27431        let result = client
27432            .query_workflow("counter-1", "current", json!([]))
27433            .await
27434            .expect("query result");
27435        assert_eq!(result, json!({"count": 8}));
27436
27437        let error = client
27438            .query_workflow("counter-1", "missing", json!([]))
27439            .await
27440            .expect_err("unknown query");
27441        let Error::QueryFailed(failure) = error else {
27442            panic!("expected typed query failure");
27443        };
27444        assert_eq!(failure.status, 404);
27445        assert_eq!(failure.reason, "rejected_unknown_query");
27446    }
27447
27448    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
27449    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
27450    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
27451
27452    #[cfg(feature = "telemetry")]
27453    #[tokio::test]
27454    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
27455        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27456        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
27457        PHASE.store(0, Ordering::SeqCst);
27458        use opentelemetry::{
27459            propagation::TextMapPropagator,
27460            trace::{FutureExt, TracerProvider},
27461        };
27462        use opentelemetry_sdk::propagation::TraceContextPropagator;
27463        struct Restore;
27464        impl Drop for Restore {
27465            fn drop(&mut self) {
27466                opentelemetry::global::set_text_map_propagator(
27467                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27468                );
27469            }
27470        }
27471        let _restore = Restore;
27472        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
27473        let headers = HashMap::from([(
27474            "traceparent".to_string(),
27475            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
27476        )]);
27477        let parent = TraceContextPropagator::new().extract(&headers);
27478        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27479            request_override: Some(|path, body, _number| {
27480                if path == "/api/cluster/info" {
27481                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
27482                        ("503 Service Unavailable", "{}".into())
27483                    } else {
27484                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27485                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
27486                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27487                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27488                        }}}}).to_string())
27489                    });
27490                }
27491                let body: Value = serde_json::from_str(body).ok()?;
27492                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
27493                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
27494                    "result": "original"}).to_string()))
27495            }),
27496            ..MockWorkerBehavior::default()
27497        });
27498        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
27499        let client = Client::new(server.base_url()).unwrap().with_telemetry(
27500            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
27501        );
27502        let input = json!([{"observability_context": {"business": "preserved"}}]);
27503        async {
27504            client
27505                .start_workflow("orders", "orders", "order", &input)
27506                .await
27507                .unwrap();
27508            assert!(server
27509                .request_body("/api/workflows")
27510                .get("observability_context")
27511                .is_none());
27512            client.cluster_info().await.unwrap();
27513            client
27514                .start_workflow("orders", "orders", "order", &input)
27515                .await
27516                .unwrap();
27517            client
27518                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
27519                .await
27520                .unwrap();
27521            client
27522                .update_workflow("order", "status", &input, Some("update-original"))
27523                .await
27524                .unwrap();
27525            client
27526                .cancel_workflow("order", WorkflowCommandOptions::default())
27527                .await
27528                .unwrap();
27529            for path in [
27530                "/api/workflows",
27531                "/api/workflows/order/signal/ready",
27532                "/api/workflows/order/update/status",
27533                "/api/workflows/order/cancel",
27534            ] {
27535                let bodies = server.request_bodies(path);
27536                let body = bodies.last().unwrap();
27537                assert_eq!(
27538                    body["observability_context"]["carrier"]["traceparent"],
27539                    headers["traceparent"]
27540                );
27541                assert!(body["observability_context"]["carrier"]
27542                    .get("baggage")
27543                    .is_none());
27544            }
27545            let starts = server.request_bodies("/api/workflows");
27546            assert_eq!(
27547                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
27548                input
27549            );
27550            assert_eq!(
27551                server.request_body("/api/workflows/order/signal/ready")["request_id"],
27552                "signal-original"
27553            );
27554            assert_eq!(
27555                server.request_body("/api/workflows/order/update/status")["request_id"],
27556                "update-original"
27557            );
27558            PHASE.store(1, Ordering::SeqCst);
27559            client.cluster_info().await.unwrap();
27560            client
27561                .start_workflow("orders", "orders", "order", &input)
27562                .await
27563                .unwrap();
27564            assert!(server
27565                .request_bodies("/api/workflows")
27566                .last()
27567                .unwrap()
27568                .get("observability_context")
27569                .is_none());
27570            PHASE.store(2, Ordering::SeqCst);
27571            assert!(client.cluster_info().await.is_err());
27572            let before = server.captured_paths().len();
27573            client
27574                .start_workflow("orders", "orders", "order", &input)
27575                .await
27576                .unwrap();
27577            assert_eq!(server.captured_paths().len(), before + 1);
27578            assert!(server
27579                .request_bodies("/api/workflows")
27580                .last()
27581                .unwrap()
27582                .get("observability_context")
27583                .is_none());
27584        }
27585        .with_context(parent)
27586        .await;
27587    }
27588
27589    #[cfg(feature = "telemetry")]
27590    fn observability_worker_server(
27591        path: &str,
27592        _body: &str,
27593        _: usize,
27594    ) -> Option<(&'static str, String)> {
27595        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27596            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
27597                        "baggage": "credential=private"}});
27598        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27599            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
27600        if path == "/api/cluster/info" {
27601            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27602                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
27603                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27604                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27605            }}}}).to_string()));
27606        }
27607        if path.ends_with("/complete") {
27608            return Some(("200 OK", json!({"recorded": true}).to_string()));
27609        }
27610        let task_id = match path {
27611            "/api/worker/workflow-tasks/poll" => "workflow-task",
27612            "/api/worker/activity-tasks/poll" => "activity-task",
27613            "/api/worker/query-tasks/poll" => "query-task",
27614            _ => return None,
27615        };
27616        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
27617        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
27618        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
27619        "activity_type": "wire.activity", "activity_execution_id": "activity",
27620        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
27621        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
27622        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
27623        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
27624        "query_arguments": input, "history_events": [], "observability_context": context,
27625        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
27626            "task_id": task_id, "context": link_context},
27627        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
27628            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
27629                {"kind": "command", "command_id": "accepted-command", "context": link_context},
27630                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
27631                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
27632                 "event_type": "WorkflowCancelled", "context": link_context}
27633            ]}});
27634        if task_id == "workflow-task" {
27635            task["arguments"] = encode_value_envelope(
27636                &json!([{"observability_context": {"business": "preserved"}}]),
27637                DEFAULT_CODEC,
27638            )
27639            .unwrap();
27640        }
27641        Some((
27642            "200 OK",
27643            json!({"task": task, "poll_status": "leased"}).to_string(),
27644        ))
27645    }
27646
27647    #[cfg(feature = "telemetry")]
27648    #[tokio::test]
27649    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
27650    {
27651        use opentelemetry::trace::TracerProvider;
27652        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27653        opentelemetry::global::set_text_map_propagator(
27654            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
27655        );
27656        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27657        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27658            .with_simple_exporter(exporter.clone())
27659            .build();
27660        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
27661        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27662            request_override: Some(observability_worker_server),
27663            ..MockWorkerBehavior::default()
27664        });
27665        let client = Client::builder(server.base_url())
27666            .namespace("shipping")
27667            .build()
27668            .unwrap();
27669        client.cluster_info().await.unwrap();
27670        let mut worker = Worker::new(client, "shipping")
27671            .worker_id("test-worker")
27672            .telemetry(telemetry);
27673        worker.register_workflow("wire.workflow", |ctx, input| async move {
27674            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
27675            assert_eq!(
27676                input,
27677                json!([{"observability_context": {"business": "preserved"}}])
27678            );
27679            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
27680                .await?;
27681            Ok(Value::Null)
27682        });
27683        worker.register_activity("wire.activity", |_, _| async {
27684            let fields = telemetry::current_log_context();
27685            assert_eq!(fields["workflow_run_id"], "run");
27686            assert_eq!(fields["activity_id"], "activity");
27687            assert_eq!(fields["activity_attempt_id"], "attempt");
27688            assert_eq!(fields["activity_attempt_number"], "3");
27689            Ok(json!("original-result"))
27690        });
27691        worker.register_query("wire.workflow", "state", |_, _| async {
27692            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
27693            Ok(json!("original-query"))
27694        });
27695        assert_eq!(worker.run_once().await.unwrap(), 3);
27696        let spans = exporter.get_finished_spans().unwrap();
27697        assert_eq!(spans.len(), 4);
27698        let origin_trace = "12345678901234567890123456789012";
27699        for span in spans
27700            .iter()
27701            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
27702        {
27703            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
27704            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
27705            assert_eq!(span.links.len(), 3);
27706            assert!(!format!("{:?}", span.attributes).contains("credential"));
27707        }
27708        let task = spans
27709            .iter()
27710            .find(|span| span.name.as_ref() == "durable.workflow.task")
27711            .unwrap();
27712        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
27713        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
27714        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
27715            .as_str()
27716            .unwrap();
27717        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
27718        assert!(telemetry::current_log_context().is_empty());
27719        opentelemetry::global::set_text_map_propagator(
27720            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27721        );
27722    }
27723
27724    #[cfg(feature = "telemetry")]
27725    #[tokio::test]
27726    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
27727        use opentelemetry::trace::TracerProvider;
27728        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
27729        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
27730            let (status, reply) = observability_worker_server(path, body, count)?;
27731            if path != "/api/worker/query-tasks/poll" {
27732                return Some((status, reply));
27733            }
27734            let mut reply: Value = serde_json::from_str(&reply).unwrap();
27735            match REFUSAL.load(Ordering::SeqCst) {
27736                0 => reply["task"]["lease_owner"] = json!("other-worker"),
27737                1 => reply["task"]["query_task_attempt"] = json!(0),
27738                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
27739            }
27740            Some((status, reply.to_string()))
27741        }
27742        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27743        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27744            .with_simple_exporter(exporter.clone())
27745            .build();
27746        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27747            request_override: Some(refused_query),
27748            ..MockWorkerBehavior::default()
27749        });
27750        let client = Client::builder(server.base_url())
27751            .namespace("shipping")
27752            .build()
27753            .unwrap();
27754        client.cluster_info().await.unwrap();
27755        let mut worker = Worker::new(client, "shipping")
27756            .worker_id("test-worker")
27757            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
27758                provider.tracer("test"),
27759            ));
27760        let calls = Arc::new(AtomicUsize::new(0));
27761        let query_calls = calls.clone();
27762        worker.register_query("wire.workflow", "state", move |_, _| {
27763            query_calls.fetch_add(1, Ordering::SeqCst);
27764            async { Ok(Value::Null) }
27765        });
27766        for refusal in 0..3 {
27767            REFUSAL.store(refusal, Ordering::SeqCst);
27768            assert!(matches!(
27769                worker.poll_query_once().await.unwrap(),
27770                ManagedPollOutcome::Handled
27771            ));
27772            assert_eq!(calls.load(Ordering::SeqCst), 0);
27773            assert!(exporter.get_finished_spans().unwrap().is_empty());
27774            assert!(telemetry::current_log_context().is_empty());
27775        }
27776        assert!(!server
27777            .captured_paths()
27778            .iter()
27779            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
27780    }
27781
27782    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
27783        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
27784            return None;
27785        }
27786        serde_json::from_str(body).ok()
27787    }
27788
27789    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
27790    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27791        let request = keyed_command_request(path, body)?;
27792        let mut receipt = json!({
27793            "outcome": "accepted",
27794            "command_status": "accepted",
27795            "command_id": "cmd-keyed-1",
27796            "request_id": request["request_id"],
27797            "retained": false,
27798            "intent_verified": true,
27799        });
27800        if path == KEYED_UPDATE_PATH {
27801            receipt["update_id"] = json!("upd-keyed-1");
27802            receipt["result_envelope"] =
27803                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
27804        }
27805        Some(("202 Accepted", receipt.to_string()))
27806    }
27807
27808    /// A Server released before #216: accepts the body field but echoes nothing.
27809    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27810        keyed_command_request(path, body)?;
27811        Some((
27812            "202 Accepted",
27813            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
27814                .to_string(),
27815        ))
27816    }
27817
27818    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27819        let request = keyed_command_request(path, body)?;
27820        Some((
27821            "202 Accepted",
27822            json!({
27823                "outcome": "accepted",
27824                "command_status": "accepted",
27825                "command_id": "cmd-first",
27826                "request_id": request["request_id"],
27827                "retained": true,
27828                "intent_verified": true,
27829            })
27830            .to_string(),
27831        ))
27832    }
27833
27834    fn conflicting_command_server(
27835        path: &str,
27836        body: &str,
27837        _: usize,
27838    ) -> Option<(&'static str, String)> {
27839        let request = keyed_command_request(path, body)?;
27840        let retained_type = if path == KEYED_UPDATE_PATH {
27841            "update"
27842        } else {
27843            "signal"
27844        };
27845        Some((
27846            "409 Conflict",
27847            json!({
27848                "reason": "request_id_conflict",
27849                "message": format!("request id is retained for a different {retained_type} intent"),
27850                "request_id": request["request_id"],
27851                "retained_command_id": "cmd-retained-1",
27852                "retained_command_type": retained_type,
27853                "retained_outcome": "accepted",
27854                "conflict": ["arguments", "target"],
27855                "control_plane": {"operation": retained_type},
27856            })
27857            .to_string(),
27858        ))
27859    }
27860
27861    fn closed_run_command_server(
27862        path: &str,
27863        body: &str,
27864        _: usize,
27865    ) -> Option<(&'static str, String)> {
27866        let request = keyed_command_request(path, body)?;
27867        Some((
27868            "409 Conflict",
27869            json!({
27870                "reason": "run_not_active",
27871                "message": "run is closed",
27872                "request_id": request["request_id"],
27873            })
27874            .to_string(),
27875        ))
27876    }
27877
27878    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
27879        path == KEYED_SIGNAL_PATH && request_number == 1
27880    }
27881
27882    fn keyed_client(server: &MockWorkerServer) -> Client {
27883        Client::builder(server.base_url())
27884            .timeout(Duration::from_secs(2))
27885            .build()
27886            .expect("client")
27887    }
27888
27889    fn keyed_handle(client: &Client) -> WorkflowHandle {
27890        WorkflowHandle {
27891            client: client.clone(),
27892            workflow_id: "keyed-1".to_string(),
27893            run_id: Some("run-keyed-1".to_string()),
27894            workflow_type: "keyed".to_string(),
27895        }
27896    }
27897
27898    fn assert_generated_request_id(request_id: &str, prefix: &str) {
27899        let suffix = request_id
27900            .strip_prefix(prefix)
27901            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
27902        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
27903        assert!(
27904            suffix
27905                .bytes()
27906                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
27907            "lowercase hex suffix: {request_id:?}"
27908        );
27909        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
27910    }
27911
27912    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
27913        let headers = server.request_headers(path);
27914        assert!(!headers.is_empty(), "no request captured for {path}");
27915        for headers in headers {
27916            let header_names: Vec<String> = headers
27917                .lines()
27918                .skip(1)
27919                .filter_map(|line| line.split_once(':'))
27920                .map(|(name, _)| name.trim().to_ascii_lowercase())
27921                .collect();
27922            assert!(
27923                !header_names.iter().any(|name| name == "x-request-id"),
27924                "the caller command key is a body field, never an X-Request-Id header: {headers}"
27925            );
27926        }
27927    }
27928
27929    #[tokio::test]
27930    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
27931        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27932            request_override: Some(legacy_command_server),
27933            ..MockWorkerBehavior::default()
27934        });
27935        let client = keyed_client(&server);
27936
27937        let receipt = client
27938            .signal_workflow("keyed-1", "approve", json!(["ok"]))
27939            .await
27940            .expect("signal receipt");
27941
27942        let sent = server.request_body(KEYED_SIGNAL_PATH);
27943        let request_id = sent["request_id"].as_str().expect("generated request_id");
27944        assert_generated_request_id(request_id, "sdk-rust-signal-");
27945        assert_eq!(
27946            receipt,
27947            json!({
27948                "outcome": "accepted",
27949                "command_status": "accepted",
27950                "command_id": "cmd-legacy",
27951                "request_id": request_id,
27952            }),
27953            "the sent key is added when an older Server omits it"
27954        );
27955        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
27956
27957        let receipt = keyed_handle(&client)
27958            .signal_selected_run("approve", json!(["ok"]))
27959            .await
27960            .expect("selected-run signal receipt");
27961        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
27962        let run_request_id = run_sent["request_id"]
27963            .as_str()
27964            .expect("generated request_id");
27965        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
27966        assert_eq!(receipt["request_id"], run_request_id);
27967        assert_ne!(
27968            run_request_id, request_id,
27969            "each logical call gets its own key"
27970        );
27971        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
27972    }
27973
27974    #[tokio::test]
27975    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
27976        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27977            request_override: Some(keyed_command_server),
27978            ..MockWorkerBehavior::default()
27979        });
27980        let client = keyed_client(&server);
27981
27982        let result = client
27983            .update_workflow("keyed-1", "adjust", json!([1]), None)
27984            .await
27985            .expect("update result");
27986        assert_eq!(
27987            result,
27988            json!(42),
27989            "the decoded update result is returned unchanged"
27990        );
27991        let typed = client
27992            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
27993            .await
27994            .expect("typed update result");
27995        assert_eq!(typed, AvroValue::Long(42));
27996        keyed_handle(&client)
27997            .update("adjust", json!([1]), None)
27998            .await
27999            .expect("handle update result");
28000
28001        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
28002        assert_eq!(bodies.len(), 3);
28003        for body in &bodies {
28004            assert_generated_request_id(
28005                body["request_id"].as_str().expect("generated request_id"),
28006                "sdk-rust-update-",
28007            );
28008            assert_eq!(body["wait_for"], "completed");
28009        }
28010        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
28011        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
28012        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
28013    }
28014
28015    #[tokio::test]
28016    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
28017        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28018            request_override: Some(keyed_command_server),
28019            ..MockWorkerBehavior::default()
28020        });
28021        let client = keyed_client(&server);
28022        let handle = keyed_handle(&client);
28023
28024        let receipt = client
28025            .signal_workflow_with_request_id(
28026                "keyed-1",
28027                "approve",
28028                json!(["ok"]),
28029                "Order-42/approve",
28030            )
28031            .await
28032            .expect("signal receipt");
28033        assert_eq!(receipt["request_id"], "Order-42/approve");
28034        assert_eq!(receipt["retained"], false);
28035        assert_eq!(receipt["intent_verified"], true);
28036        handle
28037            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
28038            .await
28039            .expect("handle signal receipt");
28040        client
28041            .signal_workflow_run_with_request_id(
28042                "keyed-1",
28043                "run-keyed-1",
28044                "approve",
28045                json!(["ok"]),
28046                "run-signal-key",
28047            )
28048            .await
28049            .expect("selected-run signal receipt");
28050        handle
28051            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
28052            .await
28053            .expect("handle selected-run signal receipt");
28054        let result = client
28055            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
28056            .await
28057            .expect("update result");
28058        assert_eq!(result, json!(42));
28059        handle
28060            .update("adjust", json!([1]), Some("handle-update-key"))
28061            .await
28062            .expect("handle update result");
28063        handle
28064            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
28065            .await
28066            .expect("handle typed update result");
28067
28068        let signal_keys: Vec<Value> = server
28069            .request_bodies(KEYED_SIGNAL_PATH)
28070            .into_iter()
28071            .map(|body| body["request_id"].clone())
28072            .collect();
28073        assert_eq!(
28074            signal_keys,
28075            [json!("Order-42/approve"), json!("handle-signal-key")]
28076        );
28077        let run_signal_keys: Vec<Value> = server
28078            .request_bodies(KEYED_RUN_SIGNAL_PATH)
28079            .into_iter()
28080            .map(|body| body["request_id"].clone())
28081            .collect();
28082        assert_eq!(
28083            run_signal_keys,
28084            [json!("run-signal-key"), json!("handle-run-signal-key")]
28085        );
28086        let update_keys: Vec<Value> = server
28087            .request_bodies(KEYED_UPDATE_PATH)
28088            .into_iter()
28089            .map(|body| body["request_id"].clone())
28090            .collect();
28091        assert_eq!(
28092            update_keys,
28093            [
28094                json!("update-key"),
28095                json!("handle-update-key"),
28096                json!("handle-typed-update-key")
28097            ]
28098        );
28099        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
28100            assert_key_sent_only_in_body(&server, path);
28101        }
28102    }
28103
28104    #[tokio::test]
28105    async fn retained_receipts_are_returned_unchanged() {
28106        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28107            request_override: Some(retained_command_server),
28108            ..MockWorkerBehavior::default()
28109        });
28110        let client = keyed_client(&server);
28111
28112        let receipt = client
28113            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
28114            .await
28115            .expect("retained receipt");
28116
28117        assert_eq!(
28118            receipt,
28119            json!({
28120                "outcome": "accepted",
28121                "command_status": "accepted",
28122                "command_id": "cmd-first",
28123                "request_id": "retry-key",
28124                "retained": true,
28125                "intent_verified": true,
28126            })
28127        );
28128    }
28129
28130    #[tokio::test]
28131    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
28132        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28133            request_override: Some(conflicting_command_server),
28134            ..MockWorkerBehavior::default()
28135        });
28136        let client = keyed_client(&server);
28137
28138        let error = client
28139            .signal_workflow_with_request_id(
28140                "keyed-1",
28141                "approve",
28142                json!(["changed"]),
28143                "Order-42/approve",
28144            )
28145            .await
28146            .expect_err("different intent under a retained key");
28147        assert!(
28148            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
28149            "existing Error::Http matching keeps working: {error:?}"
28150        );
28151        assert!(error.is_request_id_conflict());
28152        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
28153        let conflict = error.request_id_conflict().expect("conflict details");
28154        assert_eq!(conflict.status, 409);
28155        assert_eq!(conflict.request_id, "Order-42/approve");
28156        assert_eq!(
28157            conflict.message,
28158            "request id is retained for a different signal intent"
28159        );
28160        assert_eq!(
28161            conflict.retained_command_id.as_deref(),
28162            Some("cmd-retained-1")
28163        );
28164        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
28165        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
28166        assert_eq!(conflict.conflict, ["arguments", "target"]);
28167        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
28168
28169        let error = client
28170            .update_workflow("keyed-1", "adjust", json!([2]), None)
28171            .await
28172            .expect_err("different intent under a retained generated key");
28173        let sent = server.request_body(KEYED_UPDATE_PATH);
28174        assert_eq!(
28175            error.request_id(),
28176            sent["request_id"].as_str().map(str::to_string)
28177        );
28178        assert_eq!(
28179            error
28180                .request_id_conflict()
28181                .expect("conflict details")
28182                .retained_command_type
28183                .as_deref(),
28184            Some("update")
28185        );
28186    }
28187
28188    #[tokio::test]
28189    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
28190        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28191            request_override: Some(closed_run_command_server),
28192            ..MockWorkerBehavior::default()
28193        });
28194        let client = keyed_client(&server);
28195
28196        let error = client
28197            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
28198            .await
28199            .expect_err("closed run");
28200
28201        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
28202        assert!(!error.is_request_id_conflict());
28203        assert_eq!(error.request_id_conflict(), None);
28204        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
28205    }
28206
28207    #[tokio::test]
28208    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
28209        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28210            request_override: Some(keyed_command_server),
28211            drop_request: Some(drop_first_keyed_signal),
28212            ..MockWorkerBehavior::default()
28213        });
28214        let client = keyed_client(&server);
28215        let request_id = Client::generate_signal_request_id();
28216
28217        let error = client
28218            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28219            .await
28220            .expect_err("connection closed before any response");
28221        assert!(
28222            matches!(error, Error::Transport(_)),
28223            "the transport variant is unchanged: {error:?}"
28224        );
28225        assert_eq!(
28226            error.request_id(),
28227            None,
28228            "nothing was echoed; the application holds the key it chose"
28229        );
28230
28231        let receipt = client
28232            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28233            .await
28234            .expect("manual retry with the same key");
28235        assert_eq!(receipt["request_id"], request_id);
28236        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
28237        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
28238        assert_eq!(
28239            bodies[0], bodies[1],
28240            "the retry resends the identical key and input"
28241        );
28242        assert_eq!(bodies[0]["request_id"], request_id);
28243    }
28244
28245    #[tokio::test]
28246    async fn invalid_command_keys_are_refused_before_sending() {
28247        let server = MockWorkerServer::start();
28248        let client = keyed_client(&server);
28249        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
28250
28251        for request_id in ["", too_long.as_str()] {
28252            let error = client
28253                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
28254                .await
28255                .expect_err("invalid signal key");
28256            assert!(
28257                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
28258                "{error:?}"
28259            );
28260            let error = client
28261                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
28262                .await
28263                .expect_err("invalid update key");
28264            assert!(matches!(error, Error::Codec(_)), "{error:?}");
28265        }
28266        assert!(server.captured_paths().is_empty(), "nothing was sent");
28267
28268        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
28269        let _ = client
28270            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
28271            .await;
28272        assert_eq!(
28273            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
28274            longest
28275        );
28276    }
28277
28278    #[test]
28279    fn generated_command_keys_are_distinct_and_well_formed() {
28280        let signal = Client::generate_signal_request_id();
28281        let update = Client::generate_update_request_id();
28282        assert_generated_request_id(&signal, "sdk-rust-signal-");
28283        assert_generated_request_id(&update, "sdk-rust-update-");
28284        assert_ne!(Client::generate_signal_request_id(), signal);
28285        assert!(validate_request_id(&signal).is_ok());
28286    }
28287
28288    #[test]
28289    fn command_keys_preserve_the_published_server_unicode_character_limit() {
28290        assert!(validate_request_id(&"é".repeat(255)).is_ok());
28291        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
28292        assert!(validate_request_id(&"é".repeat(256)).is_err());
28293    }
28294
28295    #[test]
28296    fn request_id_accessors_read_only_echoed_refusal_bodies() {
28297        let conflict = Error::Http {
28298            status: reqwest::StatusCode::CONFLICT,
28299            body: r#"{"reason":"request_id_conflict","request_id":"k1","retained_command_id":"cmd-1","retained_command_type":"signal","retained_outcome":"accepted","conflict":["name"]}"#.to_string(),
28300        };
28301        assert!(conflict.is_request_id_conflict());
28302        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
28303        let details = conflict.request_id_conflict().expect("conflict details");
28304        assert_eq!(details.conflict, ["name"]);
28305        assert_eq!(
28306            details.message,
28307            "request id is retained for a different command intent"
28308        );
28309
28310        let echoed = Error::Http {
28311            status: reqwest::StatusCode::CONFLICT,
28312            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
28313        };
28314        assert!(!echoed.is_request_id_conflict());
28315        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
28316
28317        let blank = Error::Http {
28318            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
28319            body: r#"{"request_id":""}"#.to_string(),
28320        };
28321        assert_eq!(blank.request_id(), None);
28322        let text = Error::Http {
28323            status: reqwest::StatusCode::BAD_GATEWAY,
28324            body: "upstream unavailable".to_string(),
28325        };
28326        assert_eq!(text.request_id(), None);
28327        assert!(!text.is_request_id_conflict());
28328
28329        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
28330            command: WorkflowCommandKind::Cancel,
28331            status: 409,
28332            reason: "request_id_conflict".to_string(),
28333            message: "retained".to_string(),
28334            workflow_id: "wf".to_string(),
28335            run_id: None,
28336            target_scope: None,
28337            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
28338        });
28339        assert!(rejection.is_request_id_conflict());
28340        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
28341
28342        assert_eq!(Error::Timeout.request_id(), None);
28343        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
28344    }
28345
28346    #[tokio::test]
28347    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
28348        let server = MockWorkerServer::start();
28349        let client = Client::builder(server.base_url())
28350            .timeout(Duration::from_secs(2))
28351            .build()
28352            .expect("client");
28353        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
28354
28355        client
28356            .start_workflow(
28357                "typed.echo",
28358                "rust-workers",
28359                "typed-start",
28360                arguments.clone(),
28361            )
28362            .await
28363            .expect("typed workflow start");
28364        assert_eq!(
28365            decode_wire_avro_value(
28366                &server.request_body("/api/workflows")["input"],
28367                DEFAULT_CODEC,
28368            )
28369            .expect("typed start input"),
28370            arguments
28371        );
28372
28373        client
28374            .signal_workflow("typed-1", "changed", arguments.clone())
28375            .await
28376            .expect("typed signal");
28377        assert_eq!(
28378            decode_wire_avro_value(
28379                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
28380                DEFAULT_CODEC,
28381            )
28382            .expect("typed signal input"),
28383            arguments
28384        );
28385
28386        assert_eq!(
28387            client
28388                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
28389                .await
28390                .expect("typed query"),
28391            typed_fidelity_probe()
28392        );
28393        assert_eq!(
28394            decode_wire_avro_value(
28395                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
28396                DEFAULT_CODEC,
28397            )
28398            .expect("typed query input"),
28399            arguments
28400        );
28401
28402        assert_eq!(
28403            client
28404                .update_workflow_avro_value(
28405                    "typed-1",
28406                    "replace",
28407                    arguments.clone(),
28408                    Some("typed-request"),
28409                )
28410                .await
28411                .expect("typed update"),
28412            typed_fidelity_probe()
28413        );
28414        let update = server.request_body("/api/workflows/typed-1/update/replace");
28415        assert_eq!(update["request_id"], "typed-request");
28416        assert_eq!(
28417            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
28418            arguments
28419        );
28420
28421        let handle = WorkflowHandle {
28422            client: client.clone(),
28423            workflow_id: "typed-1".to_string(),
28424            run_id: Some("run-typed-1".to_string()),
28425            workflow_type: "typed.echo".to_string(),
28426        };
28427        assert_eq!(
28428            handle
28429                .result_avro_value(WorkflowResultOptions::default())
28430                .await
28431                .expect("typed workflow result"),
28432            typed_fidelity_probe()
28433        );
28434
28435        client
28436            .complete_activity_task(
28437                "activity-typed",
28438                "attempt-typed",
28439                "rust-worker",
28440                typed_fidelity_probe(),
28441                DEFAULT_CODEC,
28442            )
28443            .await
28444            .expect("typed activity completion");
28445        assert_eq!(
28446            decode_wire_avro_value(
28447                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
28448                    ["result"],
28449                DEFAULT_CODEC,
28450            )
28451            .expect("typed activity result"),
28452            typed_fidelity_probe()
28453        );
28454        client
28455            .fail_activity_task(
28456                "activity-typed",
28457                "attempt-typed",
28458                "rust-worker",
28459                "typed failure",
28460                true,
28461            )
28462            .await
28463            .expect("activity failure");
28464    }
28465
28466    #[tokio::test]
28467    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
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
28474        let options = WorkflowCommandOptions::new()
28475            .reason("cleanup requested")
28476            .request_id("cancel-17");
28477        let cancelled = client
28478            .cancel_workflow("wf-lifecycle", options)
28479            .await
28480            .expect("instance cancellation");
28481        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
28482        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
28483        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
28484        assert_eq!(
28485            server.request_body("/api/workflows/wf-lifecycle/cancel"),
28486            json!({"reason":"cleanup requested","request_id":"cancel-17"})
28487        );
28488
28489        let terminated = client
28490            .terminate_workflow(
28491                "wf-lifecycle",
28492                WorkflowCommandOptions::new().reason("forced stop"),
28493            )
28494            .await
28495            .expect("instance termination");
28496        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
28497        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
28498
28499        client
28500            .cancel_workflow_run(
28501                "wf-lifecycle",
28502                "run-current",
28503                WorkflowCommandOptions::default(),
28504            )
28505            .await
28506            .expect("selected run cancellation");
28507        client
28508            .terminate_workflow_run(
28509                "wf-lifecycle",
28510                "run-current",
28511                WorkflowCommandOptions::default(),
28512            )
28513            .await
28514            .expect("selected run termination");
28515
28516        for (command, error) in [
28517            (
28518                WorkflowCommandKind::Cancel,
28519                client
28520                    .cancel_workflow_run(
28521                        "wf-lifecycle",
28522                        "run-stale",
28523                        WorkflowCommandOptions::default(),
28524                    )
28525                    .await
28526                    .expect_err("stale cancellation must be rejected"),
28527            ),
28528            (
28529                WorkflowCommandKind::Terminate,
28530                client
28531                    .terminate_workflow_run(
28532                        "wf-lifecycle",
28533                        "run-stale",
28534                        WorkflowCommandOptions::default(),
28535                    )
28536                    .await
28537                    .expect_err("stale termination must be rejected"),
28538            ),
28539        ] {
28540            let Error::WorkflowCommandRejected(rejection) = error else {
28541                panic!("expected typed command rejection");
28542            };
28543            assert_eq!(rejection.command, command);
28544            assert_eq!(rejection.status, 409);
28545            assert_eq!(rejection.reason, "historical_run_command_rejected");
28546            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
28547            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
28548        }
28549    }
28550
28551    #[tokio::test]
28552    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
28553        let server = MockWorkerServer::start();
28554        let client = Client::builder(server.base_url())
28555            .timeout(Duration::from_secs(2))
28556            .build()
28557            .expect("client");
28558
28559        let result = client
28560            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
28561            .await
28562            .expect("redrive accepted");
28563        assert_eq!(result.workflow_id, "wf-lifecycle");
28564        assert_eq!(result.source_run_id, "run-failed");
28565        assert_eq!(result.run_id, "run-successor");
28566        assert_eq!(result.resume_step_sequence, 2);
28567        assert_eq!(
28568            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
28569            json!({"request_id":"retry-1"})
28570        );
28571
28572        let repeated = client
28573            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
28574            .await
28575            .expect("idempotent redrive response accepted");
28576        assert_eq!(repeated.run_id, "run-successor");
28577
28578        let error = client
28579            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
28580            .await
28581            .expect_err("completed run must be rejected");
28582        let Error::Http { status, body } = error else {
28583            panic!("expected HTTP redrive rejection");
28584        };
28585        assert_eq!(status.as_u16(), 409);
28586        assert!(body.contains("run_not_failed"));
28587        assert_eq!(
28588            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
28589            json!({})
28590        );
28591
28592        let handle = WorkflowHandle {
28593            client: client.clone(),
28594            workflow_id: "wf-lifecycle".to_string(),
28595            run_id: Some("run-failed".to_string()),
28596            workflow_type: "test".to_string(),
28597        };
28598        assert_eq!(
28599            handle.redrive(None).await.expect("handle redrive").run_id,
28600            "run-successor"
28601        );
28602        let missing_run = WorkflowHandle {
28603            run_id: None,
28604            ..handle
28605        };
28606        assert!(matches!(
28607            missing_run.redrive(None).await,
28608            Err(Error::Codec(_))
28609        ));
28610    }
28611
28612    #[tokio::test]
28613    async fn workflow_start_options_send_server_enforced_deadlines() {
28614        let server = MockWorkerServer::start();
28615        let client = Client::builder(server.base_url())
28616            .timeout(Duration::from_secs(2))
28617            .build()
28618            .expect("client");
28619
28620        let handle = client
28621            .start_workflow_with_options(
28622                "rust.timeout",
28623                "rust-timeouts",
28624                "wf-start-options",
28625                WorkflowStartOptions::new()
28626                    .execution_timeout_seconds(30)
28627                    .run_timeout_seconds(1),
28628                json!([]),
28629            )
28630            .await
28631            .expect("workflow start");
28632
28633        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
28634        let body = server.request_body("/api/workflows");
28635        assert_eq!(body["execution_timeout_seconds"], 30);
28636        assert_eq!(body["run_timeout_seconds"], 1);
28637
28638        let invalid = client
28639            .start_workflow_with_options(
28640                "rust.timeout",
28641                "rust-timeouts",
28642                "wf-invalid-options",
28643                WorkflowStartOptions::new()
28644                    .execution_timeout_seconds(1)
28645                    .run_timeout_seconds(2),
28646                json!([]),
28647            )
28648            .await
28649            .expect_err("invalid deadline ordering");
28650        assert!(invalid
28651            .to_string()
28652            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
28653    }
28654
28655    #[tokio::test]
28656    async fn workflow_result_returns_each_typed_terminal_outcome() {
28657        let server = MockWorkerServer::start();
28658        let client = Client::builder(server.base_url())
28659            .timeout(Duration::from_secs(2))
28660            .build()
28661            .expect("client");
28662        let options = WorkflowResultOptions {
28663            poll_interval: Duration::ZERO,
28664            timeout: Duration::from_secs(1),
28665        };
28666
28667        let failed = WorkflowHandle {
28668            client: client.clone(),
28669            workflow_id: "wf-failed".to_string(),
28670            run_id: Some("run-failed".to_string()),
28671            workflow_type: "failure".to_string(),
28672        }
28673        .result(options)
28674        .await
28675        .expect_err("failed outcome");
28676        let Error::WorkflowFailed(failure) = failed else {
28677            panic!("expected WorkflowFailed");
28678        };
28679        assert_eq!(failure.workflow_id, "wf-failed");
28680        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
28681        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
28682        assert_eq!(failure.failure_category.as_deref(), Some("application"));
28683        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
28684        assert_eq!(
28685            failure.exception_class.as_deref(),
28686            Some("billing::PaymentError")
28687        );
28688        assert_eq!(failure.non_retryable, Some(true));
28689
28690        for (workflow_id, expected_kind, expected_reason) in [
28691            (
28692                "wf-cancelled",
28693                WorkflowTerminalKind::Cancelled,
28694                "cleanup requested",
28695            ),
28696            (
28697                "wf-terminated",
28698                WorkflowTerminalKind::Terminated,
28699                "forced stop",
28700            ),
28701            (
28702                "wf-timed-out",
28703                WorkflowTerminalKind::TimedOut,
28704                "run_timeout",
28705            ),
28706        ] {
28707            let error = WorkflowHandle {
28708                client: client.clone(),
28709                workflow_id: workflow_id.to_string(),
28710                run_id: None,
28711                workflow_type: "terminal".to_string(),
28712            }
28713            .result(options)
28714            .await
28715            .expect_err("typed terminal outcome");
28716            let outcome = match error {
28717                Error::WorkflowCancelled(outcome) => outcome,
28718                Error::WorkflowTerminated(outcome) => outcome,
28719                Error::WorkflowTimedOut(outcome) => outcome,
28720                other => panic!("unexpected terminal error: {other}"),
28721            };
28722            assert_eq!(outcome.kind, expected_kind);
28723            assert_eq!(outcome.workflow_id, workflow_id);
28724            assert_eq!(outcome.reason, expected_reason);
28725        }
28726
28727        let wait_timeout = WorkflowHandle {
28728            client,
28729            workflow_id: "wf-waiting".to_string(),
28730            run_id: Some("run-waiting".to_string()),
28731            workflow_type: "waiting".to_string(),
28732        }
28733        .result(WorkflowResultOptions {
28734            poll_interval: Duration::ZERO,
28735            timeout: Duration::ZERO,
28736        })
28737        .await
28738        .expect_err("client wait timeout");
28739        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
28740            panic!("expected typed client timeout");
28741        };
28742        assert_eq!(timeout.reason, "result_wait_timeout");
28743        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
28744        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
28745    }
28746
28747    #[tokio::test]
28748    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
28749        let server = MockWorkerServer::start();
28750        let client = Client::builder(server.base_url())
28751            .timeout(Duration::from_secs(2))
28752            .build()
28753            .expect("client");
28754
28755        let handle = WorkflowHandle {
28756            client,
28757            workflow_id: "wf-selected".to_string(),
28758            run_id: Some("run-selected".to_string()),
28759            workflow_type: "selected".to_string(),
28760        };
28761        let options = WorkflowResultOptions {
28762            poll_interval: Duration::ZERO,
28763            timeout: Duration::from_secs(1),
28764        };
28765
28766        let current = handle
28767            .result(options)
28768            .await
28769            .expect("instance result follows the current run");
28770        assert_eq!(current, json!("current run output"));
28771
28772        let error = handle
28773            .result_selected_run(options)
28774            .await
28775            .expect_err("the selected run is cancelled even though the current run completed");
28776
28777        let Error::WorkflowCancelled(outcome) = error else {
28778            panic!("expected selected run cancellation");
28779        };
28780        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
28781        assert_eq!(outcome.reason, "selected run cancelled");
28782        assert_eq!(
28783            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
28784            1
28785        );
28786        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
28787    }
28788
28789    #[tokio::test]
28790    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
28791        let server = MockWorkerServer::draining_polls();
28792        let client = Client::builder(server.base_url())
28793            .timeout(Duration::from_secs(2))
28794            .build()
28795            .expect("client");
28796
28797        let workflow = client
28798            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
28799            .await
28800            .expect("workflow drain response");
28801        let activity = client
28802            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
28803            .await
28804            .expect("activity drain response");
28805        let query = client
28806            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
28807            .await
28808            .expect("query drain response");
28809
28810        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
28811            assert_eq!(
28812                outcome,
28813                WorkerPollOutcome::Stop {
28814                    poll_status: Some("draining".to_string()),
28815                    reason: Some("worker_draining".to_string()),
28816                }
28817            );
28818        }
28819
28820        assert!(client
28821            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
28822            .await
28823            .expect("compatibility poll")
28824            .is_none());
28825    }
28826
28827    #[tokio::test]
28828    async fn managed_worker_honors_drain_stop_for_every_task_family() {
28829        let server = MockWorkerServer::draining_polls();
28830        let client = Client::builder(server.base_url())
28831            .timeout(Duration::from_secs(2))
28832            .build()
28833            .expect("client");
28834
28835        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
28836            .worker_id("draining-workflow-worker")
28837            .poll_timeout(Duration::ZERO);
28838        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
28839        workflow_worker
28840            .run()
28841            .await
28842            .expect("workflow drain is a clean stop");
28843
28844        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
28845            .worker_id("draining-activity-worker")
28846            .poll_timeout(Duration::ZERO);
28847        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
28848        activity_worker
28849            .run()
28850            .await
28851            .expect("activity drain is a clean stop");
28852
28853        let mut query_worker = Worker::new(client, "rust-workers")
28854            .worker_id("draining-query-worker")
28855            .poll_timeout(Duration::ZERO);
28856        query_worker.register_query("counter", "current", |_ctx, _args| async {
28857            Ok(Value::Null)
28858        });
28859        query_worker
28860            .run()
28861            .await
28862            .expect("query drain is a clean stop");
28863    }
28864
28865    #[tokio::test]
28866    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
28867        let server = MockWorkerServer::start();
28868        let client = Client::builder(server.base_url())
28869            .timeout(Duration::from_secs(2))
28870            .build()
28871            .expect("client");
28872
28873        let details: Value = serde_json::from_str(include_str!(
28874            "../tests/fixtures/activity-heartbeat-progress.json"
28875        ))
28876        .expect("heartbeat progress fixture");
28877        // Every individual field fits Server's progress contract, while the
28878        // obsolete encoded envelope exceeded its 191-character string limit.
28879        assert!(
28880            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
28881                .unwrap()["blob"]
28882                .as_str()
28883                .unwrap()
28884                .len()
28885                > 191
28886        );
28887        let heartbeat = client
28888            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
28889            .await
28890            .expect("cancellation heartbeat");
28891        assert!(heartbeat.cancel_requested);
28892        assert!(heartbeat.should_stop());
28893        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
28894        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
28895        let heartbeat_body =
28896            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
28897        assert_eq!(heartbeat_body["details"], details);
28898        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
28899        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
28900
28901        let error = client
28902            .complete_activity_task(
28903                "activity-cancel",
28904                "attempt-cancel",
28905                "rust-worker",
28906                json!({"late":true}),
28907                DEFAULT_CODEC,
28908            )
28909            .await
28910            .expect_err("late completion must be refused");
28911        assert!(activity_task_rejection_is_final(&error));
28912        let Error::ActivityTaskRejected(rejection) = error else {
28913            panic!("expected typed activity rejection");
28914        };
28915        assert_eq!(rejection.status, 409);
28916        assert_eq!(rejection.reason, "run_cancelled");
28917        assert!(rejection.cancel_requested);
28918        assert_eq!(rejection.can_continue, Some(false));
28919    }
28920
28921    #[tokio::test]
28922    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
28923        let server = MockWorkerServer::cancelled_activity();
28924        let client = Client::builder(server.base_url())
28925            .timeout(Duration::from_secs(2))
28926            .build()
28927            .expect("client");
28928        let cancellation_observed = Arc::new(AtomicBool::new(false));
28929        let observed = Arc::clone(&cancellation_observed);
28930        let mut worker = Worker::new(client.clone(), "rust-workers")
28931            .worker_id("rust-cancel-worker")
28932            .poll_timeout(Duration::from_millis(10));
28933        worker.register_activity("cancel-aware", move |ctx, _args| {
28934            let observed = Arc::clone(&observed);
28935            async move {
28936                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
28937                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
28938                Ok(json!({"late":"completion"}))
28939            }
28940        });
28941
28942        assert_eq!(
28943            worker.run_once().await.expect("cancelled attempt handled"),
28944            1
28945        );
28946        assert!(cancellation_observed.load(Ordering::SeqCst));
28947        assert_eq!(
28948            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
28949            1
28950        );
28951
28952        let mut restarted = Worker::new(client, "rust-workers")
28953            .worker_id("rust-cancel-worker-restarted")
28954            .poll_timeout(Duration::from_millis(10));
28955        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
28956        assert_eq!(
28957            restarted
28958                .run_once()
28959                .await
28960                .expect("replacement worker continues polling"),
28961            0
28962        );
28963    }
28964
28965    #[tokio::test]
28966    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
28967        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"}"#;
28968        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
28969        let client = Client::builder(server.base_url())
28970            .timeout(Duration::from_secs(2))
28971            .build()
28972            .expect("client");
28973
28974        let direct_error = client
28975            .complete_workflow_task(
28976                "workflow-timeout-task",
28977                "timeout-worker",
28978                3,
28979                vec![json!({
28980                    "type": "complete_workflow",
28981                    "result": fixture_envelope(Value::Null)
28982                })],
28983            )
28984            .await
28985            .expect_err("the low-level client preserves the completion rejection");
28986        let Error::Http { status, body } = direct_error else {
28987            panic!("expected the original HTTP completion rejection");
28988        };
28989        assert_eq!(status, reqwest::StatusCode::CONFLICT);
28990        assert_eq!(
28991            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
28992            "run_timed_out"
28993        );
28994
28995        let mut worker = Worker::new(client, "rust-workers")
28996            .worker_id("timeout-worker")
28997            .poll_timeout(Duration::from_millis(10));
28998        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
28999            Ok(json!({"late": "result"}))
29000        });
29001
29002        assert_eq!(
29003            worker
29004                .run_once()
29005                .await
29006                .expect("authoritative selected-run timeout settles the tick"),
29007            1
29008        );
29009        assert_eq!(
29010            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
29011            2,
29012            "both the direct client proof and managed worker must see the rejection"
29013        );
29014    }
29015
29016    #[tokio::test]
29017    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
29018        for (name, status, response) in [
29019            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
29020            (
29021                "command was recorded",
29022                "409 Conflict",
29023                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29024            ),
29025            (
29026                "lease conflict",
29027                "409 Conflict",
29028                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
29029            ),
29030            (
29031                "nonterminal run",
29032                "409 Conflict",
29033                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
29034            ),
29035            (
29036                "different selected run",
29037                "409 Conflict",
29038                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"}"#,
29039            ),
29040            (
29041                "different task attempt",
29042                "409 Conflict",
29043                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29044            ),
29045            (
29046                "authentication failure",
29047                "401 Unauthorized",
29048                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29049            ),
29050            (
29051                "authorization failure",
29052                "403 Forbidden",
29053                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29054            ),
29055            (
29056                "protocol failure",
29057                "400 Bad Request",
29058                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
29059            ),
29060            (
29061                "malformed command",
29062                "422 Unprocessable Entity",
29063                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29064            ),
29065            (
29066                "transient server failure",
29067                "503 Service Unavailable",
29068                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29069            ),
29070        ] {
29071            let server = MockWorkerServer::workflow_completion(status, response);
29072            let client = Client::builder(server.base_url())
29073                .timeout(Duration::from_secs(2))
29074                .build()
29075                .expect("client");
29076            let mut worker = Worker::new(client, "rust-workers")
29077                .worker_id("timeout-worker")
29078                .poll_timeout(Duration::from_millis(10));
29079            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29080                Ok(json!({"late": "result"}))
29081            });
29082
29083            let error = worker
29084                .run_once()
29085                .await
29086                .expect_err(&format!("{name} must remain an error"));
29087            assert!(
29088                matches!(error, Error::Http { .. } | Error::Protocol(_)),
29089                "{name} returned an unexpected error variant: {error}"
29090            );
29091        }
29092    }
29093
29094    #[tokio::test]
29095    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
29096        let server = MockWorkerServer::start();
29097        let client = Client::builder(server.base_url())
29098            .worker_token(Some("worker-secret".to_string()))
29099            .namespace("orders")
29100            .timeout(Duration::from_secs(2))
29101            .build()
29102            .expect("client");
29103        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
29104
29105        let result = client
29106            .deregister_worker_registration("worker/α space")
29107            .await
29108            .expect("deregister worker registration");
29109
29110        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
29111        assert_eq!(
29112            server.worker_protocol_for(path).as_deref(),
29113            Some(WORKER_PROTOCOL_VERSION)
29114        );
29115        assert_eq!(server.control_protocol_for(path), None);
29116        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
29117        assert_eq!(
29118            server.authorization_for(path).as_deref(),
29119            Some("Bearer worker-secret")
29120        );
29121        assert_eq!(
29122            result,
29123            WorkerDeregistrationEnvelope {
29124                worker_id: "deregistered-worker".to_string(),
29125                outcome: "deregistered".to_string(),
29126                recovered_workflow_task_count: 2,
29127            }
29128        );
29129    }
29130
29131    #[tokio::test]
29132    async fn low_level_registration_rejects_update_validators_before_transport() {
29133        let server = MockWorkerServer::start();
29134        let client = Client::builder(server.base_url())
29135            .timeout(Duration::from_secs(2))
29136            .build()
29137            .expect("client");
29138
29139        for update_validators in [json!(["approve"]), json!("approve")] {
29140            let error = client
29141                .register_worker_with_command_contracts(
29142                    "validator-claiming-worker",
29143                    "rust-workers",
29144                    vec!["orders".to_string()],
29145                    vec![],
29146                    1,
29147                    1,
29148                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29149                    json!({
29150                        "orders": {
29151                            "queries": ["current"],
29152                            "updates": ["approve"],
29153                            "update_validators": update_validators,
29154                        },
29155                    }),
29156                )
29157                .await
29158                .expect_err("unsupported validator claims must fail before registration");
29159
29160            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
29161                panic!("expected typed unsupported-validator failure");
29162            };
29163            assert_eq!(workflow_type, "orders");
29164        }
29165        assert_eq!(server.request_count("/api/worker/register"), 0);
29166    }
29167
29168    #[tokio::test]
29169    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
29170        let server = MockWorkerServer::start();
29171        let client = Client::builder(server.base_url())
29172            .timeout(Duration::from_secs(2))
29173            .build()
29174            .expect("client");
29175        let mut worker = Worker::new(client, "rust-workers");
29176        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
29177        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
29178        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29179        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
29180        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29181        worker
29182            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
29183            .expect("declare workflow signals");
29184
29185        worker.register().await.expect("register handler contracts");
29186
29187        let declaration =
29188            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
29189        let expected_contracts = json!([
29190            {
29191                "name": "a-avro",
29192                "parameters": [{
29193                    "name": "args", "position": 0, "required": false,
29194                    "variadic": true, "type": null, "allows_null": true,
29195                    "default_available": false, "default": null,
29196                }],
29197            },
29198            {
29199                "name": "z-json",
29200                "parameters": [{
29201                    "name": "args", "position": 0, "required": false,
29202                    "variadic": true, "type": null, "allows_null": true,
29203                    "default_available": false, "default": null,
29204                }],
29205            },
29206        ]);
29207        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
29208        assert_eq!(declaration["query_contracts"], expected_contracts);
29209        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
29210        assert_eq!(declaration["update_contracts"], expected_contracts);
29211        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
29212        assert_eq!(declaration["signal_contracts"], expected_contracts);
29213        assert_eq!(declaration["update_validators"], json!([]));
29214    }
29215
29216    #[tokio::test]
29217    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
29218        let server = MockWorkerServer::start();
29219        let client = Client::new(server.base_url()).expect("client");
29220        let mut worker = Worker::new(client, "rust-workers");
29221        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
29222        assert!(worker
29223            .declare_workflow_signals("missing", &["finish"])
29224            .is_err());
29225        worker
29226            .declare_workflow_signals("orders", &["finish"])
29227            .unwrap();
29228        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
29229            assert!(worker.declare_workflow_signals("orders", names).is_err());
29230        }
29231        worker.register().await.unwrap();
29232        assert_eq!(
29233            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
29234                ["signals"],
29235            json!(["finish"])
29236        );
29237        worker.declare_workflow_signals("orders", &[]).unwrap();
29238        worker.register().await.unwrap();
29239        let registrations = server.request_bodies("/api/worker/register");
29240        assert_eq!(
29241            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
29242            json!([])
29243        );
29244        assert_eq!(
29245            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
29246            json!([])
29247        );
29248    }
29249
29250    #[tokio::test]
29251    async fn low_level_registration_preserves_query_and_update_contracts() {
29252        let server = MockWorkerServer::start();
29253        let client = Client::builder(server.base_url())
29254            .timeout(Duration::from_secs(2))
29255            .build()
29256            .expect("client");
29257        let contracts = json!({
29258            "orders": {
29259                "queries": ["current"],
29260                "updates": ["approve"],
29261                "update_validators": [],
29262            },
29263            "payments": {
29264                "queries": ["status"],
29265                "updates": ["capture"],
29266            },
29267        });
29268
29269        client
29270            .register_worker_with_command_contracts(
29271                "command-worker",
29272                "rust-workers",
29273                vec!["orders".to_string(), "payments".to_string()],
29274                vec![],
29275                1,
29276                1,
29277                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29278                contracts.clone(),
29279            )
29280            .await
29281            .expect("query and update contracts must remain supported");
29282
29283        assert_eq!(
29284            server.request_body("/api/worker/register")["workflow_command_contracts"],
29285            contracts
29286        );
29287        assert!(server
29288            .request_body("/api/worker/register")
29289            .get("workflow_definition_fingerprints")
29290            .is_none());
29291    }
29292
29293    #[tokio::test]
29294    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
29295        let server = MockWorkerServer::start();
29296        let client = Client::builder(server.base_url())
29297            .timeout(Duration::from_secs(2))
29298            .build()
29299            .expect("client");
29300        let mut worker = Worker::new(client.clone(), "rust-workers");
29301        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29302
29303        assert!(worker
29304            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
29305            .is_err());
29306        assert!(worker
29307            .set_workflow_definition_sources("orders", &[])
29308            .is_err());
29309        worker
29310            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
29311            .expect("embed workflow source");
29312        worker.register().await.expect("register worker");
29313        let first = server.request_bodies("/api/worker/register")[0]
29314            ["workflow_definition_fingerprints"]["orders"]
29315            .as_str()
29316            .expect("source-backed fingerprint")
29317            .to_string();
29318        assert!(first.starts_with("sha256:"));
29319
29320        worker
29321            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
29322            .expect("change embedded helper source");
29323        worker.register().await.expect("register changed source");
29324        let changed = server.request_bodies("/api/worker/register")[1]
29325            ["workflow_definition_fingerprints"]["orders"]
29326            .as_str()
29327            .expect("changed fingerprint")
29328            .to_string();
29329        assert_ne!(first, changed);
29330
29331        let mut replacement =
29332            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
29333        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29334        replacement
29335            .register()
29336            .await
29337            .expect("register replacement handler");
29338        assert_eq!(
29339            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
29340            json!({})
29341        );
29342    }
29343
29344    #[tokio::test]
29345    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
29346        let server = MockWorkerServer::start();
29347        let control_only = Client::builder(server.base_url())
29348            .control_token(Some("control-secret".to_string()))
29349            .build()
29350            .expect("control client");
29351
29352        let error = control_only
29353            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29354            .await
29355            .expect_err("control token must not authorize a worker request");
29356        assert!(matches!(
29357            error,
29358            Error::MissingRoleCredentials { role: "worker", .. }
29359        ));
29360        assert_eq!(server.request_count("/api/worker/register"), 0);
29361
29362        let worker_only = Client::builder(server.base_url())
29363            .worker_token(Some("worker-secret".to_string()))
29364            .build()
29365            .expect("worker client");
29366        let error = worker_only
29367            .health()
29368            .await
29369            .expect_err("worker token must not authorize a control request");
29370        assert!(matches!(
29371            error,
29372            Error::MissingRoleCredentials {
29373                role: "control",
29374                ..
29375            }
29376        ));
29377        assert_eq!(server.request_count("/api/health"), 0);
29378    }
29379
29380    #[tokio::test]
29381    async fn shared_token_supports_worker_and_control_planes() {
29382        let server = MockWorkerServer::start();
29383        let client = Client::builder(server.base_url())
29384            .token(Some("shared-secret".to_string()))
29385            .build()
29386            .expect("client");
29387
29388        client.health().await.expect("control request");
29389        client
29390            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29391            .await
29392            .expect("worker request");
29393
29394        assert_eq!(
29395            server.authorization_for("/api/health").as_deref(),
29396            Some("Bearer shared-secret")
29397        );
29398        assert_eq!(
29399            server.control_protocol_for("/api/health").as_deref(),
29400            Some(CONTROL_PLANE_VERSION)
29401        );
29402        assert_eq!(
29403            server.authorization_for("/api/worker/register").as_deref(),
29404            Some("Bearer shared-secret")
29405        );
29406        assert_eq!(
29407            server
29408                .worker_protocol_for("/api/worker/register")
29409                .as_deref(),
29410            Some(WORKER_PROTOCOL_VERSION)
29411        );
29412    }
29413
29414    #[tokio::test]
29415    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
29416        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
29417        let server = MockWorkerServer::start();
29418        let client = Client::builder(server.base_url())
29419            .timeout(Duration::from_secs(2))
29420            .build()
29421            .expect("client");
29422
29423        client
29424            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
29425            .await
29426            .expect("register");
29427        client
29428            .heartbeat_worker("capture-worker", 1, 1)
29429            .await
29430            .expect("heartbeat");
29431        client
29432            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29433            .await
29434            .expect("workflow poll");
29435        client
29436            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29437            .await
29438            .expect("activity poll");
29439
29440        for path in [
29441            "/api/worker/register",
29442            "/api/worker/heartbeat",
29443            "/api/worker/workflow-tasks/poll",
29444            "/api/worker/activity-tasks/poll",
29445        ] {
29446            assert_eq!(
29447                server.worker_protocol_for(path).as_deref(),
29448                Some(WORKER_PROTOCOL_VERSION),
29449                "unexpected protocol for {path}"
29450            );
29451        }
29452
29453        assert_eq!(
29454            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
29455            1
29456        );
29457        assert_eq!(
29458            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
29459            500
29460        );
29461        assert_eq!(
29462            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
29463            1
29464        );
29465        assert!(
29466            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
29467                .as_str()
29468                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
29469        );
29470        assert!(
29471            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
29472                .as_str()
29473                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
29474        );
29475        let registration = server.request_body("/api/worker/register");
29476        for optional in [
29477            "cooperative_cancellation",
29478            "local_activities",
29479            "worker_sessions",
29480            "sticky_execution",
29481        ] {
29482            assert!(!registration["capabilities"]
29483                .as_array()
29484                .is_some_and(|capabilities| capabilities
29485                    .iter()
29486                    .any(|capability| capability.as_str() == Some(optional))));
29487        }
29488    }
29489
29490    #[tokio::test]
29491    async fn explicit_previous_worker_protocol_preserves_headers() {
29492        let server = MockWorkerServer::start();
29493        let client = Client::builder(server.base_url())
29494            .worker_protocol_version(WorkerProtocolVersion::V119)
29495            .timeout(Duration::from_secs(2))
29496            .build()
29497            .expect("client");
29498        client
29499            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
29500            .await
29501            .expect("register");
29502        client
29503            .heartbeat_worker("legacy-worker", 1, 1)
29504            .await
29505            .expect("heartbeat");
29506        client
29507            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
29508            .await
29509            .expect("workflow poll");
29510        client
29511            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
29512            .await
29513            .expect("activity poll");
29514        client
29515            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
29516            .await
29517            .expect("query poll");
29518        client
29519            .deregister_worker_registration("legacy-worker")
29520            .await
29521            .expect("deregister");
29522        for path in [
29523            "/api/worker/register",
29524            "/api/worker/heartbeat",
29525            "/api/worker/workflow-tasks/poll",
29526            "/api/worker/activity-tasks/poll",
29527            "/api/worker/query-tasks/poll",
29528            "/api/worker/registrations/legacy-worker",
29529        ] {
29530            assert_eq!(
29531                server.worker_protocol_for(path).as_deref(),
29532                Some("1.19"),
29533                "{path}"
29534            );
29535            assert_eq!(server.control_protocol_for(path), None, "{path}");
29536        }
29537    }
29538
29539    #[tokio::test]
29540    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
29541        let server = MockWorkerServer::start();
29542        let client = Client::builder(server.base_url())
29543            .worker_protocol_version(WorkerProtocolVersion::V119)
29544            .timeout(Duration::from_secs(2))
29545            .build()
29546            .expect("client");
29547        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
29548        let error = worker
29549            .register()
29550            .await
29551            .expect_err("legacy cooperation must be refused");
29552        assert!(matches!(
29553            error,
29554            Error::CooperativeCancellationUnavailable(_)
29555        ));
29556        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
29557    }
29558
29559    #[tokio::test]
29560    async fn query_task_endpoints_send_the_selected_worker_protocol() {
29561        let server = MockWorkerServer::start();
29562        let client = Client::builder(server.base_url())
29563            .timeout(Duration::from_secs(2))
29564            .build()
29565            .expect("client");
29566
29567        client
29568            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29569            .await
29570            .expect("query poll");
29571        client
29572            .complete_query_task(
29573                "query-capture",
29574                "capture-worker",
29575                1,
29576                json!(8),
29577                DEFAULT_CODEC,
29578            )
29579            .await
29580            .expect("query complete");
29581        client
29582            .fail_query_task(
29583                "query-capture",
29584                "capture-worker",
29585                1,
29586                "failed",
29587                "query_rejected",
29588                "QueryFailed",
29589            )
29590            .await
29591            .expect("query fail");
29592
29593        for path in [
29594            "/api/worker/query-tasks/poll",
29595            "/api/worker/query-tasks/query-capture/complete",
29596            "/api/worker/query-tasks/query-capture/fail",
29597        ] {
29598            assert_eq!(
29599                server.worker_protocol_for(path).as_deref(),
29600                Some(WORKER_PROTOCOL_VERSION),
29601                "unexpected protocol for {path}"
29602            );
29603        }
29604
29605        assert_eq!(
29606            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
29607            1
29608        );
29609        assert!(
29610            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
29611                .as_str()
29612                .is_some_and(|id| id.starts_with("rust-query-poll-"))
29613        );
29614    }
29615
29616    #[tokio::test]
29617    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
29618        let server = MockWorkerServer::transient_worker_failures();
29619        let client = Client::builder(server.base_url())
29620            .timeout(Duration::from_secs(2))
29621            .build()
29622            .expect("client");
29623
29624        client
29625            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29626            .await
29627            .expect("workflow poll retry");
29628        client
29629            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29630            .await
29631            .expect("activity poll retry");
29632        client
29633            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29634            .await
29635            .expect("query poll retry");
29636
29637        for path in [
29638            "/api/worker/workflow-tasks/poll",
29639            "/api/worker/activity-tasks/poll",
29640            "/api/worker/query-tasks/poll",
29641        ] {
29642            let bodies = server.request_bodies(path);
29643            assert_eq!(bodies.len(), 2, "{path} must be retried once");
29644            assert_eq!(
29645                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
29646                "{path} must preserve the request binding across retry"
29647            );
29648        }
29649    }
29650
29651    #[tokio::test]
29652    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
29653        let server = MockWorkerServer::consecutive_poll_failures(2);
29654        let client = Client::builder(server.base_url())
29655            .timeout(Duration::from_secs(2))
29656            .build()
29657            .expect("client");
29658        let mut worker = Worker::new(client, "capture")
29659            .worker_id("capture-worker")
29660            .poll_timeout(Duration::from_millis(10))
29661            .retry_policy(WorkerRetryPolicy {
29662                max_retries: 2,
29663                initial_backoff: Duration::from_millis(1),
29664                max_backoff: Duration::from_millis(1),
29665            });
29666        worker.register_workflow(
29667            "capture.workflow",
29668            |_ctx, _input| async move { Ok(Value::Null) },
29669        );
29670        worker.register_activity(
29671            "capture.activity",
29672            |_ctx, _input| async move { Ok(Value::Null) },
29673        );
29674        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
29675            Ok(Value::Null)
29676        });
29677
29678        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
29679
29680        for path in [
29681            "/api/worker/workflow-tasks/poll",
29682            "/api/worker/activity-tasks/poll",
29683            "/api/worker/query-tasks/poll",
29684        ] {
29685            let bodies = server.request_bodies(path);
29686            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
29687            assert!(
29688                bodies
29689                    .iter()
29690                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
29691                "{path} must preserve one request binding across every retry"
29692            );
29693        }
29694    }
29695
29696    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
29697        let reason = if unavailable {
29698            "storage_admission_unavailable"
29699        } else {
29700            "storage_pressure"
29701        };
29702        let mut body = json!({
29703            "reason": reason,
29704            "storage_state": if unavailable { "fenced" } else { "draining" },
29705            "retryable": true,
29706            "retry_after_seconds": 1,
29707        });
29708        if !mid_poll {
29709            body["request_admitted"] = json!(false);
29710        }
29711        if let Some(id) = poll_id {
29712            body["task"] = Value::Null;
29713            body["poll_status"] = json!(reason);
29714            body["poll_request_id"] = json!(id);
29715            body["retry_same_poll_request_id"] = json!(true);
29716            body["claim_admitted"] = json!(false);
29717        }
29718        body
29719    }
29720
29721    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
29722        let operation = match path {
29723            "/api/worker/register" => "register_worker",
29724            "/api/worker/heartbeat" => "heartbeat_worker",
29725            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
29726            "/api/worker/activity-tasks/poll" => "poll_activity_task",
29727            "/api/worker/query-tasks/poll" => "poll_query_task",
29728            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
29729            _ => return None,
29730        };
29731        let request: Value = serde_json::from_str(request).ok()?;
29732        let mut response = json!({
29733            "reason": "backend_unavailable",
29734            "operation": operation,
29735            "outcome": "unknown",
29736            "retryable": true,
29737            "retry_after_seconds": 1,
29738            "worker_id": request["worker_id"],
29739            "task_queue": request.get("task_queue"),
29740        });
29741        if path.ends_with("/poll") {
29742            response["task"] = Value::Null;
29743            response["poll_status"] = json!("backend_unavailable");
29744            response["poll_request_id"] = request["poll_request_id"].clone();
29745            response["retry_same_poll_request_id"] = json!(true);
29746        }
29747        Some(response)
29748    }
29749
29750    fn backend_retry_override(
29751        path: &str,
29752        request: &str,
29753        number: usize,
29754    ) -> Option<(&'static str, String)> {
29755        if number > 8 {
29756            return None;
29757        }
29758        Some((
29759            "503 Service Unavailable",
29760            backend_refusal(path, request)?.to_string(),
29761        ))
29762    }
29763
29764    fn backend_unavailable_override(
29765        path: &str,
29766        request: &str,
29767        _number: usize,
29768    ) -> Option<(&'static str, String)> {
29769        Some((
29770            "503 Service Unavailable",
29771            backend_refusal(path, request)?.to_string(),
29772        ))
29773    }
29774
29775    fn storage_worker(server: &MockWorkerServer) -> Worker {
29776        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
29777            .worker_id("storage-worker")
29778            .retry_policy(WorkerRetryPolicy {
29779                max_retries: 1,
29780                initial_backoff: Duration::from_millis(1),
29781                max_backoff: Duration::from_millis(1),
29782            })
29783    }
29784
29785    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
29786        let requests = server.requests.lock().expect("requests");
29787        let bodies: Vec<_> = requests
29788            .iter()
29789            .filter(|request| request.path == path)
29790            .map(|request| &request.body)
29791            .collect();
29792        assert_eq!(bodies.len(), count, "{path}");
29793        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
29794    }
29795
29796    #[test]
29797    fn backend_recovery_requires_the_explicit_worker_contract() {
29798        for (path, operation) in [
29799            ("/worker/register", "register_worker"),
29800            ("/worker/heartbeat", "heartbeat_worker"),
29801            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
29802            ("/worker/activity-tasks/poll", "poll_activity_task"),
29803            ("/worker/query-tasks/poll", "poll_query_task"),
29804            (
29805                "/worker/update-validation-tasks/poll",
29806                "poll_update_validation_task",
29807            ),
29808        ] {
29809            let poll_id = path.ends_with("/poll").then_some("same-poll");
29810            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
29811            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
29812                .expect("worker operation");
29813            assert_eq!(body["operation"], operation);
29814            let error = Error::Http {
29815                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29816                body: body.to_string(),
29817            };
29818            assert_eq!(
29819                worker_backend_unavailable_retry_after(&error, path, poll_id),
29820                Some(Duration::from_secs(1))
29821            );
29822            assert!(!worker_operation_is_retryable(&error));
29823            for (field, value) in [
29824                ("operation", json!("wrong_operation")),
29825                ("outcome", json!("completed")),
29826                ("retryable", json!(false)),
29827                ("retry_after_seconds", json!(0)),
29828                ("worker_id", json!("")),
29829            ] {
29830                let mut invalid = body.clone();
29831                invalid[field] = value;
29832                let error = Error::Http {
29833                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29834                    body: invalid.to_string(),
29835                };
29836                assert!(
29837                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
29838                    "{path}: {field}"
29839                );
29840                assert!(!worker_operation_is_retryable(&error));
29841            }
29842            if let Some(poll_id) = poll_id {
29843                for (field, value) in [
29844                    ("poll_request_id", json!("wrong-poll")),
29845                    ("poll_status", json!("empty")),
29846                    ("task", json!({"task_id":"claimed"})),
29847                    ("retry_same_poll_request_id", json!(false)),
29848                ] {
29849                    let mut invalid = body.clone();
29850                    invalid[field] = value;
29851                    let error = Error::Http {
29852                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29853                        body: invalid.to_string(),
29854                    };
29855                    assert!(
29856                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
29857                            .is_none(),
29858                        "{path}: {field}"
29859                    );
29860                }
29861            }
29862            let error = Error::Http {
29863                status: reqwest::StatusCode::UNAUTHORIZED,
29864                body: body.to_string(),
29865            };
29866            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
29867            assert!(!worker_operation_is_retryable(&error));
29868        }
29869    }
29870
29871    #[tokio::test]
29872    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
29873        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29874            request_override: Some(backend_retry_override),
29875            ..MockWorkerBehavior::default()
29876        });
29877        let mut worker =
29878            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
29879        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29880        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
29881        worker.register_query("backend.workflow", "state", |_, _| async {
29882            Ok(Value::Null)
29883        });
29884        worker.register().await.expect("registration recovery");
29885        worker
29886            .client
29887            .heartbeat_worker("storage-worker", 1, 1)
29888            .await
29889            .expect("heartbeat recovery");
29890        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
29891        for path in [
29892            "/api/worker/register",
29893            "/api/worker/heartbeat",
29894            "/api/worker/workflow-tasks/poll",
29895            "/api/worker/activity-tasks/poll",
29896            "/api/worker/query-tasks/poll",
29897        ] {
29898            assert_identical_requests(&server, path, 9);
29899        }
29900    }
29901
29902    #[tokio::test]
29903    async fn backend_recovery_wait_stops_with_worker() {
29904        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29905            request_override: Some(backend_unavailable_override),
29906            ..MockWorkerBehavior::default()
29907        });
29908        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
29909            max_retries: 1,
29910            initial_backoff: Duration::from_secs(2),
29911            max_backoff: Duration::from_secs(2),
29912        });
29913        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29914        let started = tokio::time::Instant::now();
29915        let _ = tokio::time::timeout(
29916            Duration::from_secs(1),
29917            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
29918        )
29919        .await
29920        .expect("shutdown interrupts backend wait");
29921        assert!(started.elapsed() < Duration::from_secs(1));
29922        assert!(server.request_count("/api/worker/register") >= 1);
29923    }
29924
29925    #[test]
29926    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
29927        for unavailable in [false, true] {
29928            for mid_poll in [false, true] {
29929                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
29930                let error = Error::Http {
29931                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29932                    body: body.to_string(),
29933                };
29934                assert_eq!(
29935                    worker_storage_admission_retry_after(&error, Some("same-poll")),
29936                    Some(Duration::from_secs(1))
29937                );
29938                assert!(
29939                    !worker_operation_is_retryable(&error),
29940                    "storage is not a bounded generic retry"
29941                );
29942                for (field, value) in [
29943                    ("poll_request_id", json!("wrong-poll")),
29944                    ("task", json!({"task_id":"claimed"})),
29945                    ("retryable", json!(false)),
29946                    ("retry_after_seconds", json!(0)),
29947                    ("retry_after_seconds", json!(true)),
29948                    ("retry_after_seconds", json!(1.0)),
29949                    ("storage_state", json!("normal")),
29950                    ("poll_status", json!("empty")),
29951                    ("claim_admitted", json!(true)),
29952                    ("retry_same_poll_request_id", json!(false)),
29953                    ("request_admitted", json!(true)),
29954                ] {
29955                    let mut invalid = body.clone();
29956                    invalid[field] = value;
29957                    let error = Error::Http {
29958                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29959                        body: invalid.to_string(),
29960                    };
29961                    assert!(
29962                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
29963                        "{field}"
29964                    );
29965                }
29966            }
29967        }
29968        let body = storage_refusal(None, false, false);
29969        let error = Error::Http {
29970            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29971            body: body.to_string(),
29972        };
29973        assert!(worker_storage_admission_retry_after(&error, None).is_some());
29974        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
29975        let error = Error::Http {
29976            status: reqwest::StatusCode::FORBIDDEN,
29977            body: body.to_string(),
29978        };
29979        assert!(worker_storage_admission_retry_after(&error, None).is_none());
29980        let body = storage_refusal(None, false, true);
29981        let error = Error::Http {
29982            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29983            body: body.to_string(),
29984        };
29985        assert!(worker_storage_admission_retry_after(&error, None).is_none());
29986    }
29987
29988    #[tokio::test]
29989    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
29990        for unavailable in [false, true] {
29991            for mid_poll in [false, true] {
29992                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29993                    poll_failures_per_path: 1,
29994                    storage_refusals: 7,
29995                    storage_path: Some("/poll"),
29996                    storage_unavailable: unavailable,
29997                    storage_mid_poll: mid_poll,
29998                    ..MockWorkerBehavior::default()
29999                });
30000                let mut worker = storage_worker(&server);
30001                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
30002                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
30003                for path in [
30004                    "/api/worker/workflow-tasks/poll",
30005                    "/api/worker/activity-tasks/poll",
30006                    "/api/worker/query-tasks/poll",
30007                ] {
30008                    assert_identical_requests(&server, path, 9);
30009                }
30010            }
30011        }
30012    }
30013
30014    #[tokio::test]
30015    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
30016        struct CountedBody(Arc<AtomicUsize>);
30017        impl Serialize for CountedBody {
30018            fn serialize<S: Serializer>(
30019                &self,
30020                serializer: S,
30021            ) -> std::result::Result<S::Ok, S::Error> {
30022                let count = self.0.fetch_add(1, Ordering::SeqCst);
30023                json!({"serialization":count,"lease_owner":"worker","attempt":7})
30024                    .serialize(serializer)
30025            }
30026        }
30027        for path in [
30028            "/api/worker/register",
30029            "/api/worker/heartbeat",
30030            "/api/worker/workflow-tasks/storage-task/complete",
30031            "/api/worker/workflow-tasks/storage-task/fail",
30032            "/api/worker/activity-tasks/storage-task/complete",
30033            "/api/worker/activity-tasks/storage-task/fail",
30034            "/api/worker/activity-tasks/storage-task/heartbeat",
30035            "/api/worker/query-tasks/storage-task/complete",
30036            "/api/worker/query-tasks/storage-task/fail",
30037        ] {
30038            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30039                storage_refusals: 7,
30040                storage_path: Some(path),
30041                ..MockWorkerBehavior::default()
30042            });
30043            let worker =
30044                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30045            let calls = Arc::new(AtomicUsize::new(0));
30046            let _: Value = worker
30047                .client
30048                .request_json(
30049                    reqwest::Method::POST,
30050                    &path[4..],
30051                    RequestProtocol::DefaultWorker,
30052                    Some(&CountedBody(Arc::clone(&calls))),
30053                )
30054                .await
30055                .expect("prepared request recovery");
30056            assert_eq!(calls.load(Ordering::SeqCst), 1);
30057            assert_identical_requests(&server, path, 8);
30058        }
30059        for worker_scope in [false, true] {
30060            let path = if worker_scope {
30061                "/api/health"
30062            } else {
30063                "/api/worker/register"
30064            };
30065            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30066                storage_refusals: usize::MAX,
30067                storage_path: Some(path),
30068                ..MockWorkerBehavior::default()
30069            });
30070            let worker = storage_worker(&server);
30071            let client = worker.client.clone();
30072            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
30073            let error = if worker_scope {
30074                worker
30075                    .client
30076                    .health()
30077                    .await
30078                    .expect_err("control plane is not retried")
30079            } else {
30080                client
30081                    .request_json::<Value, Value>(
30082                        reqwest::Method::POST,
30083                        "/worker/register",
30084                        RequestProtocol::DefaultWorker,
30085                        Some(&json!({})),
30086                    )
30087                    .await
30088                    .expect_err("direct client is not retried")
30089            };
30090            assert!(worker_storage_admission_body(&error).is_some());
30091            assert_eq!(server.request_count(path), 1);
30092        }
30093    }
30094
30095    #[tokio::test]
30096    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
30097        for fail in [false, true] {
30098            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30099                storage_activity: true,
30100                storage_refusals: 7,
30101                storage_path: Some("/storage-activity/"),
30102                ..MockWorkerBehavior::default()
30103            });
30104            let mut worker = storage_worker(&server);
30105            let calls = Arc::new(AtomicUsize::new(0));
30106            let observed = Arc::clone(&calls);
30107            worker.register_activity("storage.activity", move |ctx, _| {
30108                let calls = Arc::clone(&observed);
30109                async move {
30110                    calls.fetch_add(1, Ordering::SeqCst);
30111                    ctx.heartbeat(json!({"step":2})).await?;
30112                    if fail {
30113                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
30114                    } else {
30115                        Ok(json!({"receipt":true}))
30116                    }
30117                }
30118            });
30119            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30120            assert_eq!(calls.load(Ordering::SeqCst), 1);
30121            assert_identical_requests(
30122                &server,
30123                "/api/worker/activity-tasks/storage-activity/heartbeat",
30124                8,
30125            );
30126            let suffix = if fail { "fail" } else { "complete" };
30127            assert_identical_requests(
30128                &server,
30129                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
30130                8,
30131            );
30132            let other = if fail { "complete" } else { "fail" };
30133            assert_eq!(
30134                server.request_count(&format!(
30135                    "/api/worker/activity-tasks/storage-activity/{other}"
30136                )),
30137                0
30138            );
30139        }
30140    }
30141
30142    #[tokio::test]
30143    async fn storage_waits_are_interruptible_without_false_activity_failure() {
30144        for path in [
30145            "/api/worker/register",
30146            "/api/worker/heartbeat",
30147            "/api/worker/activity-tasks/poll",
30148            "/api/worker/activity-tasks/storage-activity/heartbeat",
30149            "/api/worker/activity-tasks/storage-activity/complete",
30150        ] {
30151            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30152                storage_activity: true,
30153                storage_refusals: usize::MAX,
30154                storage_path: Some(path),
30155                ..MockWorkerBehavior::default()
30156            });
30157            let mut worker = storage_worker(&server)
30158                .max_concurrent_workflow_tasks(1)
30159                .max_concurrent_activity_tasks(1)
30160                .retry_policy(WorkerRetryPolicy::default());
30161            worker.register_activity("storage.activity", |ctx, _| async move {
30162                ctx.heartbeat(json!({"step":2})).await?;
30163                Ok(json!({"receipt":true}))
30164            });
30165            let shutdown = async {
30166                while server.request_count(path) == 0 {
30167                    tokio::time::sleep(Duration::from_millis(1)).await;
30168                }
30169            };
30170            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
30171                .await
30172                .expect("shutdown interrupts admission");
30173            assert!(
30174                result.is_err(),
30175                "a refused operation must not appear acknowledged: {path}, {result:?}"
30176            );
30177            assert_eq!(server.request_count(path), 1);
30178            assert_eq!(
30179                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
30180                0
30181            );
30182            assert_eq!(
30183                server.request_count("/api/worker/registrations/mock-worker"),
30184                usize::from(!path.ends_with("/register"))
30185            );
30186        }
30187    }
30188
30189    #[tokio::test]
30190    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
30191        for fail in [false, true] {
30192            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30193                storage_query: true,
30194                storage_refusals: 7,
30195                storage_path: Some("/storage-query/"),
30196                ..MockWorkerBehavior::default()
30197            });
30198            let mut worker = storage_worker(&server);
30199            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
30200            let calls = Arc::new(AtomicUsize::new(0));
30201            let observed = Arc::clone(&calls);
30202            worker.register_query("storage.workflow", "state", move |_, _| {
30203                let calls = Arc::clone(&observed);
30204                async move {
30205                    calls.fetch_add(1, Ordering::SeqCst);
30206                    if fail {
30207                        Err(Error::WorkerLoop("intentional query failure".to_string()))
30208                    } else {
30209                        Ok(json!({"state":"waiting"}))
30210                    }
30211                }
30212            });
30213            assert_eq!(worker.run_once().await.expect("query settled"), 1);
30214            assert_eq!(calls.load(Ordering::SeqCst), 1);
30215            let suffix = if fail { "fail" } else { "complete" };
30216            assert_identical_requests(
30217                &server,
30218                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
30219                8,
30220            );
30221            let other = if fail { "complete" } else { "fail" };
30222            assert_eq!(
30223                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
30224                0
30225            );
30226        }
30227    }
30228
30229    #[tokio::test]
30230    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
30231        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30232            storage_refusals: 7,
30233            storage_path: Some("/poll"),
30234            unauthorized_polls: true,
30235            ..MockWorkerBehavior::default()
30236        });
30237        let error = storage_worker(&server)
30238            .run_once()
30239            .await
30240            .expect_err("auth remains terminal");
30241        assert!(matches!(
30242            error,
30243            Error::Http {
30244                status: reqwest::StatusCode::UNAUTHORIZED,
30245                ..
30246            }
30247        ));
30248        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
30249
30250        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30251            storage_refusals: 7,
30252            storage_path: Some("/activity-cancel/complete"),
30253            ..MockWorkerBehavior::default()
30254        });
30255        let worker =
30256            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30257        let error = worker
30258            .client
30259            .complete_activity_task(
30260                "activity-cancel",
30261                "attempt-cancel",
30262                "worker",
30263                json!({}),
30264                DEFAULT_CODEC,
30265            )
30266            .await
30267            .expect_err("cancellation remains terminal");
30268        assert!(activity_task_rejection_is_final(&error));
30269        assert_identical_requests(
30270            &server,
30271            "/api/worker/activity-tasks/activity-cancel/complete",
30272            8,
30273        );
30274
30275        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30276            storage_refusals: usize::MAX,
30277            storage_path: Some("/poll"),
30278            storage_wrong_poll_id: true,
30279            ..MockWorkerBehavior::default()
30280        });
30281        assert!(storage_worker(&server).run_once().await.is_err());
30282        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
30283    }
30284
30285    #[tokio::test]
30286    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
30287        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30288            storage_refusals: usize::MAX,
30289            storage_path: Some("/poll"),
30290            ..MockWorkerBehavior::default()
30291        });
30292        let mut worker = storage_worker(&server)
30293            .max_concurrent_workflow_tasks(1)
30294            .max_concurrent_activity_tasks(1)
30295            .retry_policy(WorkerRetryPolicy::default());
30296        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
30297        let run = tokio::spawn(async move { worker.run().await });
30298        tokio::time::timeout(Duration::from_secs(2), async {
30299            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
30300                tokio::time::sleep(Duration::from_millis(1)).await;
30301            }
30302        })
30303        .await
30304        .expect("poll started");
30305        run.abort();
30306        assert!(run.await.expect_err("cancelled run").is_cancelled());
30307        tokio::time::sleep(Duration::from_millis(250)).await;
30308        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
30309    }
30310
30311    #[tokio::test]
30312    async fn query_protocol_rejection_from_older_server_is_typed() {
30313        let server = MockWorkerServer::reject_query_protocol();
30314        let client = Client::builder(server.base_url())
30315            .timeout(Duration::from_secs(2))
30316            .build()
30317            .expect("client");
30318
30319        let error = client
30320            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
30321            .await
30322            .expect_err("server below query protocol floor must reject");
30323        let Error::Protocol(failure) = error else {
30324            panic!("expected typed protocol failure");
30325        };
30326
30327        assert_eq!(failure.status, 400);
30328        assert_eq!(failure.reason, "unsupported_protocol_version");
30329        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
30330        assert_eq!(
30331            failure.requested_version.as_deref(),
30332            Some(WORKER_PROTOCOL_VERSION)
30333        );
30334        assert_eq!(
30335            server
30336                .worker_protocol_for("/api/worker/query-tasks/poll")
30337                .as_deref(),
30338            Some(WORKER_PROTOCOL_VERSION)
30339        );
30340    }
30341
30342    #[tokio::test]
30343    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
30344        let server = MockWorkerServer::reject_query_protocol();
30345        let client = Client::builder(server.base_url())
30346            .timeout(Duration::from_secs(2))
30347            .build()
30348            .expect("client");
30349        let mut worker = Worker::new(client, "rust-workers")
30350            .worker_id("baseline-worker")
30351            .poll_timeout(Duration::from_millis(10));
30352
30353        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
30354            Ok(Value::Null)
30355        });
30356
30357        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
30358        assert_eq!(
30359            server
30360                .worker_protocol_for("/api/worker/workflow-tasks/poll")
30361                .as_deref(),
30362            Some(WORKER_PROTOCOL_VERSION)
30363        );
30364        assert_eq!(
30365            server.worker_protocol_for("/api/worker/query-tasks/poll"),
30366            None,
30367            "a worker without query handlers must not use the query-task endpoint"
30368        );
30369    }
30370
30371    #[tokio::test]
30372    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
30373        let server = MockWorkerServer::reject_query_completion();
30374        let client = Client::builder(server.base_url())
30375            .timeout(Duration::from_secs(2))
30376            .build()
30377            .expect("client");
30378
30379        let error = client
30380            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
30381            .await
30382            .expect_err("expired completion must be rejected");
30383        let Error::QueryFailed(failure) = error else {
30384            panic!("expected typed query failure");
30385        };
30386        assert_eq!(failure.status, 409);
30387        assert_eq!(failure.reason, "query_task_timed_out");
30388
30389        let mut worker = Worker::new(client, "rust-workers")
30390            .worker_id("late-worker")
30391            .poll_timeout(Duration::from_millis(10));
30392        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30393        worker.register_query(
30394            "counter",
30395            "current",
30396            |_ctx, _args| async move { Ok(json!(8)) },
30397        );
30398
30399        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
30400        assert_eq!(
30401            worker
30402                .run_once()
30403                .await
30404                .expect("worker continues after late completion"),
30405            0
30406        );
30407        assert_eq!(
30408            server.request_count("/api/worker/query-tasks/query-late/complete"),
30409            2
30410        );
30411        assert_eq!(
30412            server.request_count("/api/worker/query-tasks/query-late/fail"),
30413            0,
30414            "a server completion rejection must not be reported as an encoding failure"
30415        );
30416    }
30417
30418    #[tokio::test]
30419    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
30420        let server = MockWorkerServer::start();
30421        let client = Client::builder(server.base_url())
30422            .timeout(Duration::from_secs(2))
30423            .build()
30424            .expect("client");
30425        let mut worker = Worker::new(client, "rust-workers")
30426            .worker_id("joined-worker")
30427            .poll_timeout(Duration::from_millis(10));
30428        worker.register_workflow(
30429            "joined.workflow",
30430            |_ctx, _input| async move { Ok(Value::Null) },
30431        );
30432        worker.register_activity(
30433            "joined.activity",
30434            |_ctx, _input| async move { Ok(Value::Null) },
30435        );
30436        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
30437            Ok(Value::Null)
30438        });
30439
30440        worker
30441            .run_until(tokio::time::sleep(Duration::from_millis(20)))
30442            .await
30443            .expect("normal shutdown");
30444
30445        let deregistration_path = "/api/worker/registrations/mock-worker";
30446        assert_eq!(server.request_count(deregistration_path), 1);
30447        for poll_path in [
30448            "/api/worker/workflow-tasks/poll",
30449            "/api/worker/activity-tasks/poll",
30450            "/api/worker/query-tasks/poll",
30451        ] {
30452            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
30453        }
30454        assert_eq!(
30455            server.captured_paths().last().map(String::as_str),
30456            Some(deregistration_path),
30457            "deregistration must start only after every poller has joined"
30458        );
30459    }
30460
30461    #[tokio::test]
30462    async fn registration_failure_does_not_deregister() {
30463        let server = MockWorkerServer::rejected_registration();
30464        let client = Client::builder(server.base_url())
30465            .timeout(Duration::from_secs(2))
30466            .build()
30467            .expect("client");
30468        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
30469
30470        let error = worker
30471            .run_until(async {})
30472            .await
30473            .expect_err("registration must fail");
30474        assert!(matches!(
30475            error,
30476            Error::Http {
30477                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30478                ..
30479            }
30480        ));
30481        assert!(server
30482            .captured_paths()
30483            .iter()
30484            .all(|path| !path.starts_with("/api/worker/registrations/")));
30485    }
30486
30487    #[tokio::test]
30488    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
30489        let server = MockWorkerServer::rejected_registration_protocol();
30490        let client = Client::builder(server.base_url())
30491            .timeout(Duration::from_secs(2))
30492            .build()
30493            .expect("client");
30494        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
30495
30496        let error = worker
30497            .run_until(async {})
30498            .await
30499            .expect_err("a protocol 1.16 server must reject this worker");
30500        let Error::Protocol(failure) = error else {
30501            panic!("expected typed protocol rejection");
30502        };
30503        assert_eq!(failure.reason, "unsupported_protocol_version");
30504        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
30505        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
30506        assert_eq!(
30507            server
30508                .worker_protocol_for("/api/worker/register")
30509                .as_deref(),
30510            Some(WORKER_PROTOCOL_VERSION)
30511        );
30512    }
30513
30514    #[tokio::test]
30515    async fn declined_registration_does_not_deregister() {
30516        let server = MockWorkerServer::declined_registration();
30517        let client = Client::builder(server.base_url())
30518            .timeout(Duration::from_secs(2))
30519            .build()
30520            .expect("client");
30521        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
30522
30523        let error = worker
30524            .run_until(async {})
30525            .await
30526            .expect_err("declined registration must fail");
30527        assert!(matches!(error, Error::WorkerLoop(_)));
30528        assert!(error.to_string().contains("was not accepted"));
30529        assert!(server
30530            .captured_paths()
30531            .iter()
30532            .all(|path| !path.starts_with("/api/worker/registrations/")));
30533    }
30534
30535    #[tokio::test]
30536    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
30537        let server = MockWorkerServer::rejected_deregistration();
30538        let client = Client::builder(server.base_url())
30539            .timeout(Duration::from_secs(2))
30540            .build()
30541            .expect("client");
30542        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
30543
30544        let error = worker
30545            .run_until(async {})
30546            .await
30547            .expect_err("deregistration must fail");
30548        assert!(matches!(
30549            error,
30550            Error::Http {
30551                status: reqwest::StatusCode::FORBIDDEN,
30552                ..
30553            }
30554        ));
30555        assert_eq!(
30556            server.request_count("/api/worker/registrations/mock-worker"),
30557            1
30558        );
30559    }
30560
30561    #[tokio::test]
30562    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
30563        let server = MockWorkerServer::rejected_deregistration_protocol();
30564        let client = Client::builder(server.base_url())
30565            .timeout(Duration::from_secs(2))
30566            .build()
30567            .expect("client");
30568        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
30569
30570        let error = worker
30571            .run_until(async {})
30572            .await
30573            .expect_err("protocol rejection must fail shutdown");
30574        let Error::Protocol(failure) = error else {
30575            panic!("expected typed protocol failure");
30576        };
30577        assert_eq!(failure.reason, "unsupported_protocol_version");
30578        assert_eq!(
30579            failure.requested_version.as_deref(),
30580            Some(WORKER_PROTOCOL_VERSION)
30581        );
30582        assert_eq!(
30583            server.request_count("/api/worker/registrations/mock-worker"),
30584            1
30585        );
30586    }
30587
30588    #[tokio::test]
30589    async fn primary_poller_error_retains_deregistration_failure_context() {
30590        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
30591        let client = Client::builder(server.base_url())
30592            .timeout(Duration::from_secs(2))
30593            .build()
30594            .expect("client");
30595        let mut worker = Worker::new(client, "rust-workers")
30596            .worker_id("combined-failure")
30597            .poll_timeout(Duration::from_millis(10));
30598        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
30599            Ok(Value::Null)
30600        });
30601
30602        let error = worker
30603            .run()
30604            .await
30605            .expect_err("worker and cleanup must fail");
30606        let summary = error.to_string();
30607        assert!(summary.contains("authentication_failed"));
30608        assert!(summary.contains("worker cannot deregister"));
30609        let Error::WorkerShutdown {
30610            primary,
30611            deregistration,
30612        } = error
30613        else {
30614            panic!("expected combined worker shutdown error");
30615        };
30616        assert!(matches!(
30617            *primary,
30618            Error::Http {
30619                status: reqwest::StatusCode::UNAUTHORIZED,
30620                ..
30621            }
30622        ));
30623        assert!(matches!(
30624            *deregistration,
30625            Error::Http {
30626                status: reqwest::StatusCode::FORBIDDEN,
30627                ..
30628            }
30629        ));
30630        assert_eq!(
30631            server.request_count("/api/worker/registrations/mock-worker"),
30632            1
30633        );
30634    }
30635
30636    #[tokio::test]
30637    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
30638        let server = MockWorkerServer::start();
30639        let client = Client::builder(server.base_url())
30640            .timeout(Duration::from_secs(2))
30641            .build()
30642            .expect("client");
30643        let mut worker = Worker::new(client, "rust-workers")
30644            .worker_id("activity-only-worker")
30645            .poll_timeout(Duration::from_millis(10));
30646
30647        worker.register_activity(
30648            "activity.only",
30649            |_ctx, _args| async move { Ok(Value::Null) },
30650        );
30651
30652        worker.run_until(async {}).await.expect("run worker");
30653    }
30654
30655    #[tokio::test]
30656    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
30657        let server = MockWorkerServer::start();
30658        let client = Client::builder(server.base_url())
30659            .timeout(Duration::from_secs(2))
30660            .build()
30661            .expect("client");
30662        let mut worker = Worker::new(client, "rust-workers")
30663            .worker_id("workflow-only-worker")
30664            .poll_timeout(Duration::from_millis(10));
30665
30666        worker.register_workflow(
30667            "workflow.only",
30668            |_ctx, _input| async move { Ok(Value::Null) },
30669        );
30670
30671        worker.run_until(async {}).await.expect("run worker");
30672    }
30673
30674    #[tokio::test]
30675    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
30676        let server = MockWorkerServer::start();
30677        let client = Client::builder(server.base_url())
30678            .timeout(Duration::from_secs(2))
30679            .build()
30680            .expect("client");
30681        let observations = Arc::new(Mutex::new(Vec::new()));
30682        let observed = Arc::clone(&observations);
30683        let mut worker = Worker::new(client, "rust-workers")
30684            .worker_id("observed-heartbeat-worker")
30685            .poll_timeout(Duration::from_millis(10))
30686            .on_worker_heartbeat(move |observation| {
30687                observed
30688                    .lock()
30689                    .expect("heartbeat observations")
30690                    .push(observation.clone());
30691            });
30692
30693        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
30694            Ok(Value::Null)
30695        });
30696        let acknowledged = Arc::clone(&observations);
30697        worker
30698            .run_until(async move {
30699                tokio::time::timeout(Duration::from_secs(2), async move {
30700                    loop {
30701                        if !acknowledged
30702                            .lock()
30703                            .expect("heartbeat observations")
30704                            .is_empty()
30705                        {
30706                            break;
30707                        }
30708                        tokio::time::sleep(Duration::from_millis(1)).await;
30709                    }
30710                })
30711                .await
30712                .expect("heartbeat acknowledgement within timeout");
30713            })
30714            .await
30715            .expect("run worker");
30716
30717        let observations = observations.lock().expect("heartbeat observations");
30718        let first = observations.first().expect("heartbeat acknowledgement");
30719        assert_eq!(first.worker_id, "observed-heartbeat-worker");
30720        assert_eq!(first.task_queue, "rust-workers");
30721        assert!(first.acknowledged_at_unix_millis > 0);
30722        assert_eq!(first.acknowledgement, json!({}));
30723    }
30724
30725    #[tokio::test]
30726    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
30727        let server = MockWorkerServer::delayed_heartbeat_worker();
30728        let client = Client::builder(server.base_url())
30729            .timeout(Duration::from_secs(3))
30730            .build()
30731            .expect("client");
30732        let observations = Arc::new(Mutex::new(Vec::new()));
30733        let observed = Arc::clone(&observations);
30734        let mut worker = Worker::new(client, "rust-snapshot-workers")
30735            .max_concurrent_workflow_tasks(1)
30736            .max_concurrent_activity_tasks(1)
30737            .worker_id("rust-snapshot-worker")
30738            .poll_timeout(Duration::from_millis(10))
30739            .on_worker_heartbeat(move |observation| {
30740                observed
30741                    .lock()
30742                    .expect("heartbeat observations")
30743                    .push(observation.clone());
30744            });
30745
30746        worker.register_workflow("snapshot", |ctx, _input| async move {
30747            ctx.wait_signal("finish").await?;
30748            Ok(json!({"status": "finished"}))
30749        });
30750        worker.register_query("snapshot", "current", |ctx, _args| async move {
30751            Ok(json!(ctx
30752                .signals("increment")
30753                .iter()
30754                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30755                .sum::<i64>()))
30756        });
30757        worker.register_activity("cancel-aware", |_ctx, _args| async move {
30758            Ok(json!({"late": "completion"}))
30759        });
30760
30761        worker
30762            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
30763            .await
30764            .expect("delayed heartbeat must allow a clean worker shutdown");
30765
30766        let observations = observations.lock().expect("heartbeat observations");
30767        assert!(
30768            observations.len() >= 3,
30769            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
30770        );
30771        assert!(
30772            observations.windows(2).all(|pair| {
30773                pair[1].acknowledged_at_unix_millis
30774                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30775                    >= 850
30776            }),
30777            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
30778        );
30779        drop(observations);
30780
30781        let heartbeat_times = server.request_times("/api/worker/heartbeat");
30782        let delayed_request_at = *heartbeat_times
30783            .get(1)
30784            .expect("intentionally delayed heartbeat request");
30785        let delay_window_start = delayed_request_at + Duration::from_millis(100);
30786        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
30787        for path in [
30788            "/api/worker/workflow-tasks/poll",
30789            "/api/worker/activity-tasks/poll",
30790            "/api/worker/query-tasks/poll",
30791        ] {
30792            assert!(
30793                server
30794                    .request_times(path)
30795                    .iter()
30796                    .any(|received_at| *received_at >= delay_window_start
30797                        && *received_at <= delay_window_end),
30798                "{path} must keep polling while a heartbeat acknowledgement is delayed"
30799            );
30800        }
30801        assert!(
30802            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
30803            "workflow work must be settled"
30804        );
30805        assert!(
30806            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
30807            "activity work must be settled"
30808        );
30809        assert!(
30810            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
30811            "query work must be settled"
30812        );
30813    }
30814
30815    #[tokio::test]
30816    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
30817        let server = MockWorkerServer::heartbeat_retry_worker();
30818        let client = Client::builder(server.base_url())
30819            .timeout(Duration::from_secs(2))
30820            .build()
30821            .expect("client");
30822        let observations = Arc::new(Mutex::new(Vec::new()));
30823        let observed = Arc::clone(&observations);
30824        let worker = Worker::new(client, "rust-workers")
30825            .worker_id("heartbeat-retry-worker")
30826            .retry_policy(WorkerRetryPolicy {
30827                max_retries: 1,
30828                initial_backoff: Duration::from_millis(300),
30829                max_backoff: Duration::from_millis(300),
30830            })
30831            .on_worker_heartbeat(move |observation| {
30832                observed
30833                    .lock()
30834                    .expect("heartbeat observations")
30835                    .push(observation.clone());
30836            });
30837
30838        worker
30839            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
30840            .await
30841            .expect("retryable heartbeat failure must remain bounded and recover");
30842
30843        let observations = observations.lock().expect("heartbeat observations");
30844        assert!(observations.len() >= 3, "heartbeat retry must recover");
30845        assert!(
30846            observations.windows(2).all(|pair| {
30847                pair[1]
30848                    .acknowledged_at_unix_millis
30849                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30850                    >= 850
30851            }),
30852            "a successful retry must start a fresh advertised cadence: {observations:?}"
30853        );
30854        assert_eq!(
30855            server.request_count("/api/worker/heartbeat"),
30856            observations.len() + 1,
30857            "one retryable failure must add exactly one bounded request"
30858        );
30859    }
30860
30861    #[tokio::test]
30862    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
30863        let server = MockWorkerServer::waiting_query_worker();
30864        let client = Client::builder(server.base_url())
30865            .timeout(Duration::from_secs(2))
30866            .build()
30867            .expect("client");
30868        let observations = Arc::new(Mutex::new(Vec::new()));
30869        let observed = Arc::clone(&observations);
30870        let mut worker = Worker::new(client, "rust-snapshot-workers")
30871            .worker_id("rust-snapshot-worker")
30872            .poll_timeout(Duration::from_millis(10))
30873            .on_worker_heartbeat(move |observation| {
30874                observed
30875                    .lock()
30876                    .expect("heartbeat observations")
30877                    .push(observation.clone());
30878            });
30879
30880        worker.register_workflow("snapshot", |ctx, _input| async move {
30881            ctx.wait_signal("finish").await?;
30882            Ok(json!({"status": "finished"}))
30883        });
30884        worker.register_query("snapshot", "current", |ctx, _args| async move {
30885            let current = ctx
30886                .signals("increment")
30887                .iter()
30888                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30889                .sum::<i64>();
30890            Ok(json!(current))
30891        });
30892        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
30893        worker
30894            .declare_workflow_signals("snapshot", &["finish"])
30895            .expect("declare finish signal");
30896
30897        worker
30898            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
30899            .await
30900            .expect("pending workflow and query poller must remain live until shutdown");
30901
30902        assert!(
30903            observations.lock().expect("heartbeat observations").len() >= 4,
30904            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
30905        );
30906        assert!(
30907            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
30908            "workflow polling must continue after empty replay acknowledgements"
30909        );
30910        assert!(
30911            server.request_count("/api/worker/query-tasks/poll") >= 2,
30912            "query polling must continue after serving the current query"
30913        );
30914        assert_eq!(
30915            server.request_body("/api/worker/register")["capabilities"],
30916            json!([
30917                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
30918                "workflow_entry_arguments_validation",
30919                DURABLE_SELECTION_CAPABILITY,
30920                MEMO_UPSERTS_CAPABILITY,
30921                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
30922                QUERY_TASKS_CAPABILITY,
30923                WORKFLOW_UPDATES_CAPABILITY,
30924                MESSAGE_STREAMS_CAPABILITY
30925            ])
30926        );
30927        assert_eq!(
30928            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
30929            json!({
30930                "queries": ["current"],
30931                "query_contracts": [{
30932                    "name": "current",
30933                    "parameters": [{
30934                        "name": "args", "position": 0, "required": false,
30935                        "variadic": true, "type": null, "allows_null": true,
30936                        "default_available": false, "default": null,
30937                    }],
30938                }],
30939                "signals": ["finish"],
30940                "signal_contracts": [{
30941                    "name": "finish",
30942                    "parameters": [{
30943                        "name": "args", "position": 0, "required": false,
30944                        "variadic": true, "type": null, "allows_null": true,
30945                        "default_available": false, "default": null,
30946                    }],
30947                }],
30948                "updates": ["replace"],
30949                "update_contracts": [{
30950                    "name": "replace",
30951                    "parameters": [{
30952                        "name": "args", "position": 0, "required": false,
30953                        "variadic": true, "type": null, "allows_null": true,
30954                        "default_available": false, "default": null,
30955                    }],
30956                }],
30957                "update_validators": [],
30958            })
30959        );
30960
30961        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
30962        assert_eq!(
30963            opened["commands"],
30964            json!([{
30965                "type": "open_signal_wait",
30966                "signal_name": "finish",
30967            }])
30968        );
30969
30970        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
30971            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
30972            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
30973            let failure = server.request_body(&fail_path);
30974            assert_eq!(
30975                failure["failure"]["type"],
30976                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
30977            );
30978            assert_eq!(server.request_count(&completion_path), 0);
30979        }
30980
30981        let query_completion =
30982            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
30983        assert_eq!(query_completion["result"], json!(8));
30984
30985        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
30986        assert_eq!(
30987            server.request_count(terminal_path),
30988            1,
30989            "the matching signal must settle the workflow exactly once"
30990        );
30991        let terminal = server.request_body(terminal_path);
30992        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
30993        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
30994        assert_eq!(
30995            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
30996                .expect("terminal workflow result"),
30997            json!({"status": "finished"})
30998        );
30999    }
31000
31001    #[tokio::test]
31002    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
31003        let server = MockWorkerServer::transient_worker_failures();
31004        let client = Client::builder(server.base_url())
31005            .timeout(Duration::from_secs(2))
31006            .build()
31007            .expect("client");
31008        let mut worker = Worker::new(client, "rust-workers")
31009            .max_concurrent_workflow_tasks(1)
31010            .max_concurrent_activity_tasks(1)
31011            .worker_id("retry-worker")
31012            .poll_timeout(Duration::from_millis(10))
31013            .retry_policy(WorkerRetryPolicy {
31014                max_retries: 2,
31015                initial_backoff: Duration::from_millis(1),
31016                max_backoff: Duration::from_millis(1),
31017            });
31018        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31019        worker.register_activity(
31020            "counter.activity",
31021            |_ctx, _input| async move { Ok(Value::Null) },
31022        );
31023        worker.register_query(
31024            "counter",
31025            "current",
31026            |_ctx, _args| async move { Ok(json!(8)) },
31027        );
31028
31029        worker
31030            .run_until(tokio::time::sleep(Duration::from_millis(75)))
31031            .await
31032            .expect("transient failures must not stop the worker");
31033
31034        for path in [
31035            "/api/worker/heartbeat",
31036            "/api/worker/workflow-tasks/poll",
31037            "/api/worker/activity-tasks/poll",
31038            "/api/worker/query-tasks/poll",
31039        ] {
31040            assert!(
31041                server.request_count(path) >= 2,
31042                "{path} must continue after its transient failure"
31043            );
31044        }
31045    }
31046
31047    #[tokio::test]
31048    async fn worker_continues_after_long_poll_capacity_backpressure() {
31049        let server = MockWorkerServer::capacity_limited_activity_poll();
31050        let client = Client::builder(server.base_url())
31051            .timeout(Duration::from_secs(2))
31052            .build()
31053            .expect("client");
31054        let mut worker = Worker::new(client, "rust-workers")
31055            .worker_id("capacity-worker")
31056            .poll_timeout(Duration::from_millis(10))
31057            .retry_policy(WorkerRetryPolicy {
31058                max_retries: 0,
31059                initial_backoff: Duration::from_millis(1),
31060                max_backoff: Duration::from_millis(1),
31061            });
31062        worker.register_activity("capacity.activity", |_ctx, _input| async move {
31063            Ok(json!({"handled": true}))
31064        });
31065
31066        worker
31067            .run_until(tokio::time::sleep(Duration::from_millis(50)))
31068            .await
31069            .expect("capacity backpressure must not stop the worker");
31070
31071        assert!(
31072            server.request_count("/api/worker/activity-tasks/poll") >= 2,
31073            "the activity poller must continue after capacity backpressure"
31074        );
31075        assert_eq!(
31076            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
31077            1,
31078            "the worker must complete work returned after capacity recovers"
31079        );
31080    }
31081
31082    #[test]
31083    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
31084        let capacity = Error::Http {
31085            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31086            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
31087        };
31088        assert_eq!(
31089            worker_poll_capacity_retry_after(&capacity),
31090            Some(Duration::from_secs(3))
31091        );
31092
31093        let rejected_capacity = Error::Http {
31094            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31095            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
31096        };
31097        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
31098        assert!(!worker_operation_is_retryable(&rejected_capacity));
31099
31100        let ordinary_rate_limit = Error::Http {
31101            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31102            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
31103                .to_string(),
31104        };
31105        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
31106        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
31107    }
31108
31109    #[tokio::test]
31110    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
31111        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31112            poll_failures_per_path: 8,
31113            heartbeat_failures: 8,
31114            ..MockWorkerBehavior::default()
31115        });
31116        let client = Client::builder(server.base_url())
31117            .timeout(Duration::from_secs(2))
31118            .build()
31119            .expect("client");
31120        let acknowledgements = Arc::new(AtomicUsize::new(0));
31121        let observed = Arc::clone(&acknowledgements);
31122        let mut worker = Worker::new(client, "rust-workers")
31123            .max_concurrent_workflow_tasks(1)
31124            .max_concurrent_activity_tasks(1)
31125            .recover_transient_outages(true)
31126            .poll_timeout(Duration::from_millis(10))
31127            .retry_policy(WorkerRetryPolicy {
31128                max_retries: 2,
31129                initial_backoff: Duration::from_millis(2),
31130                max_backoff: Duration::from_millis(5),
31131            })
31132            .on_worker_heartbeat(move |_| {
31133                observed.fetch_add(1, Ordering::SeqCst);
31134            });
31135        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31136        worker.register_activity(
31137            "counter.activity",
31138            |_ctx, _input| async move { Ok(Value::Null) },
31139        );
31140        worker.register_query("counter", "current", |_ctx, _args| async move {
31141            Ok(Value::Null)
31142        });
31143
31144        worker
31145            .run_until(tokio::time::sleep(Duration::from_millis(500)))
31146            .await
31147            .expect("a recoverable outage must not stop the service worker");
31148
31149        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
31150        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
31151        for path in [
31152            "/api/worker/workflow-tasks/poll",
31153            "/api/worker/activity-tasks/poll",
31154            "/api/worker/query-tasks/poll",
31155        ] {
31156            let bodies = server.request_bodies(path);
31157            assert!(bodies.len() >= 10, "{path} must resume after recovery");
31158            let first = &bodies[0]["poll_request_id"];
31159            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
31160            for body in &bodies[..9] {
31161                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
31162            }
31163            assert_ne!(&bodies[9]["poll_request_id"], first);
31164            let times = server.request_times(path);
31165            for pair in times[..9].windows(2) {
31166                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
31167            }
31168        }
31169    }
31170
31171    #[tokio::test]
31172    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
31173        for heartbeat_outage in [false, true] {
31174            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31175                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
31176                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
31177                ..MockWorkerBehavior::default()
31178            });
31179            let client = Client::builder(server.base_url()).build().expect("client");
31180            let mut worker = Worker::new(client, "rust-workers")
31181                .max_concurrent_workflow_tasks(1)
31182                .max_concurrent_activity_tasks(1)
31183                .recover_transient_outages(true)
31184                .retry_policy(WorkerRetryPolicy {
31185                    max_retries: 1,
31186                    initial_backoff: Duration::from_secs(5),
31187                    max_backoff: Duration::from_secs(5),
31188                });
31189            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31190            let started = Instant::now();
31191            worker
31192                .run_until(tokio::time::sleep(Duration::from_millis(200)))
31193                .await
31194                .expect("shutdown during an outage is a normal stop");
31195            assert!(started.elapsed() < Duration::from_secs(1));
31196            let path = if heartbeat_outage {
31197                "/api/worker/heartbeat"
31198            } else {
31199                "/api/worker/workflow-tasks/poll"
31200            };
31201            assert_eq!(server.request_count(path), 1);
31202            assert_eq!(
31203                server.request_count("/api/worker/registrations/mock-worker"),
31204                1
31205            );
31206        }
31207    }
31208
31209    #[tokio::test]
31210    async fn worker_outage_recovery_keeps_run_once_bounded() {
31211        let server = MockWorkerServer::unavailable_polls();
31212        let client = Client::builder(server.base_url()).build().expect("client");
31213        let mut worker = Worker::new(client, "rust-workers")
31214            .recover_transient_outages(true)
31215            .retry_policy(WorkerRetryPolicy {
31216                max_retries: 2,
31217                initial_backoff: Duration::from_millis(1),
31218                max_backoff: Duration::from_millis(1),
31219            });
31220        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31221        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
31222        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
31223    }
31224
31225    #[tokio::test]
31226    async fn worker_outage_recovery_respects_disabled_retries() {
31227        let server = MockWorkerServer::unavailable_polls();
31228        let client = Client::builder(server.base_url()).build().expect("client");
31229        let mut worker = Worker::new(client, "rust-workers")
31230            .max_concurrent_workflow_tasks(1)
31231            .max_concurrent_activity_tasks(1)
31232            .recover_transient_outages(true)
31233            .retry_policy(WorkerRetryPolicy {
31234                max_retries: 0,
31235                ..WorkerRetryPolicy::default()
31236            });
31237        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31238        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
31239        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31240    }
31241
31242    #[tokio::test]
31243    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
31244        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31245            heartbeat_failures: usize::MAX,
31246            unauthorized_polls: true,
31247            ..MockWorkerBehavior::default()
31248        });
31249        let client = Client::builder(server.base_url()).build().expect("client");
31250        let mut worker = Worker::new(client, "rust-workers")
31251            .max_concurrent_workflow_tasks(1)
31252            .max_concurrent_activity_tasks(1)
31253            .recover_transient_outages(true)
31254            .retry_policy(WorkerRetryPolicy {
31255                max_retries: 1,
31256                initial_backoff: Duration::from_secs(5),
31257                max_backoff: Duration::from_secs(5),
31258            });
31259        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31260        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
31261            .await
31262            .expect("fatal poll errors must interrupt heartbeat recovery")
31263            .expect_err("authentication failure is terminal");
31264        assert!(
31265            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
31266        );
31267        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31268    }
31269
31270    #[tokio::test]
31271    async fn worker_bounds_transport_retries() {
31272        let server = MockWorkerServer::unavailable_polls();
31273        let client = Client::builder(server.base_url())
31274            .timeout(Duration::from_secs(2))
31275            .build()
31276            .expect("client");
31277        let mut worker = Worker::new(client, "rust-workers")
31278            .max_concurrent_workflow_tasks(1)
31279            .max_concurrent_activity_tasks(1)
31280            .worker_id("bounded-retry-worker")
31281            .poll_timeout(Duration::from_millis(10))
31282            .retry_policy(WorkerRetryPolicy {
31283                max_retries: 2,
31284                initial_backoff: Duration::from_millis(1),
31285                max_backoff: Duration::from_millis(1),
31286            });
31287        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31288
31289        let error = worker.run().await.expect_err("retry bound must terminate");
31290        assert!(matches!(error, Error::Transport(_)));
31291        assert_eq!(
31292            server.request_count("/api/worker/workflow-tasks/poll"),
31293            3,
31294            "one initial request plus exactly two retries"
31295        );
31296    }
31297
31298    #[tokio::test]
31299    async fn worker_retry_policy_can_disable_poll_retries() {
31300        let server = MockWorkerServer::unavailable_polls();
31301        let client = Client::builder(server.base_url())
31302            .timeout(Duration::from_secs(2))
31303            .build()
31304            .expect("client");
31305        let mut worker = Worker::new(client, "rust-workers")
31306            .worker_id("no-retry-worker")
31307            .poll_timeout(Duration::from_millis(10))
31308            .retry_policy(WorkerRetryPolicy {
31309                max_retries: 0,
31310                initial_backoff: Duration::from_millis(1),
31311                max_backoff: Duration::from_millis(1),
31312            });
31313        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31314
31315        let error = worker
31316            .run_once()
31317            .await
31318            .expect_err("disabled retries must return the first transport failure");
31319        assert!(matches!(error, Error::Transport(_)));
31320        assert_eq!(
31321            server.request_count("/api/worker/workflow-tasks/poll"),
31322            1,
31323            "max_retries=0 must send only the initial request"
31324        );
31325    }
31326
31327    #[tokio::test]
31328    async fn worker_does_not_retry_authentication_failures() {
31329        let server = MockWorkerServer::unauthorized_polls();
31330        let client = Client::builder(server.base_url())
31331            .timeout(Duration::from_secs(2))
31332            .build()
31333            .expect("client");
31334        let mut worker = Worker::new(client, "rust-workers")
31335            .max_concurrent_workflow_tasks(1)
31336            .max_concurrent_activity_tasks(1)
31337            .worker_id("unauthorized-worker")
31338            .recover_transient_outages(true)
31339            .poll_timeout(Duration::from_millis(10));
31340        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31341
31342        let error = worker
31343            .run()
31344            .await
31345            .expect_err("authentication must terminate");
31346        let Error::Http { status, body } = error else {
31347            panic!("expected stable HTTP authentication error");
31348        };
31349        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
31350        assert!(body.contains("authentication_failed"));
31351        assert_eq!(
31352            server.request_count("/api/worker/workflow-tasks/poll"),
31353            1,
31354            "authentication failures must not be retried"
31355        );
31356    }
31357
31358    #[test]
31359    fn duplicate_registration_keeps_the_original_workflow() {
31360        let client = Client::new("http://127.0.0.1:9").expect("client");
31361        let mut worker = Worker::new(client, "registration-tests");
31362        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31363        let original = Arc::clone(&worker.workflows["same"].execute);
31364        worker
31365            .set_workflow_definition_sources("same", &["first workflow source"])
31366            .expect("source identity");
31367        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
31368        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
31369        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
31370        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
31371    }
31372
31373    #[test]
31374    fn duplicate_registration_keeps_the_original_activity() {
31375        let client = Client::new("http://127.0.0.1:9").expect("client");
31376        let mut worker = Worker::new(client, "registration-tests");
31377        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
31378        let original = Arc::clone(&worker.activities["same"]);
31379        worker.register_activity_avro_value("same", |_ctx, _input| async {
31380            Ok(AvroValue::String("second".into()))
31381        });
31382        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
31383    }
31384
31385    #[test]
31386    fn duplicate_registration_keeps_original_query_and_update_handlers() {
31387        let client = Client::new("http://127.0.0.1:9").expect("client");
31388        let mut worker = Worker::new(client, "registration-tests");
31389        worker.register_query("orders", "same", |_ctx, _input| async {
31390            Ok(json!("first"))
31391        });
31392        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
31393            panic!("snapshot query");
31394        };
31395        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
31396            Ok(json!("second"))
31397        });
31398        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
31399            panic!("duplicate replaced the query adapter");
31400        };
31401        assert!(Arc::ptr_eq(&original, retained));
31402        worker.register_update("orders", "same", |_ctx, _input| async {
31403            Ok(json!("first"))
31404        });
31405        let original = Arc::clone(&worker.updates["orders"]["same"]);
31406        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
31407            Ok(AvroValue::Null)
31408        });
31409        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
31410    }
31411
31412    #[tokio::test]
31413    async fn duplicate_registration_fails_before_server_contact() {
31414        let server = MockWorkerServer::start();
31415        let client = Client::builder(server.base_url()).build().expect("client");
31416        let mut worker =
31417            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
31418        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31419        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
31420        let error = worker
31421            .run_once()
31422            .await
31423            .expect_err("ambiguous worker must not poll");
31424        assert!(
31425            error.to_string().contains("duplicate_registration"),
31426            "{error}"
31427        );
31428        assert!(server.requests.lock().expect("requests").is_empty());
31429    }
31430
31431    #[derive(Clone, Debug)]
31432    struct CapturedRequest {
31433        headers: String,
31434        method: String,
31435        path: String,
31436        authorization: Option<String>,
31437        namespace: Option<String>,
31438        worker_protocol: Option<String>,
31439        control_protocol: Option<String>,
31440        body: String,
31441        received_at: Instant,
31442    }
31443
31444    struct MockWorkerServer {
31445        addr: SocketAddr,
31446        stop: Arc<AtomicBool>,
31447        requests: Arc<Mutex<Vec<CapturedRequest>>>,
31448        thread: Option<thread::JoinHandle<()>>,
31449    }
31450
31451    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
31452
31453    #[derive(Clone, Copy, Default)]
31454    struct MockWorkerBehavior {
31455        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
31456        request_override: Option<RequestOverride>,
31457        /// Close the connection after reading the request, without any response.
31458        drop_request: Option<fn(&str, usize) -> bool>,
31459        storage_refusals: usize,
31460        storage_path: Option<&'static str>,
31461        storage_unavailable: bool,
31462        storage_mid_poll: bool,
31463        storage_activity: bool,
31464        storage_query: bool,
31465        storage_wrong_poll_id: bool,
31466        reject_query_protocol: bool,
31467        reject_query_completion: bool,
31468        waiting_query_worker: bool,
31469        decline_registration: bool,
31470        complete_named_signal: bool,
31471        poll_failures_per_path: usize,
31472        long_poll_capacity_responses_per_path: usize,
31473        heartbeat_failures: usize,
31474        heartbeat_failure_request: Option<usize>,
31475        delayed_heartbeat_request: Option<usize>,
31476        heartbeat_response_delay: Duration,
31477        concurrent_requests: bool,
31478        unauthorized_polls: bool,
31479        reject_registration: bool,
31480        reject_registration_protocol: bool,
31481        reject_deregistration: bool,
31482        reject_deregistration_protocol: bool,
31483        cancelled_activity: bool,
31484        draining_polls: bool,
31485        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
31486        workflow_completion_status: Option<&'static str>,
31487        workflow_completion_body: Option<&'static str>,
31488    }
31489
31490    impl MockWorkerServer {
31491        fn start() -> Self {
31492            Self::start_with_behavior(MockWorkerBehavior::default())
31493        }
31494
31495        fn reject_query_protocol() -> Self {
31496            Self::start_with_behavior(MockWorkerBehavior {
31497                reject_query_protocol: true,
31498                ..MockWorkerBehavior::default()
31499            })
31500        }
31501
31502        fn reject_query_completion() -> Self {
31503            Self::start_with_behavior(MockWorkerBehavior {
31504                reject_query_completion: true,
31505                ..MockWorkerBehavior::default()
31506            })
31507        }
31508
31509        fn waiting_query_worker() -> Self {
31510            Self::start_with_behavior(MockWorkerBehavior {
31511                waiting_query_worker: true,
31512                complete_named_signal: true,
31513                ..MockWorkerBehavior::default()
31514            })
31515        }
31516
31517        fn transient_worker_failures() -> Self {
31518            Self::start_with_behavior(MockWorkerBehavior {
31519                poll_failures_per_path: 1,
31520                heartbeat_failures: 1,
31521                ..MockWorkerBehavior::default()
31522            })
31523        }
31524
31525        fn consecutive_poll_failures(count: usize) -> Self {
31526            Self::start_with_behavior(MockWorkerBehavior {
31527                poll_failures_per_path: count,
31528                ..MockWorkerBehavior::default()
31529            })
31530        }
31531
31532        fn capacity_limited_activity_poll() -> Self {
31533            Self::start_with_behavior(MockWorkerBehavior {
31534                long_poll_capacity_responses_per_path: 1,
31535                ..MockWorkerBehavior::default()
31536            })
31537        }
31538
31539        fn delayed_heartbeat_worker() -> Self {
31540            Self::start_with_behavior(MockWorkerBehavior {
31541                waiting_query_worker: true,
31542                delayed_heartbeat_request: Some(2),
31543                heartbeat_response_delay: Duration::from_millis(1_500),
31544                concurrent_requests: true,
31545                cancelled_activity: true,
31546                ..MockWorkerBehavior::default()
31547            })
31548        }
31549
31550        fn heartbeat_retry_worker() -> Self {
31551            Self::start_with_behavior(MockWorkerBehavior {
31552                waiting_query_worker: true,
31553                heartbeat_failure_request: Some(2),
31554                concurrent_requests: true,
31555                ..MockWorkerBehavior::default()
31556            })
31557        }
31558
31559        fn unavailable_polls() -> Self {
31560            Self::start_with_behavior(MockWorkerBehavior {
31561                poll_failures_per_path: usize::MAX,
31562                ..MockWorkerBehavior::default()
31563            })
31564        }
31565
31566        fn unauthorized_polls() -> Self {
31567            Self::start_with_behavior(MockWorkerBehavior {
31568                unauthorized_polls: true,
31569                ..MockWorkerBehavior::default()
31570            })
31571        }
31572
31573        fn rejected_registration() -> Self {
31574            Self::start_with_behavior(MockWorkerBehavior {
31575                reject_registration: true,
31576                ..MockWorkerBehavior::default()
31577            })
31578        }
31579
31580        fn rejected_registration_protocol() -> Self {
31581            Self::start_with_behavior(MockWorkerBehavior {
31582                reject_registration_protocol: true,
31583                ..MockWorkerBehavior::default()
31584            })
31585        }
31586
31587        fn declined_registration() -> Self {
31588            Self::start_with_behavior(MockWorkerBehavior {
31589                decline_registration: true,
31590                ..MockWorkerBehavior::default()
31591            })
31592        }
31593
31594        fn rejected_deregistration() -> Self {
31595            Self::start_with_behavior(MockWorkerBehavior {
31596                reject_deregistration: true,
31597                ..MockWorkerBehavior::default()
31598            })
31599        }
31600
31601        fn rejected_deregistration_protocol() -> Self {
31602            Self::start_with_behavior(MockWorkerBehavior {
31603                reject_deregistration_protocol: true,
31604                ..MockWorkerBehavior::default()
31605            })
31606        }
31607
31608        fn unauthorized_polls_and_rejected_deregistration() -> Self {
31609            Self::start_with_behavior(MockWorkerBehavior {
31610                unauthorized_polls: true,
31611                reject_deregistration: true,
31612                ..MockWorkerBehavior::default()
31613            })
31614        }
31615
31616        fn cancelled_activity() -> Self {
31617            Self::start_with_behavior(MockWorkerBehavior {
31618                cancelled_activity: true,
31619                ..MockWorkerBehavior::default()
31620            })
31621        }
31622
31623        fn draining_polls() -> Self {
31624            Self::start_with_behavior(MockWorkerBehavior {
31625                draining_polls: true,
31626                ..MockWorkerBehavior::default()
31627            })
31628        }
31629
31630        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
31631            Self::start_with_behavior(MockWorkerBehavior {
31632                invalid_task_payload_codec: Some(codec),
31633                ..MockWorkerBehavior::default()
31634            })
31635        }
31636
31637        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
31638            Self::start_with_behavior(MockWorkerBehavior {
31639                workflow_completion_status: Some(status),
31640                workflow_completion_body: Some(body),
31641                ..MockWorkerBehavior::default()
31642            })
31643        }
31644
31645        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
31646            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
31647            listener
31648                .set_nonblocking(true)
31649                .expect("configure mock listener");
31650            let addr = listener.local_addr().expect("mock server address");
31651            let stop = Arc::new(AtomicBool::new(false));
31652            let server_stop = Arc::clone(&stop);
31653            let requests = Arc::new(Mutex::new(Vec::new()));
31654            let server_requests = Arc::clone(&requests);
31655            let thread = thread::spawn(move || {
31656                let mut request_threads = Vec::new();
31657                while !server_stop.load(Ordering::SeqCst) {
31658                    match listener.accept() {
31659                        Ok((mut stream, _)) => {
31660                            if behavior.concurrent_requests {
31661                                let requests = Arc::clone(&server_requests);
31662                                request_threads.push(thread::spawn(move || {
31663                                    handle_mock_worker_request(&mut stream, &requests, behavior)
31664                                }));
31665                            } else {
31666                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
31667                            }
31668                        }
31669                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
31670                            let mut index = 0;
31671                            while index < request_threads.len() {
31672                                if request_threads[index].is_finished() {
31673                                    request_threads
31674                                        .swap_remove(index)
31675                                        .join()
31676                                        .expect("join mock request");
31677                                } else {
31678                                    index += 1;
31679                                }
31680                            }
31681                            thread::sleep(Duration::from_millis(5));
31682                        }
31683                        Err(_) => break,
31684                    }
31685                }
31686                for request_thread in request_threads {
31687                    request_thread.join().expect("join mock request");
31688                }
31689            });
31690
31691            Self {
31692                addr,
31693                stop,
31694                requests,
31695                thread: Some(thread),
31696            }
31697        }
31698
31699        fn base_url(&self) -> String {
31700            format!("http://{}", self.addr)
31701        }
31702
31703        fn worker_protocol_for(&self, path: &str) -> Option<String> {
31704            self.requests
31705                .lock()
31706                .expect("captured requests")
31707                .iter()
31708                .find(|request| request.path == path)
31709                .and_then(|request| request.worker_protocol.clone())
31710        }
31711
31712        fn control_protocol_for(&self, path: &str) -> Option<String> {
31713            self.requests
31714                .lock()
31715                .expect("captured requests")
31716                .iter()
31717                .find(|request| request.path == path)
31718                .and_then(|request| request.control_protocol.clone())
31719        }
31720
31721        fn method_for(&self, path: &str) -> Option<String> {
31722            self.requests
31723                .lock()
31724                .expect("captured requests")
31725                .iter()
31726                .find(|request| request.path == path)
31727                .map(|request| request.method.clone())
31728        }
31729
31730        fn authorization_for(&self, path: &str) -> Option<String> {
31731            self.requests
31732                .lock()
31733                .expect("captured requests")
31734                .iter()
31735                .find(|request| request.path == path)
31736                .and_then(|request| request.authorization.clone())
31737        }
31738
31739        fn namespace_for(&self, path: &str) -> Option<String> {
31740            self.requests
31741                .lock()
31742                .expect("captured requests")
31743                .iter()
31744                .find(|request| request.path == path)
31745                .and_then(|request| request.namespace.clone())
31746        }
31747
31748        fn request_count(&self, path: &str) -> usize {
31749            self.requests
31750                .lock()
31751                .expect("captured requests")
31752                .iter()
31753                .filter(|request| request.path == path)
31754                .count()
31755        }
31756
31757        fn captured_paths(&self) -> Vec<String> {
31758            self.requests
31759                .lock()
31760                .expect("captured requests")
31761                .iter()
31762                .map(|request| request.path.clone())
31763                .collect()
31764        }
31765
31766        fn request_times(&self, path: &str) -> Vec<Instant> {
31767            self.requests
31768                .lock()
31769                .expect("captured requests")
31770                .iter()
31771                .filter(|request| request.path == path)
31772                .map(|request| request.received_at)
31773                .collect()
31774        }
31775
31776        fn request_body(&self, path: &str) -> Value {
31777            let requests = self.requests.lock().expect("captured requests");
31778            let body = &requests
31779                .iter()
31780                .find(|request| request.path == path)
31781                .unwrap_or_else(|| panic!("missing request for {path}"))
31782                .body;
31783            serde_json::from_str(body).unwrap_or_else(|error| {
31784                panic!("invalid JSON request body for {path}: {error}: {body:?}")
31785            })
31786        }
31787
31788        fn request_bodies(&self, path: &str) -> Vec<Value> {
31789            self.requests
31790                .lock()
31791                .expect("captured requests")
31792                .iter()
31793                .filter(|request| request.path == path)
31794                .map(|request| {
31795                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
31796                        panic!(
31797                            "invalid JSON request body for {path}: {error}: {:?}",
31798                            request.body
31799                        )
31800                    })
31801                })
31802                .collect()
31803        }
31804
31805        fn request_headers(&self, path: &str) -> Vec<String> {
31806            self.requests
31807                .lock()
31808                .expect("captured requests")
31809                .iter()
31810                .filter(|request| request.path == path)
31811                .map(|request| request.headers.clone())
31812                .collect()
31813        }
31814    }
31815
31816    impl Drop for MockWorkerServer {
31817        fn drop(&mut self) {
31818            self.stop.store(true, Ordering::SeqCst);
31819            let _ = TcpStream::connect(self.addr);
31820
31821            if let Some(thread) = self.thread.take() {
31822                thread.join().expect("join mock server");
31823            }
31824        }
31825    }
31826
31827    #[test]
31828    fn closed_mock_connection_is_not_a_worker_request() {
31829        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
31830        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
31831        let (mut stream, _) = listener.accept().unwrap();
31832        drop(client);
31833        let requests = Arc::new(Mutex::new(Vec::new()));
31834        handle_mock_worker_request(
31835            &mut stream,
31836            &requests,
31837            MockWorkerBehavior {
31838                request_override: Some(|_, _, _| {
31839                    panic!("closed connection cannot invoke an HTTP handler")
31840                }),
31841                ..MockWorkerBehavior::default()
31842            },
31843        );
31844        assert!(requests.lock().unwrap().is_empty());
31845    }
31846
31847    fn handle_mock_worker_request(
31848        stream: &mut TcpStream,
31849        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
31850        behavior: MockWorkerBehavior,
31851    ) {
31852        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
31853        let mut buffer = [0_u8; 8192];
31854        let mut request = Vec::new();
31855
31856        loop {
31857            match stream.read(&mut buffer) {
31858                Ok(0) => break,
31859                Ok(read) => {
31860                    request.extend_from_slice(&buffer[..read]);
31861                    if mock_request_is_complete(&request) {
31862                        break;
31863                    }
31864                }
31865                Err(error)
31866                    if matches!(
31867                        error.kind(),
31868                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
31869                    ) =>
31870                {
31871                    break;
31872                }
31873                Err(_) => return,
31874            }
31875        }
31876
31877        if !mock_request_is_complete(&request) {
31878            return;
31879        }
31880
31881        let request = String::from_utf8_lossy(&request);
31882        let body = request
31883            .split_once("\r\n\r\n")
31884            .map(|(_, body)| body)
31885            .unwrap_or_default();
31886        let path = request
31887            .lines()
31888            .next()
31889            .and_then(|line| line.split_whitespace().nth(1))
31890            .unwrap_or_default();
31891        let method = request
31892            .lines()
31893            .next()
31894            .and_then(|line| line.split_whitespace().next())
31895            .unwrap_or_default();
31896        let authorization = request.lines().find_map(|line| {
31897            let (name, value) = line.split_once(':')?;
31898            name.eq_ignore_ascii_case("Authorization")
31899                .then(|| value.trim().to_string())
31900        });
31901        let namespace = request.lines().find_map(|line| {
31902            let (name, value) = line.split_once(':')?;
31903            name.eq_ignore_ascii_case("X-Namespace")
31904                .then(|| value.trim().to_string())
31905        });
31906        let worker_protocol = request.lines().find_map(|line| {
31907            let (name, value) = line.split_once(':')?;
31908            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
31909                .then(|| value.trim().to_string())
31910        });
31911        let control_protocol = request.lines().find_map(|line| {
31912            let (name, value) = line.split_once(':')?;
31913            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
31914                .then(|| value.trim().to_string())
31915        });
31916        let request_number = {
31917            let mut requests = requests.lock().expect("captured requests");
31918            requests.push(CapturedRequest {
31919                headers: request
31920                    .split_once("\r\n\r\n")
31921                    .map_or("", |(headers, _)| headers)
31922                    .to_owned(),
31923                method: method.to_string(),
31924                path: path.to_string(),
31925                authorization,
31926                namespace,
31927                worker_protocol: worker_protocol.clone(),
31928                control_protocol,
31929                body: body.to_string(),
31930                received_at: Instant::now(),
31931            });
31932            requests
31933                .iter()
31934                .filter(|request| request.path == path)
31935                .count()
31936        };
31937
31938        if behavior
31939            .drop_request
31940            .is_some_and(|dropped| dropped(path, request_number))
31941        {
31942            return;
31943        }
31944        if let Some(response) = behavior
31945            .request_override
31946            .and_then(|handler| handler(path, body, request_number))
31947        {
31948            write_mock_response(stream, response.0, &response.1);
31949            return;
31950        }
31951        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
31952            write_mock_response(stream, response.0, &response.1);
31953            return;
31954        }
31955        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
31956            return;
31957        }
31958        let pressure_path = behavior
31959            .storage_path
31960            .is_some_and(|part| path.contains(part));
31961        let prior_failures = if path.ends_with("/poll") {
31962            behavior.poll_failures_per_path
31963        } else {
31964            0
31965        };
31966        if pressure_path
31967            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
31968        {
31969            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
31970            let poll_id = path
31971                .ends_with("/poll")
31972                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
31973            let mut refusal = storage_refusal(
31974                poll_id,
31975                behavior.storage_unavailable,
31976                behavior.storage_mid_poll,
31977            );
31978            if behavior.storage_wrong_poll_id {
31979                refusal["poll_request_id"] = json!("wrong-poll");
31980            }
31981            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
31982            return;
31983        }
31984        if path.contains("/storage-task/")
31985            || path.contains("/storage-activity/")
31986            || path.contains("/storage-query/")
31987        {
31988            write_mock_response(stream, "200 OK", "{}");
31989            return;
31990        }
31991        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
31992            write_mock_response(stream, "200 OK", &json!({"task":{
31993                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
31994                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
31995                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
31996                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
31997                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
31998            }}).to_string());
31999            return;
32000        }
32001        if behavior.storage_activity
32002            && path == "/api/worker/activity-tasks/poll"
32003            && request_number == 1
32004        {
32005            write_mock_response(stream, "200 OK", &json!({"task":{
32006                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
32007                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32008                "attempt_number":7, "lease_owner":"storage-worker"
32009            }}).to_string());
32010            return;
32011        }
32012
32013        if path == "/api/worker/register" {
32014            if behavior.reject_registration_protocol {
32015                write_mock_response(
32016                    stream,
32017                    "400 Bad Request",
32018                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
32019                );
32020                return;
32021            }
32022            if behavior.reject_registration {
32023                write_mock_response(
32024                    stream,
32025                    "503 Service Unavailable",
32026                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
32027                );
32028                return;
32029            }
32030        }
32031
32032        if path.starts_with("/api/worker/registrations/") {
32033            if behavior.reject_deregistration_protocol {
32034                write_mock_response(
32035                    stream,
32036                    "400 Bad Request",
32037                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
32038                );
32039            } else if behavior.reject_deregistration {
32040                write_mock_response(
32041                    stream,
32042                    "403 Forbidden",
32043                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
32044                );
32045            } else {
32046                write_mock_response(
32047                    stream,
32048                    "200 OK",
32049                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
32050                );
32051            }
32052            return;
32053        }
32054
32055        let is_poll = matches!(
32056            path,
32057            "/api/worker/workflow-tasks/poll"
32058                | "/api/worker/activity-tasks/poll"
32059                | "/api/worker/query-tasks/poll"
32060        );
32061        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
32062            write_mock_response(
32063                stream,
32064                "429 Too Many Requests",
32065                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
32066            );
32067            return;
32068        }
32069        if is_poll && request_number <= behavior.poll_failures_per_path {
32070            return;
32071        }
32072        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
32073            return;
32074        }
32075        if path == "/api/worker/heartbeat"
32076            && behavior.heartbeat_failure_request == Some(request_number)
32077        {
32078            return;
32079        }
32080        if path == "/api/worker/heartbeat"
32081            && behavior.delayed_heartbeat_request == Some(request_number)
32082        {
32083            thread::sleep(behavior.heartbeat_response_delay);
32084        }
32085        if behavior.unauthorized_polls && is_poll {
32086            write_mock_response(
32087                stream,
32088                "401 Unauthorized",
32089                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
32090            );
32091            return;
32092        }
32093        if behavior.draining_polls && is_poll {
32094            write_mock_response(
32095                stream,
32096                "409 Conflict",
32097                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
32098            );
32099            return;
32100        }
32101
32102        if let Some(codec_case) = behavior.invalid_task_payload_codec {
32103            if is_poll && request_number == 1 {
32104                let mut task = match path {
32105                    "/api/worker/workflow-tasks/poll" => json!({
32106                        "task_id": "codec-workflow",
32107                        "workflow_type": "codec.workflow",
32108                        "payload_codec": DEFAULT_CODEC,
32109                        "workflow_task_attempt": 1,
32110                        "lease_owner": "codec-worker"
32111                    }),
32112                    "/api/worker/activity-tasks/poll" => json!({
32113                        "task_id": "codec-activity",
32114                        "activity_attempt_id": "codec-activity-attempt",
32115                        "activity_type": "codec.activity",
32116                        "payload_codec": DEFAULT_CODEC,
32117                        "attempt_number": 1,
32118                        "lease_owner": "codec-worker"
32119                    }),
32120                    "/api/worker/query-tasks/poll" => json!({
32121                        "query_task_id": "codec-query",
32122                        "query_task_attempt": 1,
32123                        "workflow_type": "codec.workflow",
32124                        "query_name": "known",
32125                        "payload_codec": DEFAULT_CODEC,
32126                        "lease_owner": "codec-worker"
32127                    }),
32128                    _ => unreachable!("is_poll limits task codec probe paths"),
32129                };
32130                codec_case.apply(&mut task);
32131                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
32132                return;
32133            }
32134
32135            if matches!(
32136                path,
32137                "/api/worker/workflow-tasks/codec-workflow/fail"
32138                    | "/api/worker/activity-tasks/codec-activity/fail"
32139                    | "/api/worker/query-tasks/codec-query/fail"
32140            ) {
32141                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
32142                return;
32143            }
32144        }
32145
32146        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
32147            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
32148            let body = format!(
32149                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
32150            );
32151            write_mock_response(stream, "400 Bad Request", &body);
32152            return;
32153        }
32154
32155        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
32156        {
32157            write_mock_response(
32158                stream,
32159                "409 Conflict",
32160                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
32161            );
32162            return;
32163        }
32164
32165        if behavior.workflow_completion_status.is_some()
32166            && path == "/api/worker/workflow-tasks/poll"
32167            && request_number == 1
32168        {
32169            write_mock_response(
32170                stream,
32171                "200 OK",
32172                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"}}"#,
32173            );
32174            return;
32175        }
32176
32177        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
32178            if let (Some(status), Some(body)) = (
32179                behavior.workflow_completion_status,
32180                behavior.workflow_completion_body,
32181            ) {
32182                write_mock_response(stream, status, body);
32183                return;
32184            }
32185        }
32186
32187        if behavior.waiting_query_worker {
32188            if behavior.complete_named_signal
32189                && path == "/api/worker/workflow-tasks/poll"
32190                && request_number == 1
32191            {
32192                let body = json!({
32193                    "task": {
32194                        "task_id": "snapshot-open",
32195                        "workflow_id": "snapshot-1",
32196                        "run_id": "snapshot-run-1",
32197                        "workflow_type": "snapshot",
32198                        "payload_codec": DEFAULT_CODEC,
32199                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32200                            .expect("Avro workflow arguments"),
32201                        "history_events": [],
32202                        "workflow_task_attempt": 1,
32203                        "lease_owner": "rust-snapshot-worker"
32204                    }
32205                })
32206                .to_string();
32207                write_mock_response(stream, "200 OK", &body);
32208                return;
32209            }
32210
32211            let signal_request = request_number - usize::from(behavior.complete_named_signal);
32212            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
32213            if path == "/api/worker/workflow-tasks/poll"
32214                && signal_request >= 1
32215                && signal_request <= signal_request_limit
32216            {
32217                let finish = behavior.complete_named_signal && signal_request == 3;
32218                let amounts = if signal_request == 1 {
32219                    vec![3]
32220                } else {
32221                    vec![3, 5]
32222                };
32223                let task_id = if signal_request == 1 {
32224                    "snapshot-wait-3"
32225                } else if finish {
32226                    "snapshot-finish"
32227                } else {
32228                    "snapshot-wait-5"
32229                };
32230                let mut history_events = std::iter::once(json!({
32231                    "event_type": "SignalWaitOpened",
32232                    "payload": {"sequence": 1, "signal_name": "finish"}
32233                }))
32234                .chain(amounts.iter().enumerate().map(|(index, amount)| {
32235                    json!({
32236                        "event_type": "SignalReceived",
32237                        "payload": {
32238                            "signal_id": format!("increment-{amount}"),
32239                            "signal_name": "increment",
32240                            "workflow_sequence": index + 2,
32241                            "payload_codec": DEFAULT_CODEC,
32242                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32243                                .expect("Avro signal envelope")
32244                        }
32245                    })
32246                }))
32247                .collect::<Vec<_>>();
32248                let (resume_id, resume_name, resume_arguments) = if finish {
32249                    history_events.push(json!({
32250                        "event_type": "SignalReceived",
32251                        "payload": {
32252                            "signal_id": "finish",
32253                            "signal_name": "finish",
32254                            "workflow_sequence": 4,
32255                            "payload_codec": DEFAULT_CODEC,
32256                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32257                                .expect("Avro finish signal envelope")
32258                        }
32259                    }));
32260                    (
32261                        "finish".to_string(),
32262                        "finish".to_string(),
32263                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
32264                            .expect("Avro finish resume signal"),
32265                    )
32266                } else {
32267                    let amount = amounts.last().expect("amount");
32268                    (
32269                        format!("increment-{amount}"),
32270                        "increment".to_string(),
32271                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32272                            .expect("Avro increment resume signal"),
32273                    )
32274                };
32275                let body = json!({
32276                    "task": {
32277                        "task_id": task_id,
32278                        "workflow_id": "snapshot-1",
32279                        "run_id": "snapshot-run-1",
32280                        "workflow_type": "snapshot",
32281                        "payload_codec": DEFAULT_CODEC,
32282                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32283                            .expect("Avro workflow arguments"),
32284                        "history_events": history_events,
32285                        "workflow_task_attempt": 1,
32286                        "workflow_signal_id": resume_id,
32287                        "signal_name": resume_name,
32288                        "signal_arguments": resume_arguments,
32289                        "lease_owner": "rust-snapshot-worker"
32290                    }
32291                })
32292                .to_string();
32293                write_mock_response(stream, "200 OK", &body);
32294                return;
32295            }
32296
32297            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
32298                let history_events = [3, 5]
32299                    .into_iter()
32300                    .enumerate()
32301                    .map(|(index, amount)| {
32302                        json!({
32303                            "event_type": "SignalReceived",
32304                            "payload": {
32305                                "signal_id": format!("increment-{amount}"),
32306                                "signal_name": "increment",
32307                                "workflow_sequence": index + 2,
32308                                "payload_codec": DEFAULT_CODEC,
32309                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32310                                    .expect("Avro query signal envelope")
32311                            }
32312                        })
32313                    })
32314                    .collect::<Vec<_>>();
32315                let body = json!({
32316                    "task": {
32317                        "query_task_id": "snapshot-current",
32318                        "query_task_attempt": 1,
32319                        "lease_owner": "rust-snapshot-worker",
32320                        "workflow_id": "snapshot-1",
32321                        "run_id": "snapshot-run-1",
32322                        "workflow_type": "snapshot",
32323                        "query_name": "current",
32324                        "payload_codec": DEFAULT_CODEC,
32325                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32326                            .expect("Avro workflow arguments"),
32327                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32328                            .expect("Avro query arguments"),
32329                        "history_events": history_events,
32330                        "run_status": "waiting"
32331                    }
32332                })
32333                .to_string();
32334                write_mock_response(stream, "200 OK", &body);
32335                return;
32336            }
32337
32338            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
32339                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
32340            {
32341                write_mock_response(
32342                    stream,
32343                    "200 OK",
32344                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
32345                );
32346                return;
32347            }
32348
32349            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
32350                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
32351                return;
32352            }
32353
32354            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
32355                write_mock_response(
32356                    stream,
32357                    "200 OK",
32358                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
32359                );
32360                return;
32361            }
32362
32363            if path == "/api/worker/query-tasks/snapshot-current/complete" {
32364                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
32365                return;
32366            }
32367        }
32368
32369        if matches!(
32370            path,
32371            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
32372        ) {
32373            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32374                .expect("typed mock result");
32375            let body = json!({
32376                "result": typed_fidelity_probe().into_json().expect("result projection"),
32377                "result_envelope": result,
32378            })
32379            .to_string();
32380            write_mock_response(stream, "200 OK", &body);
32381            return;
32382        }
32383
32384        if path == "/api/workflows/typed-1" {
32385            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32386                .expect("typed mock result");
32387            let body = json!({
32388                "workflow_id": "typed-1",
32389                "run_id": "run-typed-1",
32390                "workflow_type": "typed.echo",
32391                "status": "completed",
32392                "output": typed_fidelity_probe().into_json().expect("output projection"),
32393                "output_envelope": result,
32394            })
32395            .to_string();
32396            write_mock_response(stream, "200 OK", &body);
32397            return;
32398        }
32399
32400        let (status, body) = match path {
32401            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
32402            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
32403            "/api/workflows" => (
32404                "201 Created",
32405                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
32406            ),
32407            "/api/worker/register" if behavior.decline_registration => (
32408                "200 OK",
32409                r#"{"worker_id":"declined-worker","registered":false}"#,
32410            ),
32411            "/api/worker/register" if behavior.waiting_query_worker => (
32412                "200 OK",
32413                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
32414            ),
32415            "/api/worker/register" => (
32416                "200 OK",
32417                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
32418            ),
32419            "/api/worker/heartbeat" => ("200 OK", "{}"),
32420            "/api/worker/activity-tasks/poll"
32421                if behavior.cancelled_activity && request_number == 1 =>
32422            {
32423                (
32424                    "200 OK",
32425                    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"}}"#,
32426                )
32427            }
32428            "/api/worker/activity-tasks/poll"
32429                if behavior.long_poll_capacity_responses_per_path > 0
32430                    && request_number
32431                        == behavior
32432                            .long_poll_capacity_responses_per_path
32433                            .saturating_add(1) =>
32434            {
32435                (
32436                    "200 OK",
32437                    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"}}"#,
32438                )
32439            }
32440            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
32441                ("200 OK", r#"{"task":null}"#)
32442            }
32443            "/api/worker/query-tasks/poll"
32444                if behavior.reject_query_completion && request_number == 1 =>
32445            {
32446                (
32447                    "200 OK",
32448                    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"}}"#,
32449                )
32450            }
32451            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
32452            "/api/worker/query-tasks/query-capture/complete"
32453            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
32454            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
32455                "200 OK",
32456                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
32457            ),
32458            "/api/worker/activity-tasks/activity-cancel/complete" => (
32459                "409 Conflict",
32460                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
32461            ),
32462            "/api/worker/activity-tasks/activity-typed/complete"
32463            | "/api/worker/activity-tasks/activity-typed/fail"
32464            | "/api/worker/activity-tasks/capacity-activity/complete"
32465            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
32466            "/api/workflows/counter-1/query/current" => (
32467                "200 OK",
32468                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
32469            ),
32470            "/api/workflows/counter-1/query/missing" => (
32471                "404 Not Found",
32472                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
32473            ),
32474            "/api/workflows/wf-lifecycle/cancel" => (
32475                "200 OK",
32476                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
32477            ),
32478            "/api/workflows/wf-lifecycle/terminate" => (
32479                "200 OK",
32480                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
32481            ),
32482            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
32483                "200 OK",
32484                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
32485            ),
32486            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
32487                "200 OK",
32488                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
32489            ),
32490            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
32491                "202 Accepted",
32492                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
32493            ),
32494            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
32495                "200 OK",
32496                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}"#,
32497            ),
32498            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
32499                "409 Conflict",
32500                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
32501            ),
32502            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
32503            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
32504                "409 Conflict",
32505                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
32506            ),
32507            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
32508                "200 OK",
32509                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"}]}}"#,
32510            ),
32511            "/api/workflows/wf-cancelled" => (
32512                "200 OK",
32513                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
32514            ),
32515            "/api/workflows/wf-terminated" => (
32516                "200 OK",
32517                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
32518            ),
32519            "/api/workflows/wf-timed-out" => (
32520                "200 OK",
32521                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
32522            ),
32523            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
32524                "200 OK",
32525                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
32526            ),
32527            "/api/workflows/wf-selected" => (
32528                "200 OK",
32529                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
32530            ),
32531            "/api/workflows/wf-selected/runs/run-selected" => (
32532                "200 OK",
32533                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
32534            ),
32535            _ => ("404 Not Found", r#"{"message":"not found"}"#),
32536        };
32537        write_mock_response(stream, status, body);
32538    }
32539
32540    fn mock_request_is_complete(request: &[u8]) -> bool {
32541        let Some(header_end) = request
32542            .windows(4)
32543            .position(|window| window == b"\r\n\r\n")
32544            .map(|position| position + 4)
32545        else {
32546            return false;
32547        };
32548        let headers = String::from_utf8_lossy(&request[..header_end]);
32549        let content_length = headers.lines().find_map(|line| {
32550            let (name, value) = line.split_once(':')?;
32551            name.eq_ignore_ascii_case("content-length")
32552                .then(|| value.trim().parse::<usize>().ok())
32553                .flatten()
32554        });
32555
32556        request.len() >= header_end + content_length.unwrap_or(0)
32557    }
32558
32559    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
32560        let response = format!(
32561            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
32562            body.len()
32563        );
32564
32565        let _ = stream.write_all(response.as_bytes());
32566        let _ = stream.flush();
32567    }
32568
32569    fn typed_activity_failure_server(
32570        path: &str,
32571        _body: &str,
32572        request_number: usize,
32573    ) -> Option<(&'static str, String)> {
32574        match path {
32575            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32576                "200 OK",
32577                r#"{"task":{"task_id":"typed-failure","activity_attempt_id":"typed-attempt","activity_type":"typed.failure","payload_codec":"avro","arguments":{"codec":"avro","blob":"wwHioz3/VYAiNwwA"},"attempt_number":1,"lease_owner":"typed-worker"}}"#.into(),
32578            )),
32579            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
32580            _ => None,
32581        }
32582    }
32583
32584    #[tokio::test]
32585    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
32586        for non_retryable in [false, true] {
32587            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32588                request_override: Some(typed_activity_failure_server),
32589                ..MockWorkerBehavior::default()
32590            });
32591            let client = Client::builder(server.base_url()).build().unwrap();
32592            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
32593            worker.register_activity("typed.failure", move |_, _| async move {
32594                Err(ActivityError::new("PaymentDeclined", "card declined")
32595                    .non_retryable(non_retryable)
32596                    .into())
32597            });
32598            assert_eq!(worker.run_once().await.unwrap(), 1);
32599            assert_eq!(
32600                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
32601                json!({
32602                    "activity_attempt_id": "typed-attempt",
32603                    "lease_owner": "typed-worker",
32604                    "failure": {"type": "PaymentDeclined", "message": "card declined",
32605                                "non_retryable": non_retryable}
32606                })
32607            );
32608        }
32609    }
32610
32611    fn activity_completion_backend_recovery(
32612        path: &str,
32613        _body: &str,
32614        request_number: usize,
32615    ) -> Option<(&'static str, String)> {
32616        match path {
32617            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32618                "200 OK",
32619                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(),
32620            )),
32621            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
32622                "503 Service Unavailable",
32623                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(),
32624            )),
32625            "/api/worker/activity-tasks/recover-activity/complete" => Some((
32626                "200 OK",
32627                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32628            )),
32629            _ => None,
32630        }
32631    }
32632
32633    fn workflow_completion_backend_recovery(
32634        path: &str,
32635        _body: &str,
32636        request_number: usize,
32637    ) -> Option<(&'static str, String)> {
32638        match path {
32639            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
32640                "200 OK",
32641                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
32642            )),
32643            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
32644                "503 Service Unavailable",
32645                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(),
32646            )),
32647            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
32648                "200 OK",
32649                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32650            )),
32651            _ => None,
32652        }
32653    }
32654
32655    fn workflow_completion_lock_pressure(
32656        path: &str,
32657        body: &str,
32658        request_number: usize,
32659    ) -> Option<(&'static str, String)> {
32660        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
32661            return Some((
32662                "503 Service Unavailable",
32663                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32664                    "outcome":"deferred", "recorded":false, "retryable":true,
32665                    "retry_after_seconds":1, "task_id":"recover-workflow",
32666                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
32667                    "backend":{"driver":"sqlite", "lock_pressure":true}})
32668                .to_string(),
32669            ));
32670        }
32671        workflow_completion_backend_recovery(path, body, request_number)
32672    }
32673
32674    fn workflow_completion_lock_pressure_forever(
32675        path: &str,
32676        body: &str,
32677        request_number: usize,
32678    ) -> Option<(&'static str, String)> {
32679        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
32680            return workflow_completion_lock_pressure(path, body, 1);
32681        }
32682        workflow_completion_lock_pressure(path, body, request_number)
32683    }
32684
32685    fn workflow_completion_lock_pressure_then_expired(
32686        path: &str,
32687        body: &str,
32688        request_number: usize,
32689    ) -> Option<(&'static str, String)> {
32690        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32691            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
32692                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
32693        }
32694        workflow_completion_lock_pressure(path, body, request_number)
32695    }
32696
32697    fn workflow_completion_lock_pressure_then_slow(
32698        path: &str,
32699        body: &str,
32700        request_number: usize,
32701    ) -> Option<(&'static str, String)> {
32702        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32703            thread::sleep(Duration::from_secs(2));
32704        }
32705        workflow_completion_lock_pressure(path, body, request_number)
32706    }
32707
32708    fn workflow_completion_pressure_then_backend_loss(
32709        path: &str,
32710        body: &str,
32711        request_number: usize,
32712    ) -> Option<(&'static str, String)> {
32713        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32714            return Some((
32715                "503 Service Unavailable",
32716                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
32717                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
32718                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
32719                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
32720                .to_string(),
32721            ));
32722        }
32723        workflow_completion_lock_pressure(path, body, request_number)
32724    }
32725
32726    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
32727        let client = Client::builder(server.base_url())
32728            .timeout(Duration::from_secs(4))
32729            .build()
32730            .unwrap();
32731        let mut worker = Worker::new(client, "recover-queue")
32732            .worker_id("recover-worker")
32733            .poll_timeout(Duration::from_millis(10));
32734        worker.register_workflow("recover.workflow", move |_ctx, _args| {
32735            let calls = Arc::clone(&calls);
32736            async move {
32737                calls.fetch_add(1, Ordering::SeqCst);
32738                Ok(json!("done"))
32739            }
32740        });
32741        worker
32742    }
32743
32744    #[tokio::test]
32745    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
32746        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32747            request_override: Some(workflow_completion_lock_pressure_forever),
32748            ..MockWorkerBehavior::default()
32749        });
32750        let calls = Arc::new(AtomicUsize::new(0));
32751        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32752            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32753        worker
32754            .client
32755            .worker_storage_admission
32756            .as_mut()
32757            .unwrap()
32758            .workflow_completion_retry_deadline =
32759            Some(tokio::time::Instant::now() + Duration::from_millis(250));
32760        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
32761            .await
32762            .unwrap();
32763        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32764        assert_eq!(calls.load(Ordering::SeqCst), 1);
32765        assert_eq!(
32766            server
32767                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32768                .len(),
32769            1
32770        );
32771    }
32772
32773    #[tokio::test]
32774    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
32775        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32776            request_override: Some(workflow_completion_lock_pressure_then_slow),
32777            ..MockWorkerBehavior::default()
32778        });
32779        let calls = Arc::new(AtomicUsize::new(0));
32780        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32781            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32782        let start = tokio::time::Instant::now();
32783        worker
32784            .client
32785            .worker_storage_admission
32786            .as_mut()
32787            .unwrap()
32788            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32789        assert!(matches!(
32790            worker.poll_workflow_once().await,
32791            Err(Error::Timeout)
32792        ));
32793        assert!(start.elapsed() < Duration::from_secs(2));
32794        assert_eq!(calls.load(Ordering::SeqCst), 1);
32795        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32796        assert_eq!(bodies.len(), 2);
32797        assert_eq!(bodies[0], bodies[1]);
32798    }
32799
32800    #[tokio::test]
32801    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
32802        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32803            request_override: Some(workflow_completion_pressure_then_backend_loss),
32804            ..MockWorkerBehavior::default()
32805        });
32806        let calls = Arc::new(AtomicUsize::new(0));
32807        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32808            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32809        let start = tokio::time::Instant::now();
32810        worker
32811            .client
32812            .worker_storage_admission
32813            .as_mut()
32814            .unwrap()
32815            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32816        let result = worker.poll_workflow_once().await;
32817        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32818        assert!(start.elapsed() < Duration::from_secs(2));
32819        assert_eq!(calls.load(Ordering::SeqCst), 1);
32820        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32821        assert_eq!(bodies.len(), 2);
32822        assert_eq!(bodies[0], bodies[1]);
32823    }
32824
32825    #[tokio::test]
32826    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
32827        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32828            request_override: Some(workflow_completion_lock_pressure_forever),
32829            ..MockWorkerBehavior::default()
32830        });
32831        let calls = Arc::new(AtomicUsize::new(0));
32832        let stop = Arc::new(AtomicBool::new(false));
32833        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
32834            .with_storage_admission(Arc::clone(&stop));
32835        let shutdown = async {
32836            while server
32837                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32838                .is_empty()
32839            {
32840                tokio::time::sleep(Duration::from_millis(10)).await;
32841            }
32842            stop.store(true, Ordering::SeqCst);
32843        };
32844        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
32845            tokio::join!(worker.poll_workflow_once(), shutdown)
32846        })
32847        .await
32848        .unwrap();
32849        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32850        assert_eq!(calls.load(Ordering::SeqCst), 1);
32851        assert_eq!(
32852            server
32853                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32854                .len(),
32855            1
32856        );
32857    }
32858
32859    #[tokio::test]
32860    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
32861        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32862            request_override: Some(workflow_completion_lock_pressure_then_expired),
32863            ..MockWorkerBehavior::default()
32864        });
32865        let calls = Arc::new(AtomicUsize::new(0));
32866        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
32867        let result = worker.run_once().await;
32868        assert!(
32869            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
32870        );
32871        assert_eq!(calls.load(Ordering::SeqCst), 1);
32872        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32873        assert_eq!(bodies.len(), 2);
32874        assert_eq!(bodies[0], bodies[1]);
32875        assert!(server
32876            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
32877            .is_empty());
32878    }
32879
32880    #[tokio::test]
32881    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
32882        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32883            request_override: Some(workflow_completion_lock_pressure),
32884            ..MockWorkerBehavior::default()
32885        });
32886        let client = Client::builder(server.base_url())
32887            .timeout(Duration::from_secs(2))
32888            .build()
32889            .unwrap();
32890        let calls = Arc::new(AtomicUsize::new(0));
32891        let mut worker = Worker::new(client, "recover-queue")
32892            .worker_id("recover-worker")
32893            .recover_transient_outages(true)
32894            .poll_timeout(Duration::from_millis(10))
32895            .retry_policy(WorkerRetryPolicy {
32896                max_retries: 1,
32897                initial_backoff: Duration::from_millis(10),
32898                max_backoff: Duration::from_millis(10),
32899            });
32900        worker.register_workflow("recover.workflow", {
32901            let calls = Arc::clone(&calls);
32902            move |_ctx, _args| {
32903                let calls = Arc::clone(&calls);
32904                async move {
32905                    calls.fetch_add(1, Ordering::SeqCst);
32906                    Ok(json!("done"))
32907                }
32908            }
32909        });
32910        let start = tokio::time::Instant::now();
32911        assert_eq!(worker.run_once().await.unwrap(), 1);
32912        assert!(start.elapsed() >= Duration::from_secs(1));
32913        assert_eq!(calls.load(Ordering::SeqCst), 1);
32914        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32915        assert_eq!(bodies.len(), 2);
32916        assert_eq!(bodies[0], bodies[1]);
32917    }
32918
32919    #[test]
32920    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
32921        let path = "/worker/workflow-tasks/recover-workflow/complete";
32922        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
32923        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32924            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
32925            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
32926            "backend":{"driver":"sqlite", "lock_pressure":true}});
32927        let error = |body: Value| Error::Http {
32928            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
32929            body: body.to_string(),
32930        };
32931        assert_eq!(
32932            worker_deferred_workflow_completion_retry_after(
32933                &error(response.clone()),
32934                path,
32935                Some(&request)
32936            ),
32937            Some(Duration::from_secs(1))
32938        );
32939        for (field, value) in [
32940            ("reason", json!("backend_unavailable")),
32941            ("operation", json!("complete_activity_task")),
32942            ("task_id", json!("other-task")),
32943            ("lease_owner", json!("other-owner")),
32944            ("workflow_task_attempt", json!(4)),
32945            ("recorded", json!(true)),
32946            ("recorded", Value::Null),
32947            ("recorded", json!("false")),
32948            ("retryable", json!(false)),
32949            ("retry_after_seconds", json!(0)),
32950            ("retry_after_seconds", json!(-1)),
32951            ("retry_after_seconds", json!(1.0)),
32952            ("retry_after_seconds", json!("1")),
32953            ("retry_after_seconds", json!(6)),
32954            ("backend", json!({"lock_pressure":false})),
32955        ] {
32956            let mut invalid = response.clone();
32957            invalid[field] = value;
32958            assert_eq!(
32959                worker_deferred_workflow_completion_retry_after(
32960                    &error(invalid),
32961                    path,
32962                    Some(&request)
32963                ),
32964                None,
32965                "invalid {field}"
32966            );
32967        }
32968        for field in [
32969            "reason",
32970            "operation",
32971            "task_id",
32972            "lease_owner",
32973            "workflow_task_attempt",
32974            "recorded",
32975            "retryable",
32976            "retry_after_seconds",
32977            "backend",
32978        ] {
32979            let mut missing = response.clone();
32980            missing.as_object_mut().unwrap().remove(field);
32981            assert_eq!(
32982                worker_deferred_workflow_completion_retry_after(
32983                    &error(missing),
32984                    path,
32985                    Some(&request)
32986                ),
32987                None,
32988                "missing {field}"
32989            );
32990        }
32991        assert_eq!(
32992            worker_deferred_workflow_completion_retry_after(
32993                &error(response.clone()),
32994                "/worker/activity-tasks/recover-workflow/complete",
32995                Some(&request)
32996            ),
32997            None
32998        );
32999        assert_eq!(
33000            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
33001            None
33002        );
33003        let wrong_status = Error::Http {
33004            status: reqwest::StatusCode::CONFLICT,
33005            body: response.to_string(),
33006        };
33007        assert_eq!(
33008            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
33009            None
33010        );
33011    }
33012
33013    fn activity_completion_stale_after_backend_recovery(
33014        path: &str,
33015        body: &str,
33016        request_number: usize,
33017    ) -> Option<(&'static str, String)> {
33018        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
33019            return Some((
33020                "409 Conflict",
33021                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(),
33022            ));
33023        }
33024        activity_completion_backend_recovery(path, body, request_number)
33025    }
33026
33027    fn activity_completion_remains_unavailable(
33028        path: &str,
33029        body: &str,
33030        request_number: usize,
33031    ) -> Option<(&'static str, String)> {
33032        if path == "/api/worker/activity-tasks/recover-activity/complete" {
33033            return activity_completion_backend_recovery(path, body, 1);
33034        }
33035        activity_completion_backend_recovery(path, body, request_number)
33036    }
33037
33038    #[tokio::test]
33039    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
33040        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33041            request_override: Some(activity_completion_backend_recovery),
33042            ..MockWorkerBehavior::default()
33043        });
33044        let client = Client::builder(server.base_url())
33045            .timeout(Duration::from_secs(2))
33046            .build()
33047            .expect("client");
33048        let handler_calls = Arc::new(AtomicUsize::new(0));
33049        let mut worker = Worker::new(client, "recover-queue")
33050            .worker_id("recover-worker")
33051            .poll_timeout(Duration::from_millis(10));
33052        worker.register_activity("recover.activity", {
33053            let handler_calls = Arc::clone(&handler_calls);
33054            move |_ctx, _args| {
33055                let handler_calls = Arc::clone(&handler_calls);
33056                async move {
33057                    handler_calls.fetch_add(1, Ordering::SeqCst);
33058                    Ok(json!("done"))
33059                }
33060            }
33061        });
33062
33063        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33064        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33065        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33066        assert_eq!(bodies.len(), 2);
33067        assert_eq!(bodies[0], bodies[1]);
33068    }
33069
33070    #[tokio::test]
33071    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
33072        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33073            request_override: Some(workflow_completion_backend_recovery),
33074            ..MockWorkerBehavior::default()
33075        });
33076        let client = Client::builder(server.base_url())
33077            .timeout(Duration::from_secs(2))
33078            .build()
33079            .expect("client");
33080        let handler_calls = Arc::new(AtomicUsize::new(0));
33081        let mut worker = Worker::new(client, "recover-queue")
33082            .worker_id("recover-worker")
33083            .poll_timeout(Duration::from_millis(10));
33084        worker.register_workflow("recover.workflow", {
33085            let handler_calls = Arc::clone(&handler_calls);
33086            move |_ctx, _args| {
33087                let handler_calls = Arc::clone(&handler_calls);
33088                async move {
33089                    handler_calls.fetch_add(1, Ordering::SeqCst);
33090                    Ok(json!("done"))
33091                }
33092            }
33093        });
33094
33095        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
33096        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33097        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
33098        assert_eq!(bodies.len(), 2);
33099        assert_eq!(bodies[0], bodies[1]);
33100    }
33101
33102    #[tokio::test]
33103    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
33104        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33105            request_override: Some(activity_completion_stale_after_backend_recovery),
33106            ..MockWorkerBehavior::default()
33107        });
33108        let client = Client::builder(server.base_url())
33109            .timeout(Duration::from_secs(2))
33110            .build()
33111            .expect("client");
33112        let handler_calls = Arc::new(AtomicUsize::new(0));
33113        let mut worker = Worker::new(client, "recover-queue")
33114            .worker_id("recover-worker")
33115            .poll_timeout(Duration::from_millis(10));
33116        worker.register_activity("recover.activity", {
33117            let handler_calls = Arc::clone(&handler_calls);
33118            move |_ctx, _args| {
33119                let handler_calls = Arc::clone(&handler_calls);
33120                async move {
33121                    handler_calls.fetch_add(1, Ordering::SeqCst);
33122                    Ok(json!("done"))
33123                }
33124            }
33125        });
33126
33127        assert_eq!(
33128            worker
33129                .run_once()
33130                .await
33131                .expect("authoritative stale outcome"),
33132            1
33133        );
33134        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33135        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33136        assert_eq!(bodies.len(), 2);
33137        assert_eq!(bodies[0], bodies[1]);
33138    }
33139
33140    #[test]
33141    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
33142        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
33143        let response = json!({
33144            "reason":"backend_unavailable", "operation":"complete_activity_task",
33145            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
33146            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
33147            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
33148        });
33149        let path = "/worker/activity-tasks/recover-activity/complete";
33150        let error = |body: Value| Error::Http {
33151            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33152            body: body.to_string(),
33153        };
33154        assert_eq!(
33155            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
33156            Some(Duration::from_secs(1))
33157        );
33158
33159        for (field, invalid) in [
33160            ("operation", json!("poll_activity_task")),
33161            ("outcome", json!("rejected")),
33162            ("worker_id", json!("another-worker")),
33163            ("task_queue", json!("recover-queue")),
33164            ("retryable", json!(false)),
33165            ("retry_after_seconds", json!(0)),
33166            ("task_id", json!("another-task")),
33167            ("lease_owner", json!("another-worker")),
33168            ("activity_attempt_id", json!("another-attempt")),
33169        ] {
33170            let mut invalid_response = response.clone();
33171            invalid_response[field] = invalid;
33172            assert_eq!(
33173                worker_fenced_completion_retry_after(
33174                    &error(invalid_response),
33175                    path,
33176                    Some(&request)
33177                ),
33178                None,
33179                "must not retry mismatched {field}"
33180            );
33181        }
33182        assert_eq!(
33183            worker_fenced_completion_retry_after(&error(response), path, None),
33184            None
33185        );
33186    }
33187
33188    #[tokio::test]
33189    async fn shutdown_interrupts_fenced_completion_backend_wait() {
33190        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33191            request_override: Some(activity_completion_remains_unavailable),
33192            ..MockWorkerBehavior::default()
33193        });
33194        let client = Client::builder(server.base_url())
33195            .timeout(Duration::from_secs(2))
33196            .build()
33197            .expect("client");
33198        let stop = Arc::new(AtomicBool::new(false));
33199        let worker = Worker::new(client, "recover-queue")
33200            .worker_id("recover-worker")
33201            .with_storage_admission(Arc::clone(&stop));
33202        let completion = tokio::spawn(async move {
33203            worker
33204                .client
33205                .complete_activity_task(
33206                    "recover-activity",
33207                    "recover-attempt",
33208                    "recover-worker",
33209                    json!("done"),
33210                    DEFAULT_CODEC,
33211                )
33212                .await
33213        });
33214        let path = "/api/worker/activity-tasks/recover-activity/complete";
33215        tokio::time::timeout(Duration::from_secs(2), async {
33216            while server.request_count(path) == 0 {
33217                tokio::time::sleep(Duration::from_millis(10)).await;
33218            }
33219        })
33220        .await
33221        .expect("first completion request");
33222        stop.store(true, Ordering::SeqCst);
33223        let error = tokio::time::timeout(Duration::from_secs(1), completion)
33224            .await
33225            .expect("shutdown must interrupt retry wait")
33226            .expect("completion task")
33227            .expect_err("backend is still unavailable");
33228        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
33229        assert_eq!(server.request_count(path), 1);
33230    }
33231}