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;
21mod worker_session;
22mod workflow_hydration;
23
24pub use activity_error::ActivityError;
25pub use cancellation_context::{
26    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
27};
28pub use cancellation_scope::CancellationScopeOpenReceipt;
29#[doc(hidden)]
30pub use cancellation_scope_history::{
31    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
32};
33#[doc(hidden)]
34pub use cancellation_scope_replay::CancellationScopeRequested;
35
36pub use cooperative_cancellation::{
37    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
38    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
39    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
40    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
41};
42
43use std::{
44    any::{type_name, Any, TypeId},
45    collections::{BTreeMap, BTreeSet, HashMap},
46    future::Future,
47    io::{self, Read},
48    pin::Pin,
49    sync::{
50        atomic::{AtomicBool, Ordering},
51        Arc, Mutex, OnceLock,
52    },
53    task::{Context as TaskContext, Poll},
54    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
55};
56
57use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
58use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
59use chrono::DateTime;
60use futures_util::{
61    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
62};
63pub use local_activity::LocalActivityOptions;
64use serde::{
65    de::DeserializeOwned,
66    ser::{SerializeMap, SerializeSeq},
67    Deserialize, Deserializer, Serialize, Serializer,
68};
69pub use serde_json::{json, Value};
70use sha2::{Digest, Sha256};
71pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
72use thiserror::Error;
73pub use uuid::Uuid;
74pub use worker_session::{WorkerSession, WorkerSessionOptions};
75
76pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
77pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
78
79/// Select the worker request protocol without enabling optional capabilities.
80#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum WorkerProtocolVersion {
83    /// Compatibility with Servers that implement only worker protocol 1.19.
84    V119,
85    /// The default worker protocol.
86    #[default]
87    V120,
88}
89
90impl WorkerProtocolVersion {
91    fn as_str(self) -> &'static str {
92        match self {
93            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
94            Self::V120 => WORKER_PROTOCOL_VERSION,
95        }
96    }
97}
98const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
99/// First additive worker protocol that defines portable worker-affinity features.
100pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
101pub const CONTROL_PLANE_VERSION: &str = "2";
102pub const DEFAULT_CODEC: &str = "avro";
103pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
104/// Worker-registration capability for authored condition-wait occurrence identity.
105pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
106    "condition_wait_occurrence_identity";
107/// Worker-registration capability for portable memo upserts.
108pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
109/// Worker-registration capability for server-routed read-only queries.
110pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
111/// Worker-registration capability for canonical typed search attributes.
112pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
113/// Worker-registration capability for synchronous workflow updates.
114pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
115/// Worker-registration capability for durable named input streams.
116pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
117/// Worker-registration capability for persisted first-completion selection.
118pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
119pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
120pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
121pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
122pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
123pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
124/// First additive worker protocol that defines query-task transport.
125pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
126/// First additive worker protocol that defines typed search-attribute upserts.
127pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
128/// First additive worker protocol that defines portable memo upserts.
129pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
130/// First additive worker protocol that preserves declared search-attribute types.
131pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
132/// First additive worker protocol that defines external durable condition waits.
133pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
134/// First additive worker protocol that preserves authored condition-wait occurrences.
135pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
136/// First additive worker protocol that defines durable selection groups.
137pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
138
139pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
140    let Some((major, minor)) = version.split_once('.') else {
141        return false;
142    };
143    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
144}
145
146fn validate_user_signal_name(signal_name: &str) -> Result<()> {
147    if signal_name == MESSAGE_STREAM_SIGNAL {
148        return Err(Error::Codec(format!(
149            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
150        )));
151    }
152    Ok(())
153}
154
155const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
156const MAX_REQUEST_ID_CHARACTERS: usize = 255;
157
158/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
159fn validate_request_id(request_id: &str) -> Result<()> {
160    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
161        return Err(Error::Codec(format!(
162            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
163        )));
164    }
165    Ok(())
166}
167
168fn generated_request_id(command: &str) -> String {
169    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
170}
171
172/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
173fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
174    if receipt.is_null() {
175        return json!({ "request_id": request_id });
176    }
177    if let Some(receipt) = receipt.as_object_mut() {
178        receipt
179            .entry("request_id")
180            .or_insert_with(|| Value::String(request_id.to_string()));
181    }
182    receipt
183}
184
185const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
186const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
187    "Workflow task waiting for scheduled history.";
188const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
189const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
190const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
191const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
192const MAX_MEMO_ENTRIES: usize = 100;
193const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
194const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
195
196const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
197    "lease_expired",
198    "query_task_not_found",
199    "query_task_not_leased",
200    "query_task_timed_out",
201    "query_deadline_unavailable",
202    "lease_owner_mismatch",
203    "query_task_attempt_mismatch",
204];
205
206/// Manifest for the default service-worker profile.
207///
208/// Inline local execution is enabled separately by [`Worker::local_activities`].
209/// Local execution, sessions and caching require explicit Worker configuration.
210pub fn portable_worker_affinity_capability_manifest() -> Value {
211    json!({
212        "local_activities": {
213            "supported": false,
214            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
215            "reason": "rust_worker_does_not_execute_record_local_activity",
216        },
217        "worker_sessions": {
218            "supported": false,
219            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
220            "reason": "rust_worker_has_no_typed_session_lifecycle",
221        },
222        "sticky_execution": {
223            "supported": false,
224            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
225            "reason": "rust_worker_uses_complete_durable_history_replay",
226        },
227    })
228}
229
230/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
231pub const AVRO_VALUE_SCHEMA_JSON: &str =
232    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
233pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
234pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
235const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
236
237static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
238static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
239    OnceLock::new();
240
241#[derive(Clone, Copy)]
242enum RequestProtocol {
243    ControlPlane,
244    DefaultWorker,
245    Worker(&'static str),
246}
247
248pub type Result<T> = std::result::Result<T, Error>;
249
250pub use nexus::{
251    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
252    NexusServiceOptions, NexusWaitFor,
253};
254
255#[derive(Debug, Error)]
256#[non_exhaustive]
257pub enum Error {
258    #[error("transport error: {0}")]
259    Transport(#[from] reqwest::Error),
260    #[error(
261        "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"
262    )]
263    InvalidBaseUrl,
264    #[error("json error: {0}")]
265    Json(#[from] serde_json::Error),
266    #[error("http {status}: {body}")]
267    Http {
268        status: reqwest::StatusCode,
269        body: String,
270    },
271    #[error("codec error: {0}")]
272    Codec(String),
273    #[error(transparent)]
274    QueryFailed(QueryFailure),
275    #[error(transparent)]
276    Protocol(ProtocolFailure),
277    #[error(transparent)]
278    NonDeterministicReplay(ReplayFailure),
279    #[error(transparent)]
280    ChildWorkflowFailed(ChildWorkflowFailure),
281    #[error(transparent)]
282    ActivityFailed(ActivityFailure),
283    #[error(transparent)]
284    ActivityError(#[from] ActivityError),
285    #[error(transparent)]
286    NexusOperationFailed(Box<NexusOperationFailure>),
287    #[error(transparent)]
288    ParallelFailed(ParallelFailure),
289    #[error(transparent)]
290    SagaCompensationFailed(SagaCompensationFailure),
291    #[error(transparent)]
292    InvalidParallelGroup(ParallelGroupError),
293    #[error(transparent)]
294    DurableOperationCancelled(DurableOperationCancelled),
295    #[error(transparent)]
296    WorkflowCancellationRequested(WorkflowCancellationRequested),
297    #[error(transparent)]
298    CooperativeCancellationRequested(CooperativeCancellationRequested),
299    #[error(transparent)]
300    CancellationScopeRequested(CancellationScopeRequested),
301    #[error(transparent)]
302    WorkflowCommandRejected(WorkflowCommandRejection),
303    #[error(transparent)]
304    WorkflowFailed(WorkflowTerminalOutcome),
305    #[error(transparent)]
306    WorkflowCancelled(WorkflowTerminalOutcome),
307    #[error(transparent)]
308    WorkflowTerminated(WorkflowTerminalOutcome),
309    #[error(transparent)]
310    WorkflowTimedOut(WorkflowTerminalOutcome),
311    #[error(transparent)]
312    ActivityTaskRejected(ActivityTaskRejection),
313    #[error("activity lease renewal unavailable: {0}")]
314    ActivityLeaseRenewalUnavailable(String),
315    #[error("workflow handler {0:?} is not registered")]
316    WorkflowNotRegistered(String),
317    #[error("activity handler {0:?} is not registered")]
318    ActivityNotRegistered(String),
319    #[error(
320        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
321    )]
322    HandlerType {
323        handler_kind: HandlerKind,
324        handler_name: String,
325        value_kind: HandlerValueKind,
326        rust_type: &'static str,
327        message: String,
328    },
329    #[error("workflow future yielded without emitting a durable command")]
330    WorkflowYieldedWithoutCommand,
331    #[error(
332        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
333    )]
334    MissingWorkflowCommandIdentity,
335    #[error("workflow state lock is poisoned")]
336    WorkflowStatePoisoned,
337    #[error("timer duration is too large for the worker protocol")]
338    TimerDurationOverflow,
339    #[error(transparent)]
340    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
341    #[error(transparent)]
342    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
343    #[error("operation timed out")]
344    Timeout,
345    #[error(
346        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
347    )]
348    MissingRoleCredentials {
349        role: &'static str,
350        opposite_role: &'static str,
351    },
352    #[error("worker loop error: {0}")]
353    WorkerLoop(String),
354    #[error(
355        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
356    )]
357    UnsupportedUpdateValidators { workflow_type: String },
358    #[error("{primary}; worker deregistration also failed: {deregistration}")]
359    WorkerShutdown {
360        primary: Box<Error>,
361        deregistration: Box<Error>,
362    },
363    #[error("invalid child workflow options: {0}")]
364    InvalidChildWorkflowOptions(String),
365    #[error("invalid workflow memo update: {0}")]
366    InvalidMemoUpdate(String),
367    #[error(
368        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
369    )]
370    WorkflowMemoUpdatesUnavailable,
371    #[error("cooperative cancellation is unavailable: {0}")]
372    CooperativeCancellationUnavailable(String),
373    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
374    CancellationScopeExecutionUnavailable,
375    #[error("invalid cooperative cancellation: {0}")]
376    InvalidCooperativeCancellation(String),
377    #[error("activity execution no longer owns its claim: {0}")]
378    ActivityExecutionAbandoned(String),
379    #[error(transparent)]
380    InvalidActivityOptions(ActivityOptionsError),
381    #[error(transparent)]
382    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
383    #[doc(hidden)]
384    #[error("workflow requested continue as new")]
385    ContinueAsNew(ContinueAsNewRequest),
386}
387
388impl Error {
389    /// The caller command key echoed by the Server in a refusal body.
390    ///
391    /// Signals and updates send their key as the `request_id` body field, and a
392    /// Server refusal such as `request_id_conflict` echoes it. Transport failures
393    /// and refusals without an echoed key return `None`: keep the key you passed
394    /// to a `*_with_request_id` method, or obtained from
395    /// [`Client::generate_signal_request_id`] or
396    /// [`Client::generate_update_request_id`], to retry the same logical command
397    /// after an uncertain outcome.
398    pub fn request_id(&self) -> Option<String> {
399        self.refusal_body()?
400            .get("request_id")
401            .and_then(Value::as_str)
402            .filter(|request_id| !request_id.is_empty())
403            .map(str::to_string)
404    }
405
406    /// Whether the Server refused a signal or update because its caller command
407    /// key is retained for a command with a different intent
408    /// (HTTP 409, `reason: "request_id_conflict"`).
409    pub fn is_request_id_conflict(&self) -> bool {
410        self.request_id_conflict().is_some()
411    }
412
413    /// The retained-command details of a `request_id_conflict` refusal.
414    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
415        let status = match self {
416            Self::Http { status, .. } => status.as_u16(),
417            Self::WorkflowCommandRejected(rejection) => rejection.status,
418            _ => return None,
419        };
420        request_id_conflict(status, self.refusal_body()?)
421    }
422
423    fn refusal_body(&self) -> Option<Value> {
424        match self {
425            Self::Http { body, .. } => serde_json::from_str(body).ok(),
426            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
427            _ => None,
428        }
429    }
430}
431
432/// A refused signal or update whose caller command key is already retained for
433/// a command with a different intent.
434///
435/// Nothing was admitted or recorded, and the key stays bound to the retained
436/// command. Send a new key for a different command, or repeat the retained
437/// command's exact intent to receive its receipt. `conflict` lists the
438/// mismatched intent parts among `name`, `arguments` and `target`.
439#[derive(Clone, Debug, PartialEq)]
440#[non_exhaustive]
441pub struct RequestIdConflict {
442    pub status: u16,
443    pub request_id: String,
444    pub message: String,
445    pub retained_command_id: Option<String>,
446    pub retained_command_type: Option<String>,
447    pub retained_outcome: Option<String>,
448    pub conflict: Vec<String>,
449    pub body: Value,
450}
451
452fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
453    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
454        return None;
455    }
456    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
457    Some(RequestIdConflict {
458        status,
459        request_id: string("request_id").unwrap_or_default(),
460        message: string("message")
461            .or_else(|| string("error"))
462            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
463        retained_command_id: string("retained_command_id"),
464        retained_command_type: string("retained_command_type"),
465        retained_outcome: string("retained_outcome"),
466        conflict: body
467            .get("conflict")
468            .and_then(Value::as_array)
469            .map(|parts| {
470                parts
471                    .iter()
472                    .filter_map(Value::as_str)
473                    .map(str::to_string)
474                    .collect()
475            })
476            .unwrap_or_default(),
477        body,
478    })
479}
480
481/// Handler namespaces checked independently within a Worker.
482#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
483pub enum RegistrationKind {
484    Workflow,
485    Activity,
486    Query,
487    Update,
488}
489
490impl std::fmt::Display for RegistrationKind {
491    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
492        formatter.write_str(match self {
493            Self::Workflow => "workflow",
494            Self::Activity => "activity",
495            Self::Query => "query",
496            Self::Update => "update",
497        })
498    }
499}
500
501/// The authoring adapter and source location of a handler registration.
502#[derive(Clone, Debug, PartialEq, Eq)]
503pub struct HandlerRegistration {
504    pub method: &'static str,
505    pub handler_type: &'static str,
506    pub file: &'static str,
507    pub line: u32,
508    pub column: u32,
509}
510
511impl std::fmt::Display for HandlerRegistration {
512    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513        write!(
514            formatter,
515            "{} at {}:{}:{} ({})",
516            self.method, self.file, self.line, self.column, self.handler_type
517        )
518    }
519}
520
521/// Ambiguous local configuration, rejected before contacting Server.
522#[derive(Clone, Debug, Error, PartialEq, Eq)]
523#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
524pub struct DuplicateRegistrationError {
525    pub handler_kind: RegistrationKind,
526    pub handler_name: String,
527    /// Query/update registrations are scoped to their owning workflow type.
528    pub workflow_type: Option<String>,
529    pub first_definition: HandlerRegistration,
530    pub second_definition: HandlerRegistration,
531}
532
533impl From<DuplicateRegistrationError> for Error {
534    fn from(error: DuplicateRegistrationError) -> Self {
535        Self::WorkerLoop(error.to_string())
536    }
537}
538
539/// Validation failure for a durable condition-wait definition.
540#[derive(Clone, Debug, Error, PartialEq, Eq)]
541pub enum ConditionWaitOptionsError {
542    #[error("condition_key must be non-empty")]
543    EmptyKey,
544    #[error("condition_definition_fingerprint must be non-empty")]
545    EmptyPredicateIdentity,
546    #[error("condition timeout is too large for the worker protocol")]
547    TimeoutOverflow,
548}
549
550/// Stable identity and optional durable timeout for a condition wait.
551///
552/// `predicate_identity` is recorded as the worker protocol's
553/// `condition_definition_fingerprint` and must change whenever predicate
554/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
555/// is written inline; it derives this identity from the predicate tokens.
556#[derive(Clone, Debug, PartialEq, Eq)]
557pub struct ConditionWaitOptions {
558    condition_key: String,
559    predicate_identity: String,
560    timeout: Option<Duration>,
561}
562
563impl ConditionWaitOptions {
564    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
565        Self {
566            condition_key: condition_key.into(),
567            predicate_identity: predicate_identity.into(),
568            timeout: None,
569        }
570    }
571
572    pub fn timeout(mut self, timeout: Duration) -> Self {
573        self.timeout = Some(timeout);
574        self
575    }
576
577    fn validate(
578        &self,
579    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
580        let condition_key = self.condition_key.trim();
581        if condition_key.is_empty() {
582            return Err(ConditionWaitOptionsError::EmptyKey);
583        }
584        let predicate_identity = self.predicate_identity.trim();
585        if predicate_identity.is_empty() {
586            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
587        }
588        let timeout_seconds = self
589            .timeout
590            .map(|timeout| {
591                timeout
592                    .as_secs()
593                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
594                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
595            })
596            .transpose()?;
597
598        Ok(ValidatedConditionWaitOptions {
599            condition_key: condition_key.to_string(),
600            predicate_identity: predicate_identity.to_string(),
601            timeout_seconds,
602        })
603    }
604}
605
606#[derive(Clone, Debug, PartialEq, Eq)]
607struct ValidatedConditionWaitOptions {
608    condition_key: String,
609    predicate_identity: String,
610    timeout_seconds: Option<u64>,
611}
612
613const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
614
615/// Unambiguous terminal result of a durable condition wait.
616#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
617#[serde(rename_all = "snake_case")]
618pub enum ConditionWaitResult {
619    Satisfied,
620    TimedOut,
621}
622
623impl ConditionWaitResult {
624    pub fn is_satisfied(self) -> bool {
625        self == Self::Satisfied
626    }
627
628    pub fn is_timed_out(self) -> bool {
629        self == Self::TimedOut
630    }
631}
632
633/// Build the stable condition definition identity used by [`wait_condition!`].
634#[doc(hidden)]
635pub fn __condition_definition_fingerprint(source: &str) -> String {
636    let mut digest = Sha256::new();
637    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
638    digest.update(source.as_bytes());
639    format!("sha256:{:x}", digest.finalize())
640}
641
642/// Create a durable condition wait whose predicate definition is fingerprinted
643/// from its inline Rust tokens.
644///
645/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
646/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
647#[macro_export]
648macro_rules! wait_condition {
649    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
650        $ctx.wait_condition(
651            $crate::ConditionWaitOptions::new(
652                $key,
653                $crate::__condition_definition_fingerprint(concat!(
654                    module_path!(),
655                    "\0",
656                    stringify!($predicate)
657                )),
658            )
659            .timeout($timeout),
660            $predicate,
661        )
662    }};
663    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
664        $ctx.wait_condition(
665            $crate::ConditionWaitOptions::new(
666                $key,
667                $crate::__condition_definition_fingerprint(concat!(
668                    module_path!(),
669                    "\0",
670                    stringify!($predicate)
671                )),
672            ),
673            $predicate,
674        )
675    }};
676}
677
678const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
679const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
680const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
681const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
682const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
683
684/// Validation failure for a typed workflow search-attribute update.
685#[derive(Clone, Debug, Error, PartialEq, Eq)]
686pub enum SearchAttributeUpdateError {
687    #[error("search-attribute update requires at least one attribute")]
688    Empty,
689    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
690    InvalidKey(String),
691    #[error("search-attribute update exceeds the limit of 100 attributes")]
692    TooManyAttributes,
693    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
694    ValueTooLong {
695        key: String,
696        kind: &'static str,
697        limit: usize,
698    },
699    #[error(
700        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
701    )]
702    EmptyString(String),
703    #[error("search attribute {0:?} has a non-finite float value")]
704    NonFiniteFloat(String),
705    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
706    InvalidDateTime(String),
707    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
708    PayloadTooLarge,
709}
710
711/// One public typed search-attribute value.
712#[derive(Clone, Debug, PartialEq)]
713pub enum SearchAttributeValue {
714    String(String),
715    Keyword(String),
716    KeywordList(Vec<String>),
717    Int(i64),
718    Float(f64),
719    Bool(bool),
720    DateTime(String),
721    Delete,
722}
723
724impl SearchAttributeValue {
725    fn type_name(&self) -> Option<&'static str> {
726        match self {
727            Self::String(_) => Some("string"),
728            Self::Keyword(_) => Some("keyword"),
729            Self::KeywordList(_) => Some("keyword_list"),
730            Self::Int(_) => Some("int"),
731            Self::Float(_) => Some("float"),
732            Self::Bool(_) => Some("bool"),
733            Self::DateTime(_) => Some("datetime"),
734            Self::Delete => None,
735        }
736    }
737
738    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
739        let normalize_string = |value: String, kind: &'static str, limit: usize| {
740            let value = value.trim().to_string();
741            if value.is_empty() {
742                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
743            }
744            if value.len() > limit {
745                return Err(SearchAttributeUpdateError::ValueTooLong {
746                    key: key.to_string(),
747                    kind,
748                    limit,
749                });
750            }
751            Ok(value)
752        };
753
754        match self {
755            Self::String(value) => Ok(Self::String(normalize_string(
756                value,
757                "string",
758                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
759            )?)),
760            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
761                value,
762                "keyword",
763                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
764            )?)),
765            Self::KeywordList(values) => {
766                let values = values
767                    .into_iter()
768                    .map(|value| {
769                        let value = value.trim().to_string();
770                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
771                            return Err(SearchAttributeUpdateError::ValueTooLong {
772                                key: key.to_string(),
773                                kind: "keyword-list entry",
774                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
775                            });
776                        }
777                        Ok(value)
778                    })
779                    .collect::<std::result::Result<Vec<_>, _>>()?;
780                Ok(Self::KeywordList(values))
781            }
782            Self::Float(value) if !value.is_finite() => {
783                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
784            }
785            Self::DateTime(value) => {
786                let value =
787                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
788                if DateTime::parse_from_rfc3339(&value).is_err() {
789                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
790                }
791                Ok(Self::DateTime(value))
792            }
793            value => Ok(value),
794        }
795    }
796
797    fn into_json(self) -> Value {
798        match self {
799            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
800                Value::String(value)
801            }
802            Self::KeywordList(values) => {
803                Value::Array(values.into_iter().map(Value::String).collect())
804            }
805            Self::Int(value) => json!(value),
806            Self::Float(value) => json!(value),
807            Self::Bool(value) => json!(value),
808            Self::Delete => Value::Null,
809        }
810    }
811}
812
813/// Validated typed workflow-side search-attribute mutation.
814#[derive(Clone, Debug, Default, PartialEq)]
815pub struct SearchAttributeUpdate {
816    attributes: BTreeMap<String, SearchAttributeValue>,
817}
818
819impl SearchAttributeUpdate {
820    pub fn new() -> Self {
821        Self::default()
822    }
823
824    pub fn set(
825        mut self,
826        key: impl Into<String>,
827        value: SearchAttributeValue,
828    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
829        let key = key.into();
830        validate_search_attribute_key(&key)?;
831        if !self.attributes.contains_key(&key)
832            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
833        {
834            return Err(SearchAttributeUpdateError::TooManyAttributes);
835        }
836        self.attributes.insert(key.clone(), value.normalized(&key)?);
837        self.validate_size()?;
838        Ok(self)
839    }
840
841    pub fn string(
842        self,
843        key: impl Into<String>,
844        value: impl Into<String>,
845    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
846        self.set(key, SearchAttributeValue::String(value.into()))
847    }
848
849    pub fn keyword(
850        self,
851        key: impl Into<String>,
852        value: impl Into<String>,
853    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
854        self.set(key, SearchAttributeValue::Keyword(value.into()))
855    }
856
857    pub fn keyword_list<I, V>(
858        self,
859        key: impl Into<String>,
860        values: I,
861    ) -> std::result::Result<Self, SearchAttributeUpdateError>
862    where
863        I: IntoIterator<Item = V>,
864        V: Into<String>,
865    {
866        self.set(
867            key,
868            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
869        )
870    }
871
872    pub fn int(
873        self,
874        key: impl Into<String>,
875        value: i64,
876    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
877        self.set(key, SearchAttributeValue::Int(value))
878    }
879
880    pub fn float(
881        self,
882        key: impl Into<String>,
883        value: f64,
884    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
885        self.set(key, SearchAttributeValue::Float(value))
886    }
887
888    pub fn bool(
889        self,
890        key: impl Into<String>,
891        value: bool,
892    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
893        self.set(key, SearchAttributeValue::Bool(value))
894    }
895
896    pub fn datetime(
897        self,
898        key: impl Into<String>,
899        value: impl Into<String>,
900    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
901        self.set(key, SearchAttributeValue::DateTime(value.into()))
902    }
903
904    pub fn delete(
905        self,
906        key: impl Into<String>,
907    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
908        self.set(key, SearchAttributeValue::Delete)
909    }
910
911    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
912        let (attributes, _) = self.clone().into_wire_parts();
913        if serde_json::to_vec(&attributes)
914            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
915            .unwrap_or(true)
916        {
917            return Err(SearchAttributeUpdateError::PayloadTooLarge);
918        }
919        Ok(())
920    }
921
922    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
923        let mut attributes = serde_json::Map::new();
924        let mut attribute_types = BTreeMap::new();
925        for (key, value) in self.attributes {
926            if let Some(type_name) = value.type_name() {
927                attribute_types.insert(key.clone(), type_name.to_string());
928            }
929            attributes.insert(key, value.into_json());
930        }
931        (Value::Object(attributes), attribute_types)
932    }
933
934    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
935        if self.attributes.is_empty() {
936            return Err(SearchAttributeUpdateError::Empty);
937        }
938        self.validate_size()
939    }
940}
941
942fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
943    let valid = !key.is_empty()
944        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
945        && key
946            .bytes()
947            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
948    if valid {
949        Ok(())
950    } else {
951        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
952    }
953}
954
955/// The registered handler family reported by [`Error::HandlerType`].
956#[derive(Clone, Copy, Debug, PartialEq, Eq)]
957pub enum HandlerKind {
958    Workflow,
959    Activity,
960}
961
962impl std::fmt::Display for HandlerKind {
963    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
964        formatter.write_str(match self {
965            Self::Workflow => "workflow",
966            Self::Activity => "activity",
967        })
968    }
969}
970
971/// Whether a typed handler failed to adapt its input or result.
972#[derive(Clone, Copy, Debug, PartialEq, Eq)]
973pub enum HandlerValueKind {
974    Input,
975    Result,
976}
977
978impl std::fmt::Display for HandlerValueKind {
979    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
980        formatter.write_str(match self {
981            Self::Input => "input",
982            Self::Result => "result",
983        })
984    }
985}
986
987/// The lifecycle command sent to a workflow execution.
988#[derive(Clone, Copy, Debug, PartialEq, Eq)]
989pub enum WorkflowCommandKind {
990    Cancel,
991    Terminate,
992}
993
994impl WorkflowCommandKind {
995    fn as_str(self) -> &'static str {
996        match self {
997            Self::Cancel => "cancel",
998            Self::Terminate => "terminate",
999        }
1000    }
1001}
1002
1003/// Optional structured fields for a cancellation or termination request.
1004#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1005pub struct WorkflowCommandOptions {
1006    #[serde(skip_serializing_if = "Option::is_none")]
1007    pub reason: Option<String>,
1008    #[serde(skip_serializing_if = "Option::is_none")]
1009    pub request_id: Option<String>,
1010}
1011
1012/// Server-enforced timeout policy for a workflow start.
1013///
1014/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1015/// only bounds how long the caller waits. A server deadline produces a terminal
1016/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1017/// `run_timeout`.
1018#[derive(Clone, Debug, PartialEq, Eq)]
1019pub struct WorkflowStartOptions {
1020    pub execution_timeout_seconds: u64,
1021    pub run_timeout_seconds: u64,
1022}
1023
1024impl Default for WorkflowStartOptions {
1025    fn default() -> Self {
1026        Self {
1027            execution_timeout_seconds: 3600,
1028            run_timeout_seconds: 600,
1029        }
1030    }
1031}
1032
1033impl WorkflowStartOptions {
1034    pub fn new() -> Self {
1035        Self::default()
1036    }
1037
1038    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1039        self.execution_timeout_seconds = seconds;
1040        self
1041    }
1042
1043    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1044        self.run_timeout_seconds = seconds;
1045        self
1046    }
1047
1048    fn validate(&self) -> Result<()> {
1049        if self.execution_timeout_seconds == 0 {
1050            return Err(Error::Codec(
1051                "execution_timeout_seconds must be at least 1".to_string(),
1052            ));
1053        }
1054        if self.run_timeout_seconds == 0 {
1055            return Err(Error::Codec(
1056                "run_timeout_seconds must be at least 1".to_string(),
1057            ));
1058        }
1059        if self.run_timeout_seconds > self.execution_timeout_seconds {
1060            return Err(Error::Codec(
1061                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1062            ));
1063        }
1064
1065        Ok(())
1066    }
1067}
1068
1069/// Optional routing overrides for a continue-as-new transition.
1070///
1071/// Omitted values retain the current workflow type and task queue. Server-owned
1072/// instance metadata is not accepted here and is carried by the server.
1073#[derive(Clone, Debug, Default, PartialEq, Eq)]
1074pub struct ContinueAsNewOptions {
1075    pub workflow_type: Option<String>,
1076    pub task_queue: Option<String>,
1077}
1078
1079impl ContinueAsNewOptions {
1080    pub fn new() -> Self {
1081        Self::default()
1082    }
1083
1084    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1085        self.workflow_type = Some(workflow_type.into());
1086        self
1087    }
1088
1089    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1090        self.task_queue = Some(task_queue.into());
1091        self
1092    }
1093
1094    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1095        for (field, value) in [
1096            ("workflow_type", self.workflow_type.as_deref()),
1097            ("task_queue", self.task_queue.as_deref()),
1098        ] {
1099            if value.is_some_and(|value| value.trim().is_empty()) {
1100                return Err(ContinueAsNewOptionsError {
1101                    field,
1102                    message: format!("{field} must not be empty"),
1103                });
1104            }
1105        }
1106        Ok(())
1107    }
1108}
1109
1110/// A stable validation error raised before a continue-as-new command is emitted.
1111#[derive(Clone, Debug, Error, PartialEq, Eq)]
1112#[error("invalid continue-as-new option {field}: {message}")]
1113pub struct ContinueAsNewOptionsError {
1114    pub field: &'static str,
1115    pub message: String,
1116}
1117
1118/// Public history-budget information attached to the current workflow task.
1119#[derive(Clone, Debug, Default, PartialEq, Eq)]
1120pub struct WorkflowHistoryBudget {
1121    pub event_count: u64,
1122    pub size_bytes: Option<u64>,
1123    pub continue_as_new_recommended: bool,
1124    pub pressure: Option<String>,
1125}
1126
1127#[doc(hidden)]
1128#[derive(Clone, Debug)]
1129pub struct ContinueAsNewRequest {
1130    arguments: AvroValue,
1131    options: ContinueAsNewOptions,
1132}
1133
1134impl WorkflowCommandOptions {
1135    pub fn new() -> Self {
1136        Self::default()
1137    }
1138
1139    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1140        self.reason = Some(reason.into());
1141        self
1142    }
1143
1144    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1145        self.request_id = Some(request_id.into());
1146        self
1147    }
1148}
1149
1150/// The accepted, machine-readable result of a lifecycle command.
1151#[derive(Clone, Debug, PartialEq)]
1152pub struct WorkflowCommandResult {
1153    pub command: WorkflowCommandKind,
1154    pub workflow_id: String,
1155    pub run_id: Option<String>,
1156    pub outcome: Option<String>,
1157    pub reason: Option<String>,
1158    pub command_status: Option<String>,
1159    pub raw: Value,
1160}
1161
1162/// A new run continuing a failed run from its recorded activity boundary.
1163#[derive(Clone, Debug, PartialEq)]
1164pub struct WorkflowRedriveResult {
1165    pub workflow_id: String,
1166    pub source_run_id: String,
1167    pub run_id: String,
1168    pub resume_step_sequence: u64,
1169    pub raw: Value,
1170}
1171
1172/// A stable rejection returned by instance- or selected-run lifecycle commands.
1173#[derive(Clone, Debug, Error)]
1174#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1175pub struct WorkflowCommandRejection {
1176    pub command: WorkflowCommandKind,
1177    pub status: u16,
1178    pub reason: String,
1179    pub message: String,
1180    pub workflow_id: String,
1181    pub run_id: Option<String>,
1182    pub target_scope: Option<String>,
1183    pub body: Value,
1184}
1185
1186/// Stable terminal categories returned by [`WorkflowHandle::result`].
1187#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1188pub enum WorkflowTerminalKind {
1189    Failed,
1190    Cancelled,
1191    Terminated,
1192    TimedOut,
1193}
1194
1195/// A typed terminal workflow outcome with durable identity and failure metadata.
1196///
1197/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1198/// of parsing its display representation. Fields remain `None` when an older
1199/// server did not publish that metadata.
1200#[derive(Clone, Debug, Error)]
1201#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1202pub struct WorkflowTerminalOutcome {
1203    pub kind: WorkflowTerminalKind,
1204    pub workflow_id: String,
1205    pub run_id: Option<String>,
1206    pub reason: String,
1207    pub failure_category: Option<String>,
1208    pub failure_id: Option<String>,
1209    pub exception_type: Option<String>,
1210    pub exception_class: Option<String>,
1211    pub non_retryable: Option<bool>,
1212    pub message: Option<String>,
1213    pub exception: Option<Value>,
1214    pub raw: Value,
1215}
1216
1217/// A worker-side activity settlement or heartbeat rejected by durable state.
1218#[derive(Clone, Debug, Error)]
1219#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1220pub struct ActivityTaskRejection {
1221    pub operation: String,
1222    pub status: u16,
1223    pub reason: String,
1224    pub task_id: String,
1225    pub activity_attempt_id: String,
1226    pub cancel_requested: bool,
1227    pub can_continue: Option<bool>,
1228    pub run_closed_reason: Option<String>,
1229    pub body: Value,
1230}
1231
1232/// Stable validation categories for [`ActivityOptions`].
1233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1234pub enum ActivityOptionsErrorKind {
1235    EmptyTaskQueue,
1236    EmptyRetryPolicy,
1237    InvalidMaxAttempts,
1238    BackoffWithoutRetryBudget,
1239    TooManyBackoffIntervals,
1240    InvalidBackoffCoefficient,
1241    BackoffGenerationTooLarge,
1242    BackoffOverflow,
1243    EmptyNonRetryableErrorType,
1244    TimeoutNotPositive,
1245    MissingTotalTimeout,
1246    TimeoutOverflow,
1247    TimeoutOrder,
1248}
1249
1250/// A machine-readable activity-options validation failure.
1251#[derive(Clone, Debug, Error, PartialEq, Eq)]
1252#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1253pub struct ActivityOptionsError {
1254    pub kind: ActivityOptionsErrorKind,
1255    pub field: Option<&'static str>,
1256    pub message: String,
1257}
1258
1259impl ActivityOptionsError {
1260    fn new(
1261        kind: ActivityOptionsErrorKind,
1262        field: Option<&'static str>,
1263        message: impl Into<String>,
1264    ) -> Self {
1265        Self {
1266            kind,
1267            field,
1268            message: message.into(),
1269        }
1270    }
1271}
1272
1273/// Stable terminal categories returned when an awaited activity does not succeed.
1274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1275pub enum ActivityFailureKind {
1276    Failed,
1277    Cancelled,
1278    TimedOut,
1279}
1280
1281/// A stable, machine-readable terminal activity failure.
1282///
1283/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1284/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1285#[derive(Clone, Debug, Error, PartialEq)]
1286#[error("activity failed ({reason}): {message}")]
1287pub struct ActivityFailure {
1288    pub kind: ActivityFailureKind,
1289    pub reason: String,
1290    pub message: String,
1291    pub activity_execution_id: Option<String>,
1292    pub activity_attempt_id: Option<String>,
1293    pub activity_type: Option<String>,
1294    pub activity_class: Option<String>,
1295    pub attempt_number: Option<u64>,
1296    pub failure_id: Option<String>,
1297    pub failure_category: Option<String>,
1298    pub timeout_kind: Option<String>,
1299    pub non_retryable: bool,
1300    pub exception_type: Option<String>,
1301    pub exception_class: Option<String>,
1302    pub code: Option<Value>,
1303    pub exception: Option<Value>,
1304}
1305
1306/// Stable terminal categories returned when an awaited child does not succeed.
1307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1308pub enum ChildWorkflowFailureKind {
1309    Failed,
1310    Cancelled,
1311    Terminated,
1312}
1313
1314/// A stable, machine-readable child workflow failure delivered to its parent.
1315///
1316/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1317/// of parsing the display message. Child and parent identifiers retain the
1318/// relationship recorded in durable history across worker restarts.
1319#[derive(Clone, Debug, Error)]
1320#[error("child workflow failed ({reason}): {message}")]
1321pub struct ChildWorkflowFailure {
1322    pub kind: ChildWorkflowFailureKind,
1323    pub reason: String,
1324    pub message: String,
1325    pub parent_workflow_id: Option<String>,
1326    pub parent_workflow_run_id: Option<String>,
1327    pub child_workflow_id: Option<String>,
1328    pub child_workflow_run_id: Option<String>,
1329    pub child_workflow_type: Option<String>,
1330    pub failure_id: Option<String>,
1331    pub failure_category: Option<String>,
1332    pub exception_type: Option<String>,
1333    pub exception_class: Option<String>,
1334    pub non_retryable: bool,
1335    pub code: Option<Value>,
1336    pub exception: Option<Value>,
1337}
1338
1339/// The identity of one durable workflow execution.
1340#[derive(Clone, Debug, PartialEq, Eq)]
1341pub struct WorkflowIdentity {
1342    pub workflow_id: Option<String>,
1343    pub run_id: Option<String>,
1344}
1345
1346/// A successful child result together with its durable parent-child identity.
1347#[derive(Clone, Debug, PartialEq)]
1348pub struct ChildWorkflowResult {
1349    pub parent: WorkflowIdentity,
1350    pub child: WorkflowIdentity,
1351    pub child_workflow_type: Option<String>,
1352    pub result: Value,
1353}
1354
1355/// Lossless successful child result for fixed Avro Value workflows.
1356#[derive(Clone, Debug, PartialEq)]
1357pub struct ChildWorkflowAvroResult {
1358    pub parent: WorkflowIdentity,
1359    pub child: WorkflowIdentity,
1360    pub child_workflow_type: Option<String>,
1361    pub result: AvroValue,
1362}
1363
1364/// Stable user-facing identity for one member of a durable selection group.
1365#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1366#[serde(untagged)]
1367pub enum SelectionKey {
1368    Index(usize),
1369    Name(String),
1370}
1371
1372impl From<usize> for SelectionKey {
1373    fn from(value: usize) -> Self {
1374        Self::Index(value)
1375    }
1376}
1377
1378impl From<String> for SelectionKey {
1379    fn from(value: String) -> Self {
1380        Self::Name(value)
1381    }
1382}
1383
1384impl From<&str> for SelectionKey {
1385    fn from(value: &str) -> Self {
1386        Self::Name(value.to_string())
1387    }
1388}
1389
1390/// Typed result of explicitly awaiting a cancelled non-winning operation.
1391#[derive(Clone, Debug, Error, PartialEq, Eq)]
1392#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1393pub struct DurableOperationCancelled {
1394    pub selection_group_id: String,
1395    pub member_key: SelectionKey,
1396    pub member_index: usize,
1397    pub operation_kind: String,
1398    pub operation_identity: String,
1399}
1400
1401/// Stable identity for one enclosing deterministic parallel group.
1402///
1403/// The same fields are attached to every ordinary activity, timer, or child
1404/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1405/// no Rust-specific wire command is introduced.
1406#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1407pub struct ParallelGroupMetadata {
1408    pub parallel_group_id: String,
1409    pub parallel_group_kind: String,
1410    pub parallel_group_base_sequence: u64,
1411    pub parallel_group_size: usize,
1412    pub parallel_group_index: usize,
1413    #[serde(default, skip_serializing_if = "Option::is_none")]
1414    pub parallel_group_mode: Option<String>,
1415    #[serde(default, skip_serializing_if = "Option::is_none")]
1416    pub selection_member_key: Option<SelectionKey>,
1417    #[serde(default, skip_serializing_if = "Option::is_none")]
1418    pub selection_member_index: Option<usize>,
1419    #[serde(default, skip_serializing_if = "Option::is_none")]
1420    pub selection_member_base_sequence: Option<u64>,
1421    #[serde(default, skip_serializing_if = "Option::is_none")]
1422    pub selection_member_size: Option<usize>,
1423    #[serde(default, skip_serializing_if = "Option::is_none")]
1424    pub selection_member_kind: Option<String>,
1425}
1426
1427/// One input-ordered result returned by [`WorkflowContext::parallel`].
1428#[derive(Clone, Debug, PartialEq)]
1429pub enum ParallelResult {
1430    Activity(Value),
1431    ChildWorkflow(ChildWorkflowResult),
1432    Timer,
1433    Signal(Vec<Value>),
1434    Condition(ConditionWaitResult),
1435    Group(Vec<ParallelResult>),
1436}
1437
1438/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1439#[derive(Clone, Debug, PartialEq)]
1440pub enum ParallelAvroResult {
1441    Activity(AvroValue),
1442    ChildWorkflow(ChildWorkflowAvroResult),
1443    Timer,
1444    Signal(Vec<AvroValue>),
1445    Condition(ConditionWaitResult),
1446    Group(Vec<ParallelAvroResult>),
1447}
1448
1449impl ParallelAvroResult {
1450    fn into_json_result(self) -> Result<ParallelResult> {
1451        match self {
1452            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1453            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1454                parent: result.parent,
1455                child: result.child,
1456                child_workflow_type: result.child_workflow_type,
1457                result: result.result.into_json()?,
1458            })),
1459            Self::Timer => Ok(ParallelResult::Timer),
1460            Self::Signal(values) => Ok(ParallelResult::Signal(
1461                values
1462                    .into_iter()
1463                    .map(AvroValue::into_json)
1464                    .collect::<Result<Vec<_>>>()?,
1465            )),
1466            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1467            Self::Group(results) => Ok(ParallelResult::Group(
1468                results
1469                    .into_iter()
1470                    .map(Self::into_json_result)
1471                    .collect::<Result<Vec<_>>>()?,
1472            )),
1473        }
1474    }
1475}
1476
1477/// One successful leaf retained when another parallel member failed.
1478#[derive(Clone, Debug, PartialEq)]
1479pub struct ParallelCompletion {
1480    pub member_path: Vec<usize>,
1481    pub result: ParallelResult,
1482}
1483
1484/// A deterministic join failed after some siblings had already completed.
1485///
1486/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1487/// error. `completed` is declaration ordered and contains only durable
1488/// successes observed in the same replay. Late sibling completions can add
1489/// entries on a later replay without changing `member_path` or the selected
1490/// positional failure.
1491#[derive(Debug, Error)]
1492#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1493pub struct ParallelFailure {
1494    pub group_id: String,
1495    pub member_path: Vec<usize>,
1496    pub group_path: Vec<ParallelGroupMetadata>,
1497    pub completed: Vec<ParallelCompletion>,
1498    #[source]
1499    pub cause: Box<Error>,
1500}
1501
1502/// Stable validation error returned before an invalid group emits commands.
1503#[derive(Clone, Debug, Error, PartialEq, Eq)]
1504#[error("invalid deterministic parallel group ({reason}): {message}")]
1505pub struct ParallelGroupError {
1506    pub reason: &'static str,
1507    pub member_path: Vec<usize>,
1508    pub message: String,
1509}
1510
1511/// Cooperative workflow cancellation observed at an author-controlled point.
1512#[derive(Clone, Debug, Error, PartialEq, Eq)]
1513#[error("workflow cancellation was requested")]
1514pub struct WorkflowCancellationRequested;
1515
1516/// A forward saga failure followed by a terminal compensation failure.
1517#[derive(Debug, Error)]
1518#[error(
1519    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1520)]
1521pub struct SagaCompensationFailure {
1522    pub initiating_failure: Box<Error>,
1523    pub compensation_failure: Box<Error>,
1524    pub compensation_activity_type: String,
1525    pub compensation_registration_order: usize,
1526}
1527
1528/// Server behavior when a parent closes while its child is still open.
1529#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1530pub enum ParentClosePolicy {
1531    #[default]
1532    Abandon,
1533    /// Legacy terminal cancellation without cooperative cleanup.
1534    RequestCancel,
1535    /// Request cooperative cleanup with the original lineage and deadline.
1536    RequestCancellation,
1537    Terminate,
1538}
1539
1540impl ParentClosePolicy {
1541    fn as_str(self) -> &'static str {
1542        match self {
1543            Self::Abandon => "abandon",
1544            Self::RequestCancel => "request_cancel",
1545            Self::RequestCancellation => "request_cancellation",
1546            Self::Terminate => "terminate",
1547        }
1548    }
1549}
1550
1551/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1552#[non_exhaustive]
1553#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1554pub enum CancellationPolicy {
1555    /// Request cancellation and continue without waiting. Historical Activity default.
1556    TryCancel,
1557    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1558    WaitCancellationCompleted,
1559    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1560    #[default]
1561    Abandon,
1562}
1563
1564impl CancellationPolicy {
1565    fn as_str(self) -> &'static str {
1566        match self {
1567            Self::TryCancel => "try_cancel",
1568            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1569            Self::Abandon => "abandon",
1570        }
1571    }
1572}
1573
1574/// Durable retry policy for one child workflow invocation.
1575#[derive(Clone, Debug, Default, PartialEq, Eq)]
1576pub struct ChildWorkflowRetryPolicy {
1577    pub max_attempts: Option<u32>,
1578    pub backoff_seconds: Vec<u64>,
1579    pub non_retryable_error_types: Vec<String>,
1580}
1581
1582/// Options recorded with a child-workflow command.
1583///
1584/// The task queue is mandatory so routing is explicit and replay-stable.
1585#[derive(Clone, Debug, PartialEq, Eq)]
1586pub struct ChildWorkflowOptions {
1587    pub task_queue: String,
1588    pub parent_close_policy: ParentClosePolicy,
1589    pub cancellation_policy: CancellationPolicy,
1590    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1591    pub execution_timeout_seconds: Option<u64>,
1592    pub run_timeout_seconds: Option<u64>,
1593}
1594
1595impl ChildWorkflowOptions {
1596    pub fn new(task_queue: impl Into<String>) -> Self {
1597        Self {
1598            task_queue: task_queue.into(),
1599            parent_close_policy: ParentClosePolicy::Abandon,
1600            cancellation_policy: CancellationPolicy::Abandon,
1601            retry_policy: None,
1602            execution_timeout_seconds: None,
1603            run_timeout_seconds: None,
1604        }
1605    }
1606
1607    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1608        self.parent_close_policy = policy;
1609        self
1610    }
1611
1612    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1613        self.cancellation_policy = policy;
1614        self
1615    }
1616
1617    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1618        self.retry_policy = Some(policy);
1619        self
1620    }
1621
1622    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1623        self.execution_timeout_seconds = Some(seconds);
1624        self
1625    }
1626
1627    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1628        self.run_timeout_seconds = Some(seconds);
1629        self
1630    }
1631}
1632
1633/// Backoff intervals for one durable activity retry policy.
1634#[derive(Clone, Debug, PartialEq, Eq)]
1635pub enum ActivityBackoff {
1636    /// Use these intervals between attempts. The server repeats the final
1637    /// interval if the retry budget contains more attempts than entries.
1638    /// All entries are retained, including those beyond the retry budget.
1639    Explicit(Vec<Duration>),
1640    /// Generate one interval for every retry using integer exponential growth.
1641    Exponential {
1642        initial_interval: Duration,
1643        coefficient: u32,
1644        maximum_interval: Option<Duration>,
1645    },
1646}
1647
1648/// Durable server-side retry policy for one activity execution.
1649#[derive(Clone, Debug, Default, PartialEq, Eq)]
1650pub struct ActivityRetryPolicy {
1651    pub max_attempts: Option<u32>,
1652    pub backoff: Option<ActivityBackoff>,
1653    pub non_retryable_error_types: Vec<String>,
1654}
1655
1656impl ActivityRetryPolicy {
1657    /// Start a policy with a finite attempt budget, including the first attempt.
1658    pub fn new(max_attempts: u32) -> Self {
1659        Self {
1660            max_attempts: Some(max_attempts),
1661            ..Self::default()
1662        }
1663    }
1664
1665    /// Preserve the complete explicit list independently of the attempt budget.
1666    /// Unused entries remain part of the policy compared during replay.
1667    /// Set explicit durable retry intervals. Each positive fractional second
1668    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
1669    /// second. Zero stays zero. Queue latency can delay the next attempt further.
1670    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1671        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1672        self
1673    }
1674
1675    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
1676    /// Each interval is capped by `maximum_interval`, when present, then rounded
1677    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
1678    /// Zero stays zero. This policy is separate from HTTP transport retries.
1679    pub fn exponential_backoff(
1680        mut self,
1681        initial_interval: Duration,
1682        coefficient: u32,
1683        maximum_interval: Option<Duration>,
1684    ) -> Self {
1685        self.backoff = Some(ActivityBackoff::Exponential {
1686            initial_interval,
1687            coefficient,
1688            maximum_interval,
1689        });
1690        self
1691    }
1692
1693    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1694        self.non_retryable_error_types.push(error_type.into());
1695        self
1696    }
1697
1698    pub fn non_retryable_error_types(
1699        mut self,
1700        error_types: impl IntoIterator<Item = impl Into<String>>,
1701    ) -> Self {
1702        self.non_retryable_error_types
1703            .extend(error_types.into_iter().map(Into::into));
1704        self
1705    }
1706}
1707
1708/// Options recorded atomically on one deterministic `schedule_activity` command.
1709///
1710/// Durations are rounded up to whole seconds when encoded, so the server never
1711/// receives a shorter timeout or backoff than the caller requested.
1712#[derive(Clone, Debug, Default, PartialEq, Eq)]
1713pub struct ActivityOptions {
1714    pub task_queue: Option<String>,
1715    pub retry_policy: Option<ActivityRetryPolicy>,
1716    pub start_to_close_timeout: Option<Duration>,
1717    pub schedule_to_start_timeout: Option<Duration>,
1718    pub schedule_to_close_timeout: Option<Duration>,
1719    pub heartbeat_timeout: Option<Duration>,
1720    pub cancellation_policy: Option<CancellationPolicy>,
1721}
1722
1723impl ActivityOptions {
1724    pub fn new() -> Self {
1725        Self::default()
1726    }
1727
1728    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1729        self.task_queue = Some(task_queue.into());
1730        self
1731    }
1732
1733    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1734        self.retry_policy = Some(policy);
1735        self
1736    }
1737
1738    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1739        self.start_to_close_timeout = Some(timeout);
1740        self
1741    }
1742
1743    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1744        self.schedule_to_start_timeout = Some(timeout);
1745        self
1746    }
1747
1748    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1749        self.schedule_to_close_timeout = Some(timeout);
1750        self
1751    }
1752
1753    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1754        self.heartbeat_timeout = Some(timeout);
1755        self
1756    }
1757
1758    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1759        self.cancellation_policy = Some(policy);
1760        self
1761    }
1762
1763    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1764        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1765            && self.schedule_to_close_timeout.is_none()
1766        {
1767            return Err(ActivityOptionsError::new(
1768                ActivityOptionsErrorKind::MissingTotalTimeout,
1769                Some("schedule_to_close_timeout"),
1770                "remote Activity Abandon requires a finite positive total timeout",
1771            ));
1772        }
1773        if self
1774            .task_queue
1775            .as_deref()
1776            .is_some_and(|queue| queue.trim().is_empty())
1777        {
1778            return Err(ActivityOptionsError::new(
1779                ActivityOptionsErrorKind::EmptyTaskQueue,
1780                Some("task_queue"),
1781                "task_queue must not be empty",
1782            ));
1783        }
1784
1785        for (field, value) in [
1786            ("start_to_close_timeout", self.start_to_close_timeout),
1787            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1788            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1789            ("heartbeat_timeout", self.heartbeat_timeout),
1790        ] {
1791            if value.is_some_and(|value| value.is_zero()) {
1792                return Err(ActivityOptionsError::new(
1793                    ActivityOptionsErrorKind::TimeoutNotPositive,
1794                    Some(field),
1795                    format!("{field} must be positive"),
1796                ));
1797            }
1798        }
1799
1800        validate_timeout_order(
1801            "heartbeat_timeout",
1802            self.heartbeat_timeout,
1803            "start_to_close_timeout",
1804            self.start_to_close_timeout,
1805        )?;
1806        validate_timeout_order(
1807            "start_to_close_timeout",
1808            self.start_to_close_timeout,
1809            "schedule_to_close_timeout",
1810            self.schedule_to_close_timeout,
1811        )?;
1812        validate_timeout_order(
1813            "schedule_to_start_timeout",
1814            self.schedule_to_start_timeout,
1815            "schedule_to_close_timeout",
1816            self.schedule_to_close_timeout,
1817        )?;
1818
1819        Ok(ValidatedActivityOptions {
1820            task_queue: self.task_queue.clone(),
1821            retry_policy: self
1822                .retry_policy
1823                .as_ref()
1824                .map(validate_activity_retry_policy)
1825                .transpose()?,
1826            start_to_close_timeout: timeout_seconds(
1827                "start_to_close_timeout",
1828                self.start_to_close_timeout,
1829            )?,
1830            schedule_to_start_timeout: timeout_seconds(
1831                "schedule_to_start_timeout",
1832                self.schedule_to_start_timeout,
1833            )?,
1834            schedule_to_close_timeout: timeout_seconds(
1835                "schedule_to_close_timeout",
1836                self.schedule_to_close_timeout,
1837            )?,
1838            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1839            cancellation_policy: self.cancellation_policy,
1840        })
1841    }
1842}
1843
1844/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1845///
1846/// Constructors capture arguments but perform no I/O. The join validates the
1847/// complete tree, attaches the existing parallel-group metadata to every
1848/// ordinary command, schedules all leaves, and then suspends.
1849pub enum ParallelOperation {
1850    Activity {
1851        activity_type: String,
1852        options: ActivityOptions,
1853        arguments: Result<AvroValue>,
1854    },
1855    ChildWorkflow {
1856        workflow_type: String,
1857        options: ChildWorkflowOptions,
1858        arguments: Result<AvroValue>,
1859    },
1860    Timer(Duration),
1861    Signal(String),
1862    Condition {
1863        options: ConditionWaitOptions,
1864        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1865    },
1866    Group(Vec<ParallelOperation>),
1867}
1868
1869impl ParallelOperation {
1870    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1871        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1872    }
1873
1874    pub fn activity_with_options<T: Serialize>(
1875        activity_type: impl Into<String>,
1876        options: ActivityOptions,
1877        args: T,
1878    ) -> Self {
1879        Self::Activity {
1880            activity_type: activity_type.into(),
1881            options,
1882            arguments: AvroValue::from_serialize(&args),
1883        }
1884    }
1885
1886    pub fn child_workflow<T: Serialize>(
1887        workflow_type: impl Into<String>,
1888        options: ChildWorkflowOptions,
1889        args: T,
1890    ) -> Self {
1891        Self::ChildWorkflow {
1892            workflow_type: workflow_type.into(),
1893            options,
1894            arguments: AvroValue::from_serialize(&args),
1895        }
1896    }
1897
1898    pub fn timer(duration: Duration) -> Self {
1899        Self::Timer(duration)
1900    }
1901
1902    pub fn signal(signal_name: impl Into<String>) -> Self {
1903        Self::Signal(signal_name.into())
1904    }
1905
1906    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1907    where
1908        F: Fn() -> Result<bool> + Send + 'static,
1909    {
1910        Self::Condition {
1911            options,
1912            predicate: Box::new(predicate),
1913        }
1914    }
1915
1916    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1917        Self::Group(operations)
1918    }
1919}
1920
1921#[derive(Clone, Debug)]
1922struct ValidatedActivityOptions {
1923    task_queue: Option<String>,
1924    retry_policy: Option<Value>,
1925    start_to_close_timeout: Option<u64>,
1926    schedule_to_start_timeout: Option<u64>,
1927    schedule_to_close_timeout: Option<u64>,
1928    heartbeat_timeout: Option<u64>,
1929    cancellation_policy: Option<CancellationPolicy>,
1930}
1931
1932fn validate_timeout_order(
1933    smaller_name: &'static str,
1934    smaller: Option<Duration>,
1935    larger_name: &'static str,
1936    larger: Option<Duration>,
1937) -> std::result::Result<(), ActivityOptionsError> {
1938    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1939        return Err(ActivityOptionsError::new(
1940            ActivityOptionsErrorKind::TimeoutOrder,
1941            Some(smaller_name),
1942            format!("{smaller_name} must be <= {larger_name}"),
1943        ));
1944    }
1945    Ok(())
1946}
1947
1948fn timeout_seconds(
1949    field: &'static str,
1950    value: Option<Duration>,
1951) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1952    value
1953        .map(|value| {
1954            activity_protocol_seconds(value).ok_or_else(|| {
1955                ActivityOptionsError::new(
1956                    ActivityOptionsErrorKind::TimeoutOverflow,
1957                    Some(field),
1958                    format!("{field} is too large for the worker protocol"),
1959                )
1960            })
1961        })
1962        .transpose()
1963}
1964
1965fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1966    value
1967        .as_secs()
1968        .checked_add(u64::from(value.subsec_nanos() > 0))
1969}
1970
1971fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1972    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1973}
1974
1975fn validate_activity_retry_policy(
1976    policy: &ActivityRetryPolicy,
1977) -> std::result::Result<Value, ActivityOptionsError> {
1978    if policy.max_attempts.is_none()
1979        && policy.backoff.is_none()
1980        && policy.non_retryable_error_types.is_empty()
1981    {
1982        return Err(ActivityOptionsError::new(
1983            ActivityOptionsErrorKind::EmptyRetryPolicy,
1984            Some("retry_policy"),
1985            "retry_policy must configure at least one field",
1986        ));
1987    }
1988    if policy.max_attempts == Some(0) {
1989        return Err(ActivityOptionsError::new(
1990            ActivityOptionsErrorKind::InvalidMaxAttempts,
1991            Some("retry_policy.max_attempts"),
1992            "max_attempts must be >= 1",
1993        ));
1994    }
1995    if policy
1996        .non_retryable_error_types
1997        .iter()
1998        .any(|error_type| error_type.trim().is_empty())
1999    {
2000        return Err(ActivityOptionsError::new(
2001            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2002            Some("retry_policy.non_retryable_error_types"),
2003            "non_retryable_error_types must not contain empty values",
2004        ));
2005    }
2006
2007    let backoff_seconds = match &policy.backoff {
2008        None => None,
2009        Some(backoff) => {
2010            let max_attempts = policy.max_attempts.ok_or_else(|| {
2011                ActivityOptionsError::new(
2012                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2013                    Some("retry_policy.backoff"),
2014                    "backoff requires max_attempts",
2015                )
2016            })?;
2017            let retry_count = max_attempts.saturating_sub(1) as usize;
2018            let intervals = match backoff {
2019                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2020                ActivityBackoff::Exponential {
2021                    initial_interval,
2022                    coefficient,
2023                    maximum_interval,
2024                } => {
2025                    if *coefficient < 1 {
2026                        return Err(ActivityOptionsError::new(
2027                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2028                            Some("retry_policy.backoff.coefficient"),
2029                            "backoff coefficient must be >= 1",
2030                        ));
2031                    }
2032                    if retry_count > 10_000 {
2033                        return Err(ActivityOptionsError::new(
2034                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2035                            Some("retry_policy.max_attempts"),
2036                            "generated backoff supports at most 10000 retry intervals",
2037                        ));
2038                    }
2039                    let mut current = *initial_interval;
2040                    let mut intervals = Vec::with_capacity(retry_count);
2041                    for _ in 0..retry_count {
2042                        let interval = maximum_interval
2043                            .map(|maximum| current.min(maximum))
2044                            .unwrap_or(current);
2045                        intervals.push(interval);
2046                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2047                            break;
2048                        }
2049                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2050                            ActivityOptionsError::new(
2051                                ActivityOptionsErrorKind::BackoffOverflow,
2052                                Some("retry_policy.backoff"),
2053                                "generated backoff interval overflowed",
2054                            )
2055                        })?;
2056                    }
2057                    intervals
2058                }
2059            };
2060            Some(
2061                intervals
2062                    .into_iter()
2063                    .map(|interval| {
2064                        activity_protocol_seconds(interval).ok_or_else(|| {
2065                            ActivityOptionsError::new(
2066                                ActivityOptionsErrorKind::BackoffOverflow,
2067                                Some("retry_policy.backoff"),
2068                                "backoff interval is too large for the worker protocol",
2069                            )
2070                        })
2071                    })
2072                    .collect::<std::result::Result<Vec<_>, _>>()?,
2073            )
2074        }
2075    };
2076
2077    let mut encoded = serde_json::Map::new();
2078    if let Some(max_attempts) = policy.max_attempts {
2079        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2080    }
2081    if let Some(backoff_seconds) = backoff_seconds {
2082        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2083    }
2084    if !policy.non_retryable_error_types.is_empty() {
2085        let mut canonical_error_types = Vec::new();
2086        for error_type in policy
2087            .non_retryable_error_types
2088            .iter()
2089            .map(|error_type| error_type.trim())
2090        {
2091            if !canonical_error_types.contains(&error_type) {
2092                canonical_error_types.push(error_type);
2093            }
2094        }
2095        encoded.insert(
2096            "non_retryable_error_types".to_string(),
2097            json!(canonical_error_types),
2098        );
2099    }
2100    Ok(Value::Object(encoded))
2101}
2102
2103/// A stable, machine-readable failure raised when workflow code no longer
2104/// reconstructs the durable command stream recorded in history.
2105#[derive(Clone, Debug, Error)]
2106#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2107pub struct ReplayFailure {
2108    pub reason: String,
2109    pub sequence: Option<u64>,
2110    pub expected: Option<String>,
2111    pub actual: Option<String>,
2112    pub message: String,
2113}
2114
2115impl ReplayFailure {
2116    fn new(
2117        reason: impl Into<String>,
2118        sequence: Option<u64>,
2119        expected: Option<String>,
2120        actual: Option<String>,
2121        message: impl Into<String>,
2122    ) -> Self {
2123        Self {
2124            reason: reason.into(),
2125            sequence,
2126            expected,
2127            actual,
2128            message: message.into(),
2129        }
2130    }
2131}
2132
2133/// A stable, machine-readable workflow query or query-task settlement failure.
2134#[derive(Clone, Debug, Error)]
2135#[error("query failed ({reason}, HTTP {status}): {message}")]
2136pub struct QueryFailure {
2137    pub status: u16,
2138    pub reason: String,
2139    pub message: String,
2140    pub body: Value,
2141}
2142
2143/// A stable failure returned when a server rejects an SDK protocol version.
2144#[derive(Clone, Debug, Error)]
2145#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2146pub struct ProtocolFailure {
2147    pub status: u16,
2148    pub reason: String,
2149    pub message: String,
2150    pub supported_version: Option<String>,
2151    pub requested_version: Option<String>,
2152    pub body: Value,
2153}
2154
2155#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2156pub struct PayloadEnvelope {
2157    pub codec: String,
2158    pub blob: String,
2159}
2160
2161impl PayloadEnvelope {
2162    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2163        encode_payload(value, DEFAULT_CODEC)
2164    }
2165
2166    /// Encode an explicit typed value, including the bytes branch that JSON
2167    /// serialization cannot represent.
2168    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2169        encode_avro_value(value)
2170    }
2171}
2172
2173/// Native adapter for the fixed language-neutral Avro Value schema.
2174#[derive(Clone, Debug)]
2175pub enum AvroValue {
2176    Null,
2177    Boolean(bool),
2178    Long(i64),
2179    Double(f64),
2180    Bytes(Vec<u8>),
2181    String(String),
2182    Array(Vec<AvroValue>),
2183    Map(BTreeMap<String, AvroValue>),
2184}
2185
2186impl PartialEq for AvroValue {
2187    fn eq(&self, other: &Self) -> bool {
2188        match (self, other) {
2189            (Self::Null, Self::Null) => true,
2190            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2191            (Self::Long(left), Self::Long(right)) => left == right,
2192            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2193            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2194            (Self::String(left), Self::String(right)) => left == right,
2195            (Self::Array(left), Self::Array(right)) => left == right,
2196            (Self::Map(left), Self::Map(right)) => left == right,
2197            _ => false,
2198        }
2199    }
2200}
2201
2202impl AvroValue {
2203    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2204        Self::from_serde_value(
2205            serde_value::to_value(value).map_err(|error| {
2206                Error::Codec(format!("could not adapt value for Avro: {error}"))
2207            })?,
2208        )
2209    }
2210
2211    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2212        use serde_value::Value as SerdeValue;
2213
2214        match value {
2215            SerdeValue::Unit => Ok(Self::Null),
2216            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2217            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2218            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2219            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2220            SerdeValue::I64(value) => Ok(Self::Long(value)),
2221            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2222            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2223            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2224            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2225                Error::Codec(
2226                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2227                        .to_string(),
2228                )
2229            }),
2230            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2231            SerdeValue::F64(value) => Self::finite_double(value),
2232            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2233            SerdeValue::String(value) => Ok(Self::String(value)),
2234            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2235            SerdeValue::Option(None) => Ok(Self::Null),
2236            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2237                Self::from_serde_value(*value)
2238            }
2239            SerdeValue::Seq(values) => values
2240                .into_iter()
2241                .map(Self::from_serde_value)
2242                .collect::<Result<Vec<_>>>()
2243                .map(Self::Array),
2244            SerdeValue::Map(values) => values
2245                .into_iter()
2246                .map(|(key, value)| {
2247                    let SerdeValue::String(key) = key else {
2248                        return Err(Error::Codec(
2249                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2250                        ));
2251                    };
2252
2253                    Ok((key, Self::from_serde_value(value)?))
2254                })
2255                .collect::<Result<BTreeMap<_, _>>>()
2256                .map(Self::Map),
2257        }
2258    }
2259
2260    fn finite_double(value: f64) -> Result<Self> {
2261        if !value.is_finite() {
2262            return Err(Error::Codec(
2263                "non_finite_float: Avro Value doubles must be finite".to_string(),
2264            ));
2265        }
2266
2267        Ok(Self::Double(value))
2268    }
2269
2270    fn into_json(self) -> Result<Value> {
2271        match self {
2272            Self::Null => Ok(Value::Null),
2273            Self::Boolean(value) => Ok(Value::Bool(value)),
2274            Self::Long(value) => Ok(Value::Number(value.into())),
2275            Self::Double(value) => serde_json::Number::from_f64(value)
2276                .map(Value::Number)
2277                .ok_or_else(|| {
2278                    Error::Codec(
2279                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2280                    )
2281                }),
2282            Self::Bytes(value) => Ok(json!({
2283                "$type": "bytes",
2284                "base64": BASE64.encode(value),
2285            })),
2286            Self::String(value) => Ok(Value::String(value)),
2287            Self::Array(values) => values
2288                .into_iter()
2289                .map(Self::into_json)
2290                .collect::<Result<Vec<_>>>()
2291                .map(Value::Array),
2292            Self::Map(values) => values
2293                .into_iter()
2294                .map(|(key, value)| Ok((key, value.into_json()?)))
2295                .collect::<Result<serde_json::Map<_, _>>>()
2296                .map(Value::Object),
2297        }
2298    }
2299
2300    fn into_serde_value(self) -> serde_value::Value {
2301        use serde_value::Value as SerdeValue;
2302
2303        match self {
2304            Self::Null => SerdeValue::Unit,
2305            Self::Boolean(value) => SerdeValue::Bool(value),
2306            Self::Long(value) => SerdeValue::I64(value),
2307            Self::Double(value) => SerdeValue::F64(value),
2308            Self::Bytes(value) => SerdeValue::Bytes(value),
2309            Self::String(value) => SerdeValue::String(value),
2310            Self::Array(values) => {
2311                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2312            }
2313            Self::Map(values) => SerdeValue::Map(
2314                values
2315                    .into_iter()
2316                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2317                    .collect(),
2318            ),
2319        }
2320    }
2321
2322    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2323        self.into_serde_value().deserialize_into().map_err(|error| {
2324            Error::Codec(format!(
2325                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2326            ))
2327        })
2328    }
2329}
2330
2331impl Serialize for AvroValue {
2332    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2333    where
2334        S: Serializer,
2335    {
2336        match self {
2337            Self::Null => serializer.serialize_unit(),
2338            Self::Boolean(value) => serializer.serialize_bool(*value),
2339            Self::Long(value) => serializer.serialize_i64(*value),
2340            Self::Double(value) => serializer.serialize_f64(*value),
2341            Self::Bytes(value) => serializer.serialize_bytes(value),
2342            Self::String(value) => serializer.serialize_str(value),
2343            Self::Array(values) => {
2344                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2345                for value in values {
2346                    sequence.serialize_element(value)?;
2347                }
2348                sequence.end()
2349            }
2350            Self::Map(values) => {
2351                let mut map = serializer.serialize_map(Some(values.len()))?;
2352                for (key, value) in values {
2353                    map.serialize_entry(key, value)?;
2354                }
2355                map.end()
2356            }
2357        }
2358    }
2359}
2360
2361pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2362    let datum = avro_value_to_datum(value)?;
2363    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2364        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2365    let mut bytes = Vec::with_capacity(datum.len() + 10);
2366    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2367    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2368    bytes.extend_from_slice(&datum);
2369    Ok(PayloadEnvelope {
2370        codec: DEFAULT_CODEC.to_string(),
2371        blob: BASE64.encode(bytes),
2372    })
2373}
2374
2375pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2376    if envelope.codec != DEFAULT_CODEC {
2377        return Err(unsupported_payload_codec(&envelope.codec));
2378    }
2379    decode_avro_value_blob(&envelope.blob)
2380}
2381
2382pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2383    let blob = match codec {
2384        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2385        other => return Err(unsupported_payload_codec(other)),
2386    };
2387
2388    Ok(PayloadEnvelope {
2389        codec: codec.to_string(),
2390        blob,
2391    })
2392}
2393
2394pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2395    match envelope.codec.as_str() {
2396        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2397        other => Err(unsupported_payload_codec(other)),
2398    }
2399}
2400
2401fn handler_type_error<T>(
2402    handler_kind: HandlerKind,
2403    handler_name: &str,
2404    value_kind: HandlerValueKind,
2405    message: impl Into<String>,
2406) -> Error {
2407    Error::HandlerType {
2408        handler_kind,
2409        handler_name: handler_name.to_string(),
2410        value_kind,
2411        rust_type: type_name::<T>(),
2412        message: message.into(),
2413    }
2414}
2415
2416fn decode_handler_input<T: DeserializeOwned>(
2417    arguments: AvroValue,
2418    handler_kind: HandlerKind,
2419    handler_name: &str,
2420) -> Result<T> {
2421    let argument = match arguments {
2422        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2423            arguments.pop().expect("one typed handler argument")
2424        }
2425        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2426        AvroValue::Array(arguments) => {
2427            return Err(handler_type_error::<T>(
2428                handler_kind,
2429                handler_name,
2430                HandlerValueKind::Input,
2431                format!(
2432                    "typed handlers accept one request value, but the task carried {} arguments",
2433                    arguments.len()
2434                ),
2435            ));
2436        }
2437        argument => argument,
2438    };
2439
2440    argument.deserialize().map_err(|error| {
2441        handler_type_error::<T>(
2442            handler_kind,
2443            handler_name,
2444            HandlerValueKind::Input,
2445            error.to_string(),
2446        )
2447    })
2448}
2449
2450fn decode_workflow_entry<T: DeserializeOwned>(
2451    arguments: AvroValue,
2452    workflow_type: &str,
2453) -> Result<T> {
2454    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2455        // Serde errors may contain recorded values. The entry refusal exposes
2456        // only the registered workflow and expected Rust type.
2457        handler_type_error::<T>(
2458            HandlerKind::Workflow,
2459            workflow_type,
2460            HandlerValueKind::Input,
2461            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2462        )
2463    })
2464}
2465
2466fn encode_handler_result<T: Serialize>(
2467    result: &T,
2468    handler_kind: HandlerKind,
2469    handler_name: &str,
2470) -> Result<AvroValue> {
2471    AvroValue::from_serialize(result).map_err(|error| {
2472        handler_type_error::<T>(
2473            handler_kind,
2474            handler_name,
2475            HandlerValueKind::Result,
2476            error.to_string(),
2477        )
2478    })
2479}
2480
2481fn decode_handler_result<T: DeserializeOwned>(
2482    result: AvroValue,
2483    handler_kind: HandlerKind,
2484    handler_name: &str,
2485) -> Result<T> {
2486    result.deserialize().map_err(|error| {
2487        handler_type_error::<T>(
2488            handler_kind,
2489            handler_name,
2490            HandlerValueKind::Result,
2491            error.to_string(),
2492        )
2493    })
2494}
2495
2496#[cfg(test)]
2497fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2498    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2499}
2500
2501fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2502    validate_payload_codec(fallback_codec)?;
2503
2504    if value.is_null() {
2505        return Ok(Value::Null);
2506    }
2507
2508    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2509        return decode_blob(blob, codec);
2510    }
2511
2512    if let Some(blob) = value.as_str() {
2513        return decode_blob(blob, fallback_codec);
2514    }
2515
2516    Err(untagged_payload_value())
2517}
2518
2519fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2520    let envelope = match codec {
2521        DEFAULT_CODEC => encode_avro_value(value)?,
2522        other => return Err(unsupported_payload_codec(other)),
2523    };
2524    Ok(serde_json::to_value(envelope)?)
2525}
2526
2527fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2528    validate_payload_codec(fallback_codec)?;
2529
2530    if value.is_null() {
2531        return Ok(AvroValue::Null);
2532    }
2533
2534    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2535        validate_payload_codec(codec)?;
2536        return decode_avro_value_blob(blob);
2537    }
2538
2539    if let Some(blob) = value.as_str() {
2540        return match fallback_codec {
2541            DEFAULT_CODEC => decode_avro_value_blob(blob),
2542            other => Err(unsupported_payload_codec(other)),
2543        };
2544    }
2545
2546    Err(untagged_payload_value())
2547}
2548
2549fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2550    match value {
2551        AvroValue::Null => AvroValue::Array(Vec::new()),
2552        AvroValue::Array(_) => value,
2553        other => AvroValue::Array(vec![other]),
2554    }
2555}
2556
2557fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2558    match codec {
2559        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2560        other => Err(unsupported_payload_codec(other)),
2561    }
2562}
2563
2564fn validate_payload_codec(codec: &str) -> Result<()> {
2565    match codec {
2566        DEFAULT_CODEC => Ok(()),
2567        MISSING_TASK_PAYLOAD_CODEC => {
2568            Err(invalid_task_payload_codec("task payload_codec is missing"))
2569        }
2570        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2571        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2572            "task payload_codec must be a string",
2573        )),
2574        other => Err(unsupported_payload_codec(other)),
2575    }
2576}
2577
2578fn invalid_task_payload_codec(reason: &str) -> Error {
2579    Error::Codec(format!(
2580        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2581    ))
2582}
2583
2584fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2585    let Some(object) = value.as_object() else {
2586        return Ok(None);
2587    };
2588    if !object.contains_key("codec") && !object.contains_key("blob") {
2589        return Ok(None);
2590    }
2591
2592    let codec = object
2593        .get("codec")
2594        .and_then(Value::as_str)
2595        .ok_or_else(invalid_payload_envelope)?;
2596    validate_payload_codec(codec)?;
2597    let blob = object
2598        .get("blob")
2599        .and_then(Value::as_str)
2600        .ok_or_else(invalid_payload_envelope)?;
2601    Ok(Some((codec, blob)))
2602}
2603
2604fn invalid_payload_envelope() -> Error {
2605    Error::Codec(
2606        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2607            .to_string(),
2608    )
2609}
2610
2611fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2612    for command in commands {
2613        let Some(command) = command.as_object() else {
2614            continue;
2615        };
2616        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2617            continue;
2618        };
2619        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2620            continue;
2621        };
2622
2623        if let Some(codec) = command.get("payload_codec") {
2624            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2625            validate_payload_codec(codec)?;
2626        }
2627
2628        let payload = command
2629            .get(payload_field)
2630            .ok_or_else(invalid_payload_envelope)?;
2631        if runtime_payloads::Reference::parse(payload)?.is_none() {
2632            validate_outbound_payload_envelope(payload)?;
2633        }
2634    }
2635    Ok(())
2636}
2637
2638fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2639    if commands.iter().any(|command| {
2640        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2641            && command
2642                .get("condition_wait_occurrence_id")
2643                .and_then(Value::as_str)
2644                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2645    }) {
2646        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2647    } else if commands.iter().any(|command| {
2648        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2649            && command.get("attribute_types").is_some()
2650    }) {
2651        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2652    } else if commands
2653        .iter()
2654        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2655    {
2656        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2657    } else if commands
2658        .iter()
2659        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2660    {
2661        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2662    } else if commands.iter().any(|command| {
2663        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2664    }) {
2665        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2666    } else {
2667        MINIMUM_WORKER_PROTOCOL_VERSION
2668    }
2669}
2670
2671fn workflow_completion_protocol_version_with_message_streams(
2672    commands: &[Value],
2673    has_message_stream_metadata: bool,
2674) -> &'static str {
2675    let command_protocol = workflow_completion_protocol_version(commands);
2676    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2677        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2678    } else {
2679        command_protocol
2680    }
2681}
2682
2683fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2684    match command_type {
2685        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2686        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2687        "start_service_operation" => Some("request_payload"),
2688        "upsert_memo" => Some("entries"),
2689        _ => None,
2690    }
2691}
2692
2693fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2694    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2695        return Err(untagged_payload_value());
2696    };
2697    validate_payload_codec(codec)?;
2698    decode_avro_value_blob(blob)?;
2699    Ok(())
2700}
2701
2702fn unsupported_payload_codec(codec: &str) -> Error {
2703    Error::Codec(format!(
2704        "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"
2705    ))
2706}
2707
2708fn untagged_payload_value() -> Error {
2709    Error::Codec(
2710        "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"
2711            .to_string(),
2712    )
2713}
2714
2715fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2716    let bytes = BASE64.decode(blob).map_err(|err| {
2717        Error::Codec(format!(
2718            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2719        ))
2720    })?;
2721
2722    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2723        return Err(unsupported_payload_codec("json"));
2724    }
2725
2726    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2727        return Err(Error::Codec(
2728            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2729        ));
2730    }
2731
2732    let fingerprint: [u8; 8] = bytes[2..10]
2733        .try_into()
2734        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2735    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2736        return Err(Error::Codec(format!(
2737            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2738            fingerprint
2739                .iter()
2740                .map(|byte| format!("{byte:02x}"))
2741                .collect::<String>()
2742        )));
2743    }
2744
2745    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2746    // The current fingerprint selects the current immutable schema, so reader
2747    // resolution would only re-walk the same recursive union. Future retained
2748    // writer fingerprints supply a distinct reader schema in this branch.
2749    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2750    if datum_reader.truncated {
2751        return Err(Error::Codec(
2752            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2753        ));
2754    }
2755    let datum = datum.map_err(|err| {
2756        Error::Codec(format!(
2757            "invalid_payload_framing: malformed Avro Value datum: {err}"
2758        ))
2759    })?;
2760    if datum_reader.remaining() != 0 {
2761        return Err(Error::Codec(format!(
2762            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2763            datum_reader.remaining()
2764        )));
2765    }
2766    avro_value_from_datum(datum)
2767}
2768
2769struct StrictAvroDatumReader<'a> {
2770    bytes: &'a [u8],
2771    offset: usize,
2772    truncated: bool,
2773}
2774
2775impl<'a> StrictAvroDatumReader<'a> {
2776    fn new(bytes: &'a [u8]) -> Self {
2777        Self {
2778            bytes,
2779            offset: 0,
2780            truncated: false,
2781        }
2782    }
2783
2784    fn remaining(&self) -> usize {
2785        self.bytes.len() - self.offset
2786    }
2787}
2788
2789impl Read for StrictAvroDatumReader<'_> {
2790    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2791        let count = buffer.len().min(self.remaining());
2792        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2793        self.offset += count;
2794        if count < buffer.len() {
2795            self.truncated = true;
2796        }
2797
2798        Ok(count)
2799    }
2800}
2801
2802fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2803    let branch = match value {
2804        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2805        AvroValue::Boolean(value) => AvroDatum::Union(
2806            1,
2807            Box::new(AvroDatum::Record(vec![(
2808                "boolean".to_string(),
2809                AvroDatum::Boolean(*value),
2810            )])),
2811        ),
2812        AvroValue::Long(value) => AvroDatum::Union(
2813            2,
2814            Box::new(AvroDatum::Record(vec![(
2815                "long".to_string(),
2816                AvroDatum::Long(*value),
2817            )])),
2818        ),
2819        AvroValue::Double(value) => {
2820            if !value.is_finite() {
2821                return Err(Error::Codec(
2822                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2823                ));
2824            }
2825            AvroDatum::Union(
2826                3,
2827                Box::new(AvroDatum::Record(vec![(
2828                    "double".to_string(),
2829                    AvroDatum::Double(*value),
2830                )])),
2831            )
2832        }
2833        AvroValue::Bytes(value) => AvroDatum::Union(
2834            4,
2835            Box::new(AvroDatum::Record(vec![(
2836                "bytes".to_string(),
2837                AvroDatum::Bytes(value.clone()),
2838            )])),
2839        ),
2840        AvroValue::String(value) => AvroDatum::Union(
2841            5,
2842            Box::new(AvroDatum::Record(vec![(
2843                "string".to_string(),
2844                AvroDatum::String(value.clone()),
2845            )])),
2846        ),
2847        AvroValue::Array(values) => AvroDatum::Union(
2848            6,
2849            Box::new(AvroDatum::Record(vec![(
2850                "items".to_string(),
2851                AvroDatum::Array(
2852                    values
2853                        .iter()
2854                        .map(avro_value_to_datum)
2855                        .collect::<Result<Vec<_>>>()?,
2856                ),
2857            )])),
2858        ),
2859        AvroValue::Map(values) => AvroDatum::Union(
2860            7,
2861            Box::new(AvroDatum::Record(vec![(
2862                "entries".to_string(),
2863                AvroDatum::Array(
2864                    values
2865                        .iter()
2866                        .map(|(key, value)| {
2867                            Ok(AvroDatum::Record(vec![
2868                                ("key".to_string(), AvroDatum::String(key.clone())),
2869                                ("value".to_string(), avro_value_to_datum(value)?),
2870                            ]))
2871                        })
2872                        .collect::<Result<Vec<_>>>()?,
2873                ),
2874            )])),
2875        ),
2876    };
2877    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2878}
2879
2880fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2881    let AvroDatum::Record(mut outer) = datum else {
2882        return Err(Error::Codec(
2883            "invalid_payload_framing: datum is not a Value record".to_string(),
2884        ));
2885    };
2886    let (_, branch) = outer
2887        .pop()
2888        .filter(|(name, _)| name == "value")
2889        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2890    let AvroDatum::Union(_, branch) = branch else {
2891        return Err(Error::Codec(
2892            "invalid_payload_framing: invalid Value union".to_string(),
2893        ));
2894    };
2895    match *branch {
2896        AvroDatum::Null => Ok(AvroValue::Null),
2897        AvroDatum::Record(mut fields) => {
2898            let (name, value) = fields.pop().ok_or_else(|| {
2899                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2900            })?;
2901            match (name.as_str(), value) {
2902                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2903                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2904                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2905                    Ok(AvroValue::Double(value))
2906                }
2907                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2908                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2909                ("items", AvroDatum::Array(values)) => values
2910                    .into_iter()
2911                    .map(avro_value_from_datum)
2912                    .collect::<Result<Vec<_>>>()
2913                    .map(AvroValue::Array),
2914                ("entries", AvroDatum::Map(values)) => values
2915                    .into_iter()
2916                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2917                    .collect::<Result<BTreeMap<_, _>>>()
2918                    .map(AvroValue::Map),
2919                _ => Err(Error::Codec(
2920                    "invalid_payload_framing: unknown Value branch".to_string(),
2921                )),
2922            }
2923        }
2924        _ => Err(Error::Codec(
2925            "invalid_payload_framing: invalid Value branch".to_string(),
2926        )),
2927    }
2928}
2929
2930fn avro_value_schema() -> Result<&'static Schema> {
2931    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2932        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2933            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2934    }) {
2935        Ok(schema) => Ok(schema),
2936        Err(message) => Err(Error::Codec(message.clone())),
2937    }
2938}
2939
2940fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2941    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2942        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2943        // have the same block representation when each ordered array record
2944        // contains the map key followed by its value, so this encoding-only
2945        // adaptation lets the official encoder retain BTreeMap wire order.
2946        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2947            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2948        let entries_schema = schema
2949            .pointer_mut("/fields/0/type/7/fields/0/type")
2950            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2951        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2952            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2953        }
2954        *entries_schema = json!({
2955            "type": "array",
2956            "items": {
2957                "type": "record",
2958                "name": "MapEntry",
2959                "fields": [
2960                    {"name": "key", "type": "string"},
2961                    {"name": "value", "type": "Value"}
2962                ]
2963            }
2964        });
2965        Schema::parse_str(&schema.to_string())
2966            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2967    }) {
2968        Ok(schema) => Ok(schema),
2969        Err(message) => Err(Error::Codec(message.clone())),
2970    }
2971}
2972
2973#[derive(Clone, Debug)]
2974pub struct Client {
2975    http: reqwest::Client,
2976    hydration_timeout: Duration,
2977    base_url: String,
2978    token: Option<String>,
2979    control_token: Option<String>,
2980    worker_token: Option<String>,
2981    namespace: String,
2982    max_external_payload_bytes: usize,
2983    worker_storage_admission: Option<WorkerStorageAdmission>,
2984    cooperative_worker_protocol: bool,
2985    worker_protocol_version: WorkerProtocolVersion,
2986    local_activities_enabled: bool,
2987    worker_sessions_enabled: bool,
2988    max_concurrent_worker_sessions: usize,
2989    worker_build_id: Option<String>,
2990    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2991    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2992    activity_lease_renewal_supported: Arc<AtomicBool>,
2993    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
2994    #[cfg(feature = "telemetry")]
2995    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
2996    #[cfg(feature = "telemetry")]
2997    observability_context_supported: Arc<AtomicBool>,
2998}
2999
3000impl Client {
3001    /// Configure optional propagation. Actual cluster discovery must advertise
3002    /// the exact supported capability before any command carries context.
3003    #[cfg(feature = "telemetry")]
3004    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3005        self.execution_telemetry = Some(telemetry);
3006        self
3007    }
3008
3009    #[cfg(feature = "telemetry")]
3010    fn with_observability_context(&self, mut body: Value) -> Value {
3011        if self.observability_context_supported.load(Ordering::SeqCst) {
3012            if let Some(context) = self
3013                .execution_telemetry
3014                .as_ref()
3015                .and_then(|telemetry| telemetry.capture())
3016            {
3017                body["observability_context"] = context;
3018            }
3019        }
3020        body
3021    }
3022
3023    #[cfg(not(feature = "telemetry"))]
3024    fn with_observability_context(&self, body: Value) -> Value {
3025        body
3026    }
3027
3028    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3029        Self::builder(base_url).build()
3030    }
3031
3032    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3033        ClientBuilder {
3034            base_url: base_url.into(),
3035            token: None,
3036            control_token: None,
3037            worker_token: None,
3038            namespace: "default".to_string(),
3039            timeout: Duration::from_secs(60),
3040            max_external_payload_bytes: 64 * 1024 * 1024,
3041            worker_protocol_version: WorkerProtocolVersion::default(),
3042        }
3043    }
3044
3045    pub async fn health(&self) -> Result<Value> {
3046        self.request_json(
3047            reqwest::Method::GET,
3048            "/health",
3049            RequestProtocol::ControlPlane,
3050            Option::<&Value>::None,
3051        )
3052        .await
3053    }
3054
3055    pub async fn cluster_info(&self) -> Result<Value> {
3056        let discovery: Value = self
3057            .request_json(
3058                reqwest::Method::GET,
3059                "/cluster/info",
3060                RequestProtocol::ControlPlane,
3061                Option::<&Value>::None,
3062            )
3063            .await?;
3064        self.observe_activity_lease_capabilities(
3065            &discovery["worker_protocol"]["server_capabilities"],
3066        );
3067        Ok(discovery)
3068    }
3069
3070    pub async fn start_workflow<T: Serialize>(
3071        &self,
3072        workflow_type: &str,
3073        task_queue: &str,
3074        workflow_id: &str,
3075        input: T,
3076    ) -> Result<WorkflowHandle> {
3077        self.start_workflow_with_options(
3078            workflow_type,
3079            task_queue,
3080            workflow_id,
3081            WorkflowStartOptions::default(),
3082            input,
3083        )
3084        .await
3085    }
3086
3087    /// Start a workflow with explicit server-enforced execution and run
3088    /// deadlines.
3089    pub async fn start_workflow_with_options<T: Serialize>(
3090        &self,
3091        workflow_type: &str,
3092        task_queue: &str,
3093        workflow_id: &str,
3094        options: WorkflowStartOptions,
3095        input: T,
3096    ) -> Result<WorkflowHandle> {
3097        options.validate()?;
3098        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3099        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3100        let body = self.with_observability_context(json!({
3101            "workflow_id": workflow_id,
3102            "workflow_type": workflow_type,
3103            "task_queue": task_queue,
3104            "input": input_envelope,
3105            "execution_timeout_seconds": options.execution_timeout_seconds,
3106            "run_timeout_seconds": options.run_timeout_seconds
3107        }));
3108
3109        let data: Value = self
3110            .request_json(
3111                reqwest::Method::POST,
3112                "/workflows",
3113                RequestProtocol::ControlPlane,
3114                Some(&body),
3115            )
3116            .await?;
3117
3118        Ok(WorkflowHandle {
3119            client: self.clone(),
3120            workflow_id: data
3121                .get("workflow_id")
3122                .and_then(Value::as_str)
3123                .unwrap_or(workflow_id)
3124                .to_string(),
3125            run_id: data
3126                .get("run_id")
3127                .and_then(Value::as_str)
3128                .map(str::to_string),
3129            workflow_type: data
3130                .get("workflow_type")
3131                .and_then(Value::as_str)
3132                .unwrap_or(workflow_type)
3133                .to_string(),
3134        })
3135    }
3136
3137    /// Send a signal with an SDK-generated caller command key.
3138    ///
3139    /// The key is sent as the `request_id` body field and is present in the
3140    /// returned receipt's `request_id`. A Server that already retains the key
3141    /// for the same signal intent returns the original receipt with
3142    /// `retained: true`; a different intent is refused with
3143    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3144    /// [`Client::signal_workflow_with_request_id`] when the application must be
3145    /// able to retry the same logical signal after a transport failure.
3146    pub async fn signal_workflow<T: Serialize>(
3147        &self,
3148        workflow_id: &str,
3149        signal_name: &str,
3150        input: T,
3151    ) -> Result<Value> {
3152        let request_id = Self::generate_signal_request_id();
3153        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3154            .await
3155    }
3156
3157    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3158    ///
3159    /// Resend the identical signal with the same key after an uncertain
3160    /// outcome: the Server returns the retained receipt instead of admitting a
3161    /// second signal, for as long as the retained run's details are kept.
3162    pub async fn signal_workflow_with_request_id<T: Serialize>(
3163        &self,
3164        workflow_id: &str,
3165        signal_name: &str,
3166        input: T,
3167        request_id: &str,
3168    ) -> Result<Value> {
3169        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3170            .await
3171    }
3172
3173    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3174    ///
3175    /// Methods without an explicit key generate one of these per call. Obtain it
3176    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3177    /// transport failure does not lose the key needed for a safe retry.
3178    pub fn generate_signal_request_id() -> String {
3179        generated_request_id("signal")
3180    }
3181
3182    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3183    ///
3184    /// [`Client::update_workflow`] generates one of these when `request_id` is
3185    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3186    /// does not lose the key needed for a safe retry.
3187    pub fn generate_update_request_id() -> String {
3188        generated_request_id("update")
3189    }
3190
3191    /// Append one idempotently identified item to an instance-scoped input stream.
3192    pub async fn append_message_stream<T: Serialize>(
3193        &self,
3194        workflow_id: &str,
3195        stream_name: &str,
3196        message_id: &str,
3197        input: T,
3198    ) -> Result<Value> {
3199        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3200        let body = json!({
3201            "message_id": message_id,
3202            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3203        });
3204        self.request_json(
3205            reqwest::Method::POST,
3206            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
3207            RequestProtocol::ControlPlane,
3208            Some(&body),
3209        )
3210        .await
3211    }
3212
3213    /// Signal only if `run_id` is still the current run for this instance,
3214    /// with an SDK-generated caller command key.
3215    pub async fn signal_workflow_run<T: Serialize>(
3216        &self,
3217        workflow_id: &str,
3218        run_id: &str,
3219        signal_name: &str,
3220        input: T,
3221    ) -> Result<Value> {
3222        let request_id = Self::generate_signal_request_id();
3223        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3224            .await
3225    }
3226
3227    /// Signal only if `run_id` is still the current run for this instance,
3228    /// with an explicit caller command key (1 to 255 Unicode characters).
3229    ///
3230    /// The selected run is part of the signal's intent: retrying with the same
3231    /// key and a different run target is a `request_id_conflict` refusal.
3232    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3233        &self,
3234        workflow_id: &str,
3235        run_id: &str,
3236        signal_name: &str,
3237        input: T,
3238        request_id: &str,
3239    ) -> Result<Value> {
3240        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3241            .await
3242    }
3243
3244    async fn signal_workflow_target<T: Serialize>(
3245        &self,
3246        workflow_id: &str,
3247        run_id: Option<&str>,
3248        signal_name: &str,
3249        input: T,
3250        request_id: &str,
3251    ) -> Result<Value> {
3252        validate_user_signal_name(signal_name)?;
3253        validate_request_id(request_id)?;
3254        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3255        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3256        let body = self.with_observability_context(json!({
3257            "input": input_envelope,
3258            "request_id": request_id,
3259        }));
3260        let path = match run_id {
3261            Some(run_id) => {
3262                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3263            }
3264            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3265        };
3266        let receipt = self
3267            .request_json(
3268                reqwest::Method::POST,
3269                &path,
3270                RequestProtocol::ControlPlane,
3271                Some(&body),
3272            )
3273            .await?;
3274        Ok(with_request_id(receipt, request_id))
3275    }
3276
3277    /// Close the current run as cancelled immediately.
3278    ///
3279    /// Server revokes open tasks and timers without resuming workflow code for
3280    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3281    /// request on a supporting runtime and opted-in worker.
3282    pub async fn cancel_workflow(
3283        &self,
3284        workflow_id: &str,
3285        options: WorkflowCommandOptions,
3286    ) -> Result<WorkflowCommandResult> {
3287        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3288            .await
3289    }
3290
3291    /// Close the selected run as cancelled, only if `run_id` is still current.
3292    pub async fn cancel_workflow_run(
3293        &self,
3294        workflow_id: &str,
3295        run_id: &str,
3296        options: WorkflowCommandOptions,
3297    ) -> Result<WorkflowCommandResult> {
3298        self.workflow_command(
3299            workflow_id,
3300            Some(run_id),
3301            WorkflowCommandKind::Cancel,
3302            options,
3303        )
3304        .await
3305    }
3306
3307    /// Forcefully terminate the current run for an instance.
3308    pub async fn terminate_workflow(
3309        &self,
3310        workflow_id: &str,
3311        options: WorkflowCommandOptions,
3312    ) -> Result<WorkflowCommandResult> {
3313        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3314            .await
3315    }
3316
3317    /// Forcefully terminate only if `run_id` is still current.
3318    pub async fn terminate_workflow_run(
3319        &self,
3320        workflow_id: &str,
3321        run_id: &str,
3322        options: WorkflowCommandOptions,
3323    ) -> Result<WorkflowCommandResult> {
3324        self.workflow_command(
3325            workflow_id,
3326            Some(run_id),
3327            WorkflowCommandKind::Terminate,
3328            options,
3329        )
3330        .await
3331    }
3332
3333    /// Continue a failed run from its recorded activity failure boundary.
3334    pub async fn redrive_workflow_run(
3335        &self,
3336        workflow_id: &str,
3337        failed_run_id: &str,
3338        request_id: Option<&str>,
3339    ) -> Result<WorkflowRedriveResult> {
3340        let body = request_id
3341            .map(|id| json!({"request_id": id}))
3342            .unwrap_or_else(|| json!({}));
3343        let data: Value = self
3344            .request_json(
3345                reqwest::Method::POST,
3346                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3347                RequestProtocol::ControlPlane,
3348                Some(&body),
3349            )
3350            .await?;
3351        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3352            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3353        {
3354            return Err(Error::Codec(
3355                "redrive response was not accepted".to_string(),
3356            ));
3357        }
3358        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3359            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3360        {
3361            return Err(Error::Codec(
3362                "redrive response does not match the requested source run".to_string(),
3363            ));
3364        }
3365        let run_id = data
3366            .get("run_id")
3367            .and_then(Value::as_str)
3368            .filter(|id| !id.is_empty() && *id != failed_run_id)
3369            .ok_or_else(|| {
3370                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3371            })?;
3372        let resume_step_sequence = data
3373            .get("resume_step_sequence")
3374            .and_then(Value::as_u64)
3375            .filter(|sequence| *sequence > 0)
3376            .ok_or_else(|| {
3377                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3378            })?;
3379        Ok(WorkflowRedriveResult {
3380            workflow_id: workflow_id.to_string(),
3381            source_run_id: failed_run_id.to_string(),
3382            run_id: run_id.to_string(),
3383            resume_step_sequence,
3384            raw: data,
3385        })
3386    }
3387
3388    async fn workflow_command(
3389        &self,
3390        workflow_id: &str,
3391        run_id: Option<&str>,
3392        command: WorkflowCommandKind,
3393        options: WorkflowCommandOptions,
3394    ) -> Result<WorkflowCommandResult> {
3395        #[cfg(feature = "telemetry")]
3396        let body = if command == WorkflowCommandKind::Cancel {
3397            self.with_observability_context(serde_json::to_value(&options)?)
3398        } else {
3399            serde_json::to_value(&options)?
3400        };
3401        #[cfg(not(feature = "telemetry"))]
3402        let body = &options;
3403        let path = match run_id {
3404            Some(run_id) => format!(
3405                "/workflows/{workflow_id}/runs/{run_id}/{}",
3406                command.as_str()
3407            ),
3408            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3409        };
3410        let data = match self
3411            .request_json(
3412                reqwest::Method::POST,
3413                &path,
3414                RequestProtocol::ControlPlane,
3415                Some(&body),
3416            )
3417            .await
3418        {
3419            Ok(data) => data,
3420            Err(Error::Http { status, body }) => {
3421                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3422                    command,
3423                    status,
3424                    body,
3425                    workflow_id,
3426                    run_id,
3427                )));
3428            }
3429            Err(error) => return Err(error),
3430        };
3431
3432        Ok(workflow_command_result(command, data, workflow_id, run_id))
3433    }
3434
3435    /// Execute a named, read-only query against a running or completed workflow.
3436    ///
3437    /// Arguments and results use the platform payload envelope. Server and
3438    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3439    /// reason, HTTP status, and original response body.
3440    pub async fn query_workflow<T: Serialize>(
3441        &self,
3442        workflow_id: &str,
3443        query_name: &str,
3444        input: T,
3445    ) -> Result<Value> {
3446        self.query_workflow_target(workflow_id, None, query_name, input)
3447            .await
3448    }
3449
3450    /// Query only if `run_id` is still current, preventing accidental retargeting.
3451    pub async fn query_workflow_run<T: Serialize>(
3452        &self,
3453        workflow_id: &str,
3454        run_id: &str,
3455        query_name: &str,
3456        input: T,
3457    ) -> Result<Value> {
3458        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3459            .await
3460    }
3461
3462    /// Query a workflow and return the lossless fixed Avro Value result.
3463    pub async fn query_workflow_avro_value<T: Serialize>(
3464        &self,
3465        workflow_id: &str,
3466        query_name: &str,
3467        input: T,
3468    ) -> Result<AvroValue> {
3469        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3470            .await
3471    }
3472
3473    /// Query a selected run and return the lossless fixed Avro Value result.
3474    pub async fn query_workflow_run_avro_value<T: Serialize>(
3475        &self,
3476        workflow_id: &str,
3477        run_id: &str,
3478        query_name: &str,
3479        input: T,
3480    ) -> Result<AvroValue> {
3481        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3482            .await
3483    }
3484
3485    async fn query_workflow_avro_value_target<T: Serialize>(
3486        &self,
3487        workflow_id: &str,
3488        run_id: Option<&str>,
3489        query_name: &str,
3490        input: T,
3491    ) -> Result<AvroValue> {
3492        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3493        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3494        let path = match run_id {
3495            Some(run_id) => {
3496                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3497            }
3498            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3499        };
3500        let response: Value = match self
3501            .request_json(
3502                reqwest::Method::POST,
3503                &path,
3504                RequestProtocol::ControlPlane,
3505                Some(&body),
3506            )
3507            .await
3508        {
3509            Ok(response) => response,
3510            Err(Error::Http { status, body }) => {
3511                return Err(Error::QueryFailed(query_failure(status, body)));
3512            }
3513            Err(error) => return Err(error),
3514        };
3515
3516        let envelope = response
3517            .get("result_envelope")
3518            .filter(|envelope| !envelope.is_null())
3519            .ok_or_else(|| {
3520                Error::Codec(
3521                    "missing_payload_envelope: typed query result requires result_envelope"
3522                        .to_string(),
3523                )
3524            })?;
3525        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3526    }
3527
3528    async fn query_workflow_target<T: Serialize>(
3529        &self,
3530        workflow_id: &str,
3531        run_id: Option<&str>,
3532        query_name: &str,
3533        input: T,
3534    ) -> Result<Value> {
3535        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3536        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3537        let body = json!({
3538            "input": input_envelope
3539        });
3540        let path = match run_id {
3541            Some(run_id) => {
3542                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3543            }
3544            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3545        };
3546        let response: Value = match self
3547            .request_json(
3548                reqwest::Method::POST,
3549                &path,
3550                RequestProtocol::ControlPlane,
3551                Some(&body),
3552            )
3553            .await
3554        {
3555            Ok(response) => response,
3556            Err(Error::Http { status, body }) => {
3557                return Err(Error::QueryFailed(query_failure(status, body)));
3558            }
3559            Err(error) => return Err(error),
3560        };
3561
3562        if let Some(envelope) = response
3563            .get("result_envelope")
3564            .filter(|envelope| !envelope.is_null())
3565        {
3566            return decode_wire_value(envelope, DEFAULT_CODEC);
3567        }
3568
3569        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3570    }
3571
3572    /// Send a synchronous update using fixed Avro Value arguments.
3573    ///
3574    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
3575    /// `request_id` body field; `None` generates one with
3576    /// [`Client::generate_update_request_id`]. A Server that already retains the
3577    /// key for the same update intent returns the original update's receipt and
3578    /// result instead of admitting a second update; a different intent is
3579    /// refused with [`Error::is_request_id_conflict`].
3580    pub async fn update_workflow<T: Serialize>(
3581        &self,
3582        workflow_id: &str,
3583        update_name: &str,
3584        input: T,
3585        request_id: Option<&str>,
3586    ) -> Result<Value> {
3587        let response = self
3588            .update_workflow_response(workflow_id, update_name, input, request_id)
3589            .await?;
3590        if let Some(envelope) = response
3591            .get("result_envelope")
3592            .filter(|envelope| !envelope.is_null())
3593        {
3594            return decode_wire_value(envelope, DEFAULT_CODEC);
3595        }
3596        Ok(response.get("result").cloned().unwrap_or(response))
3597    }
3598
3599    /// Send a synchronous update and retain a bytes-capable Avro result.
3600    pub async fn update_workflow_avro_value<T: Serialize>(
3601        &self,
3602        workflow_id: &str,
3603        update_name: &str,
3604        input: T,
3605        request_id: Option<&str>,
3606    ) -> Result<AvroValue> {
3607        let response = self
3608            .update_workflow_response(workflow_id, update_name, input, request_id)
3609            .await?;
3610        let envelope = response
3611            .get("result_envelope")
3612            .filter(|envelope| !envelope.is_null())
3613            .ok_or_else(|| {
3614                Error::Codec(
3615                    "missing_payload_envelope: typed update result requires result_envelope"
3616                        .to_string(),
3617                )
3618            })?;
3619        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3620    }
3621
3622    async fn update_workflow_response<T: Serialize>(
3623        &self,
3624        workflow_id: &str,
3625        update_name: &str,
3626        input: T,
3627        request_id: Option<&str>,
3628    ) -> Result<Value> {
3629        let request_id = match request_id {
3630            Some(request_id) => {
3631                validate_request_id(request_id)?;
3632                request_id.to_string()
3633            }
3634            None => Self::generate_update_request_id(),
3635        };
3636        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3637        let body = self.with_observability_context(json!({
3638            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3639            "wait_for": "completed",
3640            "request_id": request_id,
3641        }));
3642        let receipt = self
3643            .request_json(
3644                reqwest::Method::POST,
3645                &format!("/workflows/{workflow_id}/update/{update_name}"),
3646                RequestProtocol::ControlPlane,
3647                Some(&body),
3648            )
3649            .await?;
3650        Ok(with_request_id(receipt, &request_id))
3651    }
3652
3653    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3654        let path = format!("/workflows/{workflow_id}");
3655        let mut data: WorkflowDescription = self
3656            .request_json(
3657                reqwest::Method::GET,
3658                &path,
3659                RequestProtocol::ControlPlane,
3660                Option::<&Value>::None,
3661            )
3662            .await?;
3663        data.decode_payloads()?;
3664        Ok(data)
3665    }
3666
3667    /// Describe one selected run, including historical terminal runs.
3668    pub async fn describe_workflow_run(
3669        &self,
3670        workflow_id: &str,
3671        run_id: &str,
3672    ) -> Result<WorkflowDescription> {
3673        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3674        let mut data: WorkflowDescription = self
3675            .request_json(
3676                reqwest::Method::GET,
3677                &path,
3678                RequestProtocol::ControlPlane,
3679                Option::<&Value>::None,
3680            )
3681            .await?;
3682        data.decode_payloads()?;
3683        Ok(data)
3684    }
3685
3686    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3687        let mut path = format!(
3688            "/workflows/{}/runs/{}/streams",
3689            percent_encode_path_segment(workflow_id),
3690            percent_encode_path_segment(run_id),
3691        );
3692        if let Some(stream_name) = stream_name {
3693            path.push('/');
3694            path.push_str(&percent_encode_path_segment(stream_name));
3695        }
3696        path
3697    }
3698
3699    /// List the run-scoped output streams already opened by a workflow.
3700    pub async fn list_workflow_streams(
3701        &self,
3702        workflow_id: &str,
3703        run_id: &str,
3704    ) -> Result<Vec<WorkflowStreamDescription>> {
3705        let response: WorkflowStreamListResponse = self
3706            .request_json(
3707                reqwest::Method::GET,
3708                &Self::workflow_stream_path(workflow_id, run_id, None),
3709                RequestProtocol::ControlPlane,
3710                Option::<&Value>::None,
3711            )
3712            .await?;
3713        Ok(response.streams)
3714    }
3715
3716    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3717    pub async fn describe_workflow_stream(
3718        &self,
3719        workflow_id: &str,
3720        run_id: &str,
3721        stream_name: &str,
3722    ) -> Result<WorkflowStreamDescription> {
3723        let response: WorkflowStreamDescriptionResponse = self
3724            .request_json(
3725                reqwest::Method::GET,
3726                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3727                RequestProtocol::ControlPlane,
3728                Option::<&Value>::None,
3729            )
3730            .await?;
3731        Ok(response.stream)
3732    }
3733
3734    /// Read one bounded page beginning at a zero-based offset.
3735    ///
3736    /// Delivery is at least once: persist `next_offset` only after processing
3737    /// the page. The future is cancellation-safe; dropping it cancels the
3738    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3739    /// service contract.
3740    pub async fn subscribe_workflow_stream(
3741        &self,
3742        workflow_id: &str,
3743        run_id: &str,
3744        stream_name: &str,
3745        from_offset: u64,
3746        max_items: usize,
3747        wait: Duration,
3748    ) -> Result<WorkflowStreamPage> {
3749        let max_items = max_items.clamp(1, 500);
3750        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3751        let path = format!(
3752            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3753            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3754        );
3755        let response: WorkflowStreamPageResponse = self
3756            .request_json_with_timeout(
3757                reqwest::Method::GET,
3758                &path,
3759                RequestProtocol::ControlPlane,
3760                Option::<&Value>::None,
3761                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3762            )
3763            .await?;
3764
3765        let items = response
3766            .items
3767            .into_iter()
3768            .map(|raw| {
3769                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3770                let envelope = raw.get("payload").cloned();
3771                let payload = envelope
3772                    .as_ref()
3773                    .filter(|value| value.get("blob").is_some())
3774                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3775                    .transpose()?
3776                    .map(AvroValue::into_json)
3777                    .transpose()?;
3778                Ok(WorkflowStreamItem {
3779                    offset,
3780                    payload,
3781                    payload_envelope: envelope,
3782                    payload_reference: raw
3783                        .get("payload_reference")
3784                        .and_then(Value::as_str)
3785                        .map(str::to_string),
3786                    payload_codec: raw
3787                        .get("payload_codec")
3788                        .and_then(Value::as_str)
3789                        .map(str::to_string),
3790                    idempotency_key: raw
3791                        .get("idempotency_key")
3792                        .and_then(Value::as_str)
3793                        .map(str::to_string),
3794                    item_type: raw
3795                        .get("item_type")
3796                        .and_then(Value::as_str)
3797                        .map(str::to_string),
3798                    content_type: raw
3799                        .get("content_type")
3800                        .and_then(Value::as_str)
3801                        .map(str::to_string),
3802                    origin: raw
3803                        .get("origin")
3804                        .and_then(Value::as_str)
3805                        .map(str::to_string),
3806                    origin_reference: raw
3807                        .get("origin_reference")
3808                        .and_then(Value::as_str)
3809                        .map(str::to_string),
3810                    emitted_at: raw
3811                        .get("emitted_at")
3812                        .and_then(Value::as_str)
3813                        .map(str::to_string),
3814                    raw,
3815                })
3816            })
3817            .collect::<Result<Vec<_>>>()?;
3818        Ok(WorkflowStreamPage {
3819            stream: response.stream,
3820            items,
3821            next_offset: response.next_offset,
3822            terminal: response.terminal,
3823        })
3824    }
3825
3826    /// Append inline Avro envelopes or opaque external payload references.
3827    pub async fn append_workflow_stream(
3828        &self,
3829        workflow_id: &str,
3830        run_id: &str,
3831        stream_name: &str,
3832        items: &[WorkflowStreamAppendItem],
3833        max_pending_items: Option<u64>,
3834    ) -> Result<WorkflowStreamAppendResult> {
3835        if items.is_empty() {
3836            return Err(Error::Codec(
3837                "workflow_stream_items_empty: append requires at least one item".to_string(),
3838            ));
3839        }
3840        let mut body = json!({
3841            "items": items
3842                .iter()
3843                .map(|item| item.wire_value(None))
3844                .collect::<Vec<_>>(),
3845        });
3846        if let Some(max_pending_items) = max_pending_items {
3847            if max_pending_items == 0 {
3848                return Err(Error::Codec(
3849                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3850                        .to_string(),
3851                ));
3852            }
3853            body["max_pending_items"] = json!(max_pending_items);
3854        }
3855        let response: WorkflowStreamAppendResponse = self
3856            .request_json(
3857                reqwest::Method::POST,
3858                &format!(
3859                    "{}/items",
3860                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3861                ),
3862                RequestProtocol::ControlPlane,
3863                Some(&body),
3864            )
3865            .await?;
3866        Ok(WorkflowStreamAppendResult {
3867            stream: response.stream,
3868            accepted_offsets: response.accepted_offsets,
3869            accepted: response.accepted,
3870            deduped: response.deduped,
3871        })
3872    }
3873
3874    /// Close a stream, or mark it errored when `error_reason` is supplied.
3875    pub async fn close_workflow_stream(
3876        &self,
3877        workflow_id: &str,
3878        run_id: &str,
3879        stream_name: &str,
3880        error_reason: Option<&str>,
3881        retention_seconds: Option<u64>,
3882    ) -> Result<WorkflowStreamDescription> {
3883        let mut body = json!({});
3884        if let Some(error_reason) = error_reason {
3885            body["error_reason"] = json!(error_reason);
3886        }
3887        if let Some(retention_seconds) = retention_seconds {
3888            if retention_seconds == 0 {
3889                return Err(Error::Codec(
3890                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3891                        .to_string(),
3892                ));
3893            }
3894            body["retention_seconds"] = json!(retention_seconds);
3895        }
3896        let response: WorkflowStreamDescriptionResponse = self
3897            .request_json(
3898                reqwest::Method::POST,
3899                &format!(
3900                    "{}/close",
3901                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3902                ),
3903                RequestProtocol::ControlPlane,
3904                Some(&body),
3905            )
3906            .await?;
3907        Ok(response.stream)
3908    }
3909
3910    pub async fn register_worker(
3911        &self,
3912        worker_id: &str,
3913        task_queue: &str,
3914        supported_workflow_types: Vec<String>,
3915        supported_activity_types: Vec<String>,
3916        max_concurrent_workflow_tasks: usize,
3917        max_concurrent_activity_tasks: usize,
3918    ) -> Result<RegisterWorkerResponse> {
3919        self.register_worker_with_capabilities(
3920            worker_id,
3921            task_queue,
3922            supported_workflow_types,
3923            supported_activity_types,
3924            max_concurrent_workflow_tasks,
3925            max_concurrent_activity_tasks,
3926            Vec::new(),
3927        )
3928        .await
3929    }
3930
3931    /// Register a worker and explicitly advertise additive worker capabilities.
3932    pub async fn register_worker_with_capabilities(
3933        &self,
3934        worker_id: &str,
3935        task_queue: &str,
3936        supported_workflow_types: Vec<String>,
3937        supported_activity_types: Vec<String>,
3938        max_concurrent_workflow_tasks: usize,
3939        max_concurrent_activity_tasks: usize,
3940        capabilities: Vec<String>,
3941    ) -> Result<RegisterWorkerResponse> {
3942        self.register_worker_with_command_contracts(
3943            worker_id,
3944            task_queue,
3945            supported_workflow_types,
3946            supported_activity_types,
3947            max_concurrent_workflow_tasks,
3948            max_concurrent_activity_tasks,
3949            capabilities,
3950            Value::Object(serde_json::Map::new()),
3951        )
3952        .await
3953    }
3954
3955    /// Register a worker and advertise its named query and update handlers.
3956    ///
3957    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3958    /// so a workflow contract with a non-empty or malformed
3959    /// `update_validators` declaration returns
3960    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3961    #[allow(clippy::too_many_arguments)]
3962    pub async fn register_worker_with_command_contracts(
3963        &self,
3964        worker_id: &str,
3965        task_queue: &str,
3966        supported_workflow_types: Vec<String>,
3967        supported_activity_types: Vec<String>,
3968        max_concurrent_workflow_tasks: usize,
3969        max_concurrent_activity_tasks: usize,
3970        capabilities: Vec<String>,
3971        workflow_command_contracts: Value,
3972    ) -> Result<RegisterWorkerResponse> {
3973        self.register_worker_with_definition_fingerprints(
3974            worker_id,
3975            task_queue,
3976            supported_workflow_types,
3977            supported_activity_types,
3978            max_concurrent_workflow_tasks,
3979            max_concurrent_activity_tasks,
3980            capabilities,
3981            workflow_command_contracts,
3982            None,
3983        )
3984        .await
3985    }
3986
3987    #[allow(clippy::too_many_arguments)]
3988    async fn register_worker_with_definition_fingerprints(
3989        &self,
3990        worker_id: &str,
3991        task_queue: &str,
3992        supported_workflow_types: Vec<String>,
3993        supported_activity_types: Vec<String>,
3994        max_concurrent_workflow_tasks: usize,
3995        max_concurrent_activity_tasks: usize,
3996        capabilities: Vec<String>,
3997        workflow_command_contracts: Value,
3998        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3999    ) -> Result<RegisterWorkerResponse> {
4000        if let Some(contracts) = workflow_command_contracts.as_object() {
4001            for (workflow_type, contract) in contracts {
4002                let Some(update_validators) = contract.get("update_validators") else {
4003                    continue;
4004                };
4005                if !update_validators
4006                    .as_array()
4007                    .is_some_and(|validators| validators.is_empty())
4008                {
4009                    return Err(Error::UnsupportedUpdateValidators {
4010                        workflow_type: workflow_type.clone(),
4011                    });
4012                }
4013            }
4014        }
4015
4016        let mut body = json!({
4017            "worker_id": worker_id,
4018            "task_queue": task_queue,
4019            "runtime": "rust",
4020            "sdk_version": SDK_VERSION,
4021            "supported_workflow_types": supported_workflow_types,
4022            "supported_activity_types": supported_activity_types,
4023            "capabilities": capabilities,
4024            "capability_manifest": portable_worker_affinity_capability_manifest(),
4025            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4026            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4027        });
4028        if capabilities
4029            .iter()
4030            .any(|capability| capability == "nexus_cooperative_cancellation")
4031        {
4032            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4033                "supported":true, "minimum_protocol_version":"1.20",
4034                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4035            });
4036        }
4037        if let Some(build_id) = &self.worker_build_id {
4038            if build_id.is_empty() || build_id.len() > 255 {
4039                return Err(Error::WorkerLoop(
4040                    "worker build ID must contain 1 to 255 bytes".into(),
4041                ));
4042            }
4043            body["build_id"] = json!(build_id);
4044        }
4045        if self.sticky_cache.is_some() {
4046            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4047                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4048                "implementation":"bounded_durable_history_cache"});
4049        }
4050        if self.local_activities_enabled {
4051            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4052                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4053        }
4054        if self.worker_sessions_enabled {
4055            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4056                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4057            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4058        }
4059        if workflow_command_contracts
4060            .as_object()
4061            .is_some_and(|contracts| !contracts.is_empty())
4062        {
4063            body["workflow_command_contracts"] = workflow_command_contracts;
4064        }
4065        if let Some(fingerprints) = workflow_definition_fingerprints {
4066            body["workflow_definition_fingerprints"] = json!(fingerprints);
4067        }
4068
4069        let response: Value = self
4070            .request_json(
4071                reqwest::Method::POST,
4072                "/worker/register",
4073                RequestProtocol::DefaultWorker,
4074                Some(&body),
4075            )
4076            .await?;
4077        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4078            self.observe_activity_lease_capabilities(&response["server_capabilities"]);
4079        }
4080        if self.sticky_cache.is_some() {
4081            self.confirm_sticky_registration(&response, worker_id, task_queue)
4082                .await?;
4083        }
4084        if self.local_activities_enabled || self.worker_sessions_enabled {
4085            let compatible = response["registered"].as_bool() == Some(true)
4086                && response["worker_id"].as_str() == Some(worker_id)
4087                && response["namespace"].as_str() == Some(self.namespace.as_str())
4088                && response["task_queue"].as_str() == Some(task_queue)
4089                && response["protocol_version"]
4090                    .as_str()
4091                    .and_then(|version| version.strip_prefix("1."))
4092                    .and_then(|minor| minor.parse::<u64>().ok())
4093                    .is_some_and(|minor| minor >= 18)
4094                && (!self.local_activities_enabled
4095                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4096                        == Some(true))
4097                && (!self.worker_sessions_enabled
4098                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4099                        == Some(true)
4100                        && response["capabilities"].as_array().is_some_and(|accepted| {
4101                            capabilities.iter().all(|capability| {
4102                                accepted
4103                                    .iter()
4104                                    .any(|value| value.as_str() == Some(capability.as_str()))
4105                            })
4106                        })));
4107            if !compatible {
4108                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4109                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4110                } else {
4111                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4112                });
4113                if response["registered"] == true
4114                    && response["worker_id"].as_str() == Some(worker_id)
4115                {
4116                    if let Err(deregistration) =
4117                        self.deregister_worker_registration(worker_id).await
4118                    {
4119                        return Err(Error::WorkerShutdown {
4120                            primary: Box::new(error),
4121                            deregistration: Box::new(deregistration),
4122                        });
4123                    }
4124                }
4125                return Err(error);
4126            }
4127        }
4128        if self.cooperative_worker_protocol {
4129            let compatible = response["registered"].as_bool() == Some(true)
4130                && response["worker_id"].as_str() == Some(worker_id)
4131                && response["namespace"].as_str() == Some(self.namespace.as_str())
4132                && response["task_queue"].as_str() == Some(task_queue)
4133                && response["protocol_version"]
4134                    .as_str()
4135                    .is_some_and(cooperative_cancellation::supports_protocol)
4136                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4137                    == Some(true)
4138                && (!capabilities
4139                    .iter()
4140                    .any(|capability| capability == "nexus_cooperative_cancellation")
4141                    || nexus::installed_cooperation(&response["server_capabilities"]))
4142                && response["capabilities"].as_array().is_some_and(|accepted| {
4143                    capabilities.iter().all(|capability| {
4144                        accepted
4145                            .iter()
4146                            .any(|value| value.as_str() == Some(capability.as_str()))
4147                    })
4148                });
4149            if !compatible {
4150                let error = Error::CooperativeCancellationUnavailable(
4151                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4152                );
4153                if response["registered"].as_bool() == Some(true)
4154                    && response["worker_id"].as_str() == Some(worker_id)
4155                {
4156                    if let Err(deregistration) =
4157                        self.deregister_worker_registration(worker_id).await
4158                    {
4159                        return Err(Error::WorkerShutdown {
4160                            primary: Box::new(error),
4161                            deregistration: Box::new(deregistration),
4162                        });
4163                    }
4164                }
4165                return Err(error);
4166            }
4167        }
4168        Ok(serde_json::from_value(response)?)
4169    }
4170
4171    /// Gracefully remove one worker's registration through the worker plane.
4172    ///
4173    /// This operation is separate from operator-facing worker management. It
4174    /// uses worker-protocol authentication and returns the server's lease
4175    /// recovery result.
4176    pub async fn deregister_worker_registration(
4177        &self,
4178        worker_id: &str,
4179    ) -> Result<WorkerDeregistrationEnvelope> {
4180        let path = format!(
4181            "/worker/registrations/{}",
4182            percent_encode_path_segment(worker_id)
4183        );
4184        self.request_json(
4185            reqwest::Method::DELETE,
4186            &path,
4187            RequestProtocol::DefaultWorker,
4188            Option::<&Value>::None,
4189        )
4190        .await
4191    }
4192
4193    /// Long-poll for an ephemeral, read-only workflow query task.
4194    pub async fn poll_query_task(
4195        &self,
4196        worker_id: &str,
4197        task_queue: &str,
4198        timeout: Duration,
4199    ) -> Result<Option<QueryTask>> {
4200        Ok(self
4201            .poll_query_task_response(worker_id, task_queue, timeout)
4202            .await?
4203            .task)
4204    }
4205
4206    /// Poll a query task while preserving server stop and drain metadata.
4207    pub async fn poll_query_task_response(
4208        &self,
4209        worker_id: &str,
4210        task_queue: &str,
4211        timeout: Duration,
4212    ) -> Result<PollQueryTaskResponse> {
4213        let poll_request_id = unique_request_id("rust-query-poll");
4214        self.poll_query_task_response_with_request_id(
4215            worker_id,
4216            task_queue,
4217            timeout,
4218            &poll_request_id,
4219            1,
4220        )
4221        .await
4222    }
4223
4224    async fn poll_query_task_response_with_request_id(
4225        &self,
4226        worker_id: &str,
4227        task_queue: &str,
4228        timeout: Duration,
4229        poll_request_id: &str,
4230        transport_retries: usize,
4231    ) -> Result<PollQueryTaskResponse> {
4232        let timeout_seconds = long_poll_timeout_seconds(timeout);
4233        let body = json!({
4234            "worker_id": worker_id,
4235            "task_queue": task_queue,
4236            "poll_request_id": poll_request_id,
4237            "timeout_seconds": timeout_seconds,
4238        });
4239        self.poll_request_json(
4240            "/worker/query-tasks/poll",
4241            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4242            &body,
4243            timeout + Duration::from_secs(5),
4244            transport_retries,
4245        )
4246        .await
4247    }
4248
4249    /// Complete a query task without appending workflow history.
4250    pub async fn complete_query_task<T: Serialize>(
4251        &self,
4252        query_task_id: &str,
4253        lease_owner: &str,
4254        query_task_attempt: u64,
4255        result: T,
4256        codec: &str,
4257    ) -> Result<Value> {
4258        let typed_result = AvroValue::from_serialize(&result)?;
4259        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4260        self.complete_query_task_with_envelope(
4261            query_task_id,
4262            lease_owner,
4263            query_task_attempt,
4264            typed_result.into_json()?,
4265            result_envelope,
4266        )
4267        .await
4268    }
4269
4270    async fn complete_query_task_with_envelope(
4271        &self,
4272        query_task_id: &str,
4273        lease_owner: &str,
4274        query_task_attempt: u64,
4275        result: Value,
4276        result_envelope: Value,
4277    ) -> Result<Value> {
4278        let body = json!({
4279            "lease_owner": lease_owner,
4280            "query_task_attempt": query_task_attempt,
4281            "result": result,
4282            "result_envelope": result_envelope,
4283        });
4284        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4285        let response = self
4286            .request_json(
4287                reqwest::Method::POST,
4288                &path,
4289                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4290                Some(&body),
4291            )
4292            .await;
4293        query_task_response(response)
4294    }
4295
4296    /// Report a stable machine-readable query-task failure.
4297    pub async fn fail_query_task(
4298        &self,
4299        query_task_id: &str,
4300        lease_owner: &str,
4301        query_task_attempt: u64,
4302        message: impl Into<String>,
4303        reason: impl Into<String>,
4304        failure_type: impl Into<String>,
4305    ) -> Result<Value> {
4306        let body = json!({
4307            "lease_owner": lease_owner,
4308            "query_task_attempt": query_task_attempt,
4309            "failure": {
4310                "message": message.into(),
4311                "reason": reason.into(),
4312                "type": failure_type.into(),
4313            }
4314        });
4315        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4316        let response = self
4317            .request_json(
4318                reqwest::Method::POST,
4319                &path,
4320                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4321                Some(&body),
4322            )
4323            .await;
4324        query_task_response(response)
4325    }
4326
4327    pub async fn heartbeat_worker(
4328        &self,
4329        worker_id: &str,
4330        workflow_available: usize,
4331        activity_available: usize,
4332    ) -> Result<Value> {
4333        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4334            .await
4335    }
4336
4337    async fn heartbeat_worker_with_sessions(
4338        &self,
4339        worker_id: &str,
4340        workflow_available: usize,
4341        activity_available: usize,
4342        session_available: Option<usize>,
4343    ) -> Result<Value> {
4344        let mut body = json!({
4345            "worker_id": worker_id,
4346            "task_slots": {
4347                "workflow_available": workflow_available,
4348                "activity_available": activity_available
4349            },
4350            "process_metrics": {
4351                "process_id": std::process::id(),
4352                "process_uptime_seconds": 0
4353            }
4354        });
4355
4356        if let Some(available) = session_available {
4357            body["task_slots"]["session_available"] = json!(available);
4358        }
4359
4360        self.request_json(
4361            reqwest::Method::POST,
4362            "/worker/heartbeat",
4363            RequestProtocol::DefaultWorker,
4364            Some(&body),
4365        )
4366        .await
4367    }
4368
4369    pub async fn poll_workflow_task(
4370        &self,
4371        worker_id: &str,
4372        task_queue: &str,
4373        timeout: Duration,
4374    ) -> Result<Option<WorkflowTask>> {
4375        Ok(self
4376            .poll_workflow_task_response(worker_id, task_queue, timeout)
4377            .await?
4378            .task)
4379    }
4380
4381    pub async fn poll_workflow_task_response(
4382        &self,
4383        worker_id: &str,
4384        task_queue: &str,
4385        timeout: Duration,
4386    ) -> Result<PollWorkflowTaskResponse> {
4387        let poll_request_id = unique_request_id("rust-workflow-poll");
4388        self.poll_workflow_task_response_with_request_id(
4389            worker_id,
4390            task_queue,
4391            timeout,
4392            &poll_request_id,
4393            1,
4394        )
4395        .await
4396    }
4397
4398    async fn poll_workflow_task_response_with_request_id(
4399        &self,
4400        worker_id: &str,
4401        task_queue: &str,
4402        timeout: Duration,
4403        poll_request_id: &str,
4404        transport_retries: usize,
4405    ) -> Result<PollWorkflowTaskResponse> {
4406        let body = json!({
4407            "worker_id": worker_id,
4408            "task_queue": task_queue,
4409            "poll_request_id": poll_request_id,
4410            "timeout_seconds": long_poll_timeout_seconds(timeout),
4411            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4412        });
4413        let mut wire: Value = self
4414            .poll_request_json_unresolved(
4415                "/worker/workflow-tasks/poll",
4416                RequestProtocol::DefaultWorker,
4417                &body,
4418                timeout + Duration::from_secs(5),
4419                transport_retries,
4420            )
4421            .await?;
4422        let claim =
4423            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4424        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4425            self.resolve_runtime_payloads(
4426                &mut wire,
4427                "/worker/workflow-tasks/poll",
4428                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4429            )
4430            .await?;
4431            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4432            if let Some(task) = data.task.as_mut() {
4433                self.fetch_remaining_workflow_history(worker_id, task)
4434                    .await?;
4435            }
4436            Ok(data)
4437        })
4438        .await?;
4439        Ok(data)
4440    }
4441
4442    async fn fetch_remaining_workflow_history(
4443        &self,
4444        worker_id: &str,
4445        task: &mut WorkflowTask,
4446    ) -> Result<()> {
4447        let mut next_token = task.next_history_page_token.clone();
4448        let mut seen = BTreeSet::new();
4449
4450        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4451            if seen.len() >= 128 || !seen.insert(token.clone()) {
4452                return Err(Error::Codec(
4453                    "workflow history pagination exceeded its page bound or repeated a token"
4454                        .into(),
4455                ));
4456            }
4457            let lease_owner = task
4458                .lease_owner
4459                .clone()
4460                .unwrap_or_else(|| worker_id.to_string());
4461            let page = self
4462                .workflow_task_history_page(
4463                    &task.task_id,
4464                    &lease_owner,
4465                    task.workflow_task_attempt,
4466                    &token,
4467                )
4468                .await?;
4469
4470            task.append_history_page(page);
4471
4472            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4473                return Err(Error::Codec(
4474                    "workflow history pagination returned the same page token".to_string(),
4475                ));
4476            }
4477
4478            next_token = task.next_history_page_token.clone();
4479        }
4480
4481        Ok(())
4482    }
4483
4484    async fn workflow_task_history_page(
4485        &self,
4486        task_id: &str,
4487        lease_owner: &str,
4488        workflow_task_attempt: u64,
4489        next_history_page_token: &str,
4490    ) -> Result<WorkflowTaskHistoryPage> {
4491        let body = json!({
4492            "lease_owner": lease_owner,
4493            "workflow_task_attempt": workflow_task_attempt,
4494            "next_history_page_token": next_history_page_token
4495        });
4496        let path = format!("/worker/workflow-tasks/{task_id}/history");
4497
4498        self.request_json(
4499            reqwest::Method::POST,
4500            &path,
4501            RequestProtocol::DefaultWorker,
4502            Some(&body),
4503        )
4504        .await
4505    }
4506
4507    pub async fn complete_workflow_task(
4508        &self,
4509        task_id: &str,
4510        lease_owner: &str,
4511        workflow_task_attempt: u64,
4512        commands: Vec<Value>,
4513    ) -> Result<Value> {
4514        self.complete_workflow_task_with_message_streams(
4515            task_id,
4516            lease_owner,
4517            workflow_task_attempt,
4518            commands,
4519            Vec::new(),
4520            Vec::new(),
4521            None,
4522        )
4523        .await
4524    }
4525
4526    #[allow(clippy::too_many_arguments)]
4527    async fn complete_workflow_task_with_message_streams(
4528        &self,
4529        task_id: &str,
4530        lease_owner: &str,
4531        workflow_task_attempt: u64,
4532        commands: Vec<Value>,
4533        message_stream_cursors: Vec<Value>,
4534        message_stream_waits: Vec<Value>,
4535        sticky_cache: Option<Value>,
4536    ) -> Result<Value> {
4537        validate_workflow_task_commands(&commands)?;
4538        let has_message_stream_metadata =
4539            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4540        if has_message_stream_metadata
4541            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4542        {
4543            return Err(Error::Codec(
4544                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4545                    .to_string(),
4546            ));
4547        }
4548        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4549            &commands,
4550            has_message_stream_metadata,
4551        );
4552        let protocol_version = if sticky_cache.is_some()
4553            && protocol_version
4554                .strip_prefix("1.")
4555                .and_then(|minor| minor.parse::<u64>().ok())
4556                .is_some_and(|minor| minor < 18)
4557        {
4558            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4559        } else {
4560            protocol_version
4561        };
4562        let mut body = json!({
4563            "lease_owner": lease_owner,
4564            "workflow_task_attempt": workflow_task_attempt,
4565            "commands": commands
4566        });
4567        #[cfg(feature = "telemetry")]
4568        if self.observability_context_supported.load(Ordering::SeqCst)
4569            && opentelemetry::Context::current()
4570                .get::<telemetry::ExecutionFields>()
4571                .is_some()
4572        {
4573            if let Some(commands) = body["commands"].as_array_mut() {
4574                for command in commands {
4575                    if command.get("observability_context").is_none()
4576                        && matches!(
4577                            command["type"].as_str(),
4578                            Some("start_child_workflow" | "continue_as_new")
4579                        )
4580                    {
4581                        *command = self.with_observability_context(command.take());
4582                    }
4583                }
4584            }
4585        }
4586        if !message_stream_cursors.is_empty() {
4587            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4588        }
4589        if !message_stream_waits.is_empty() {
4590            body["message_stream_waits"] = Value::Array(message_stream_waits);
4591        }
4592        if let Some(claim) = sticky_cache {
4593            body["sticky_cache"] = claim;
4594        }
4595        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4596        self.request_json(
4597            reqwest::Method::POST,
4598            &path,
4599            RequestProtocol::Worker(protocol_version),
4600            Some(&body),
4601        )
4602        .await
4603    }
4604
4605    pub async fn fail_workflow_task(
4606        &self,
4607        task_id: &str,
4608        lease_owner: &str,
4609        workflow_task_attempt: u64,
4610        message: impl Into<String>,
4611    ) -> Result<Value> {
4612        self.fail_workflow_task_with_type(
4613            task_id,
4614            lease_owner,
4615            workflow_task_attempt,
4616            message,
4617            "RustWorkflowTaskFailure",
4618        )
4619        .await
4620    }
4621
4622    async fn fail_workflow_task_with_type(
4623        &self,
4624        task_id: &str,
4625        lease_owner: &str,
4626        workflow_task_attempt: u64,
4627        message: impl Into<String>,
4628        failure_type: &str,
4629    ) -> Result<Value> {
4630        self.fail_workflow_task_with_failure(
4631            task_id,
4632            lease_owner,
4633            workflow_task_attempt,
4634            json!({"message": message.into(), "type": failure_type}),
4635        )
4636        .await
4637    }
4638
4639    async fn fail_workflow_task_with_failure(
4640        &self,
4641        task_id: &str,
4642        lease_owner: &str,
4643        workflow_task_attempt: u64,
4644        failure: Value,
4645    ) -> Result<Value> {
4646        let body = json!({
4647            "lease_owner": lease_owner,
4648            "workflow_task_attempt": workflow_task_attempt,
4649            "failure": failure,
4650        });
4651        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4652        self.request_json(
4653            reqwest::Method::POST,
4654            &path,
4655            RequestProtocol::DefaultWorker,
4656            Some(&body),
4657        )
4658        .await
4659    }
4660
4661    pub async fn poll_activity_task(
4662        &self,
4663        worker_id: &str,
4664        task_queue: &str,
4665        timeout: Duration,
4666    ) -> Result<Option<ActivityTask>> {
4667        Ok(self
4668            .poll_activity_task_response(worker_id, task_queue, timeout)
4669            .await?
4670            .task)
4671    }
4672
4673    /// Poll an activity task while preserving server stop and drain metadata.
4674    pub async fn poll_activity_task_response(
4675        &self,
4676        worker_id: &str,
4677        task_queue: &str,
4678        timeout: Duration,
4679    ) -> Result<PollActivityTaskResponse> {
4680        let poll_request_id = unique_request_id("rust-activity-poll");
4681        self.poll_activity_task_response_with_request_id(
4682            worker_id,
4683            task_queue,
4684            timeout,
4685            &poll_request_id,
4686            1,
4687        )
4688        .await
4689        .map(worker_session::SessionPollResponse::ordinary)
4690    }
4691
4692    async fn poll_activity_task_response_with_request_id(
4693        &self,
4694        worker_id: &str,
4695        task_queue: &str,
4696        timeout: Duration,
4697        poll_request_id: &str,
4698        transport_retries: usize,
4699    ) -> Result<worker_session::SessionPollResponse> {
4700        let body = json!({
4701            "worker_id": worker_id,
4702            "task_queue": task_queue,
4703            "poll_request_id": poll_request_id,
4704            "timeout_seconds": long_poll_timeout_seconds(timeout),
4705        });
4706        let mut wire: Value = self
4707            .poll_request_json_unresolved(
4708                "/worker/activity-tasks/poll",
4709                RequestProtocol::DefaultWorker,
4710                &body,
4711                timeout + Duration::from_secs(5),
4712                transport_retries,
4713            )
4714            .await?;
4715        let lease =
4716            activity_lease::authority::Lease::confirm(self, &wire, worker_id, task_queue).await?;
4717        let observed = self.with_activity_lease_authority(
4718            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
4719        );
4720        let claim = if lease.is_none() {
4721            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
4722        } else {
4723            None
4724        };
4725        let loading = async {
4726            observed
4727                .resolve_runtime_payloads(
4728                    &mut wire,
4729                    "/worker/activity-tasks/poll",
4730                    RequestProtocol::DefaultWorker,
4731                )
4732                .await?;
4733            if let Some(lease) = &lease {
4734                lease
4735                    .authority
4736                    .refresh_delivery_session(&mut wire["task"])?;
4737            }
4738            Ok(serde_json::from_value(wire)?)
4739        };
4740        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
4741            Some(lease) => lease.authority.protect(loading).await?,
4742            None => {
4743                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
4744            }
4745        };
4746        if let Some(task) = data.task.as_mut() {
4747            task.hydration_claim = claim;
4748            task.activity_lease = lease;
4749        }
4750        Ok(data)
4751    }
4752
4753    pub async fn complete_activity_task<T: Serialize>(
4754        &self,
4755        task_id: &str,
4756        activity_attempt_id: &str,
4757        lease_owner: &str,
4758        result: T,
4759        codec: &str,
4760    ) -> Result<Value> {
4761        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4762        let body = json!({
4763            "activity_attempt_id": activity_attempt_id,
4764            "lease_owner": lease_owner,
4765            "result": result
4766        });
4767        let path = format!("/worker/activity-tasks/{task_id}/complete");
4768        activity_task_response(
4769            self.request_json(
4770                reqwest::Method::POST,
4771                &path,
4772                RequestProtocol::DefaultWorker,
4773                Some(&body),
4774            )
4775            .await,
4776            "complete",
4777            task_id,
4778            activity_attempt_id,
4779        )
4780    }
4781
4782    pub async fn fail_activity_task(
4783        &self,
4784        task_id: &str,
4785        activity_attempt_id: &str,
4786        lease_owner: &str,
4787        message: impl Into<String>,
4788        non_retryable: bool,
4789    ) -> Result<Value> {
4790        self.fail_activity_task_with_error(
4791            task_id,
4792            activity_attempt_id,
4793            lease_owner,
4794            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
4795        )
4796        .await
4797    }
4798
4799    /// Report an activity's application-defined failure type and retry marker.
4800    pub async fn fail_activity_task_with_error(
4801        &self,
4802        task_id: &str,
4803        activity_attempt_id: &str,
4804        lease_owner: &str,
4805        error: &ActivityError,
4806    ) -> Result<Value> {
4807        let error = error.validated();
4808        let body = json!({
4809            "activity_attempt_id": activity_attempt_id,
4810            "lease_owner": lease_owner,
4811            "failure": {
4812                "message": error.message,
4813                "type": error.exception_type,
4814                "non_retryable": error.non_retryable
4815            }
4816        });
4817        let path = format!("/worker/activity-tasks/{task_id}/fail");
4818        activity_task_response(
4819            self.request_json(
4820                reqwest::Method::POST,
4821                &path,
4822                RequestProtocol::DefaultWorker,
4823                Some(&body),
4824            )
4825            .await,
4826            "fail",
4827            task_id,
4828            activity_attempt_id,
4829        )
4830    }
4831
4832    /// Record a flat map of scalar/null activity progress metadata.
4833    ///
4834    /// Heartbeat details use the Server's bounded JSON progress contract.
4835    /// They are not workflow payload envelopes.
4836    pub async fn heartbeat_activity_task<T: Serialize>(
4837        &self,
4838        task_id: &str,
4839        activity_attempt_id: &str,
4840        lease_owner: &str,
4841        details: T,
4842    ) -> Result<ActivityHeartbeatResponse> {
4843        serde_json::from_value(
4844            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4845                .await?,
4846        )
4847        .map_err(Error::from)
4848    }
4849
4850    async fn heartbeat_activity_task_value<T: Serialize>(
4851        &self,
4852        task_id: &str,
4853        activity_attempt_id: &str,
4854        lease_owner: &str,
4855        details: T,
4856    ) -> Result<Value> {
4857        let details = AvroValue::from_serialize(&details)?.into_json()?;
4858        let body = json!({
4859            "activity_attempt_id": activity_attempt_id,
4860            "lease_owner": lease_owner,
4861            "details": details
4862        });
4863        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4864        let started = tokio::time::Instant::now();
4865        let response = activity_task_response(
4866            self.request_json(
4867                reqwest::Method::POST,
4868                &path,
4869                RequestProtocol::DefaultWorker,
4870                Some(&body),
4871            )
4872            .await,
4873            "heartbeat",
4874            task_id,
4875            activity_attempt_id,
4876        )?;
4877        if let Some(authority) = &self.activity_lease_authority {
4878            authority.progress(&response, started)?;
4879        }
4880        Ok(response)
4881    }
4882
4883    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4884        &self,
4885        method: reqwest::Method,
4886        path: &str,
4887        protocol: RequestProtocol,
4888        body: Option<&B>,
4889    ) -> Result<T> {
4890        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4891            .await
4892    }
4893
4894    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4895        &self,
4896        method: reqwest::Method,
4897        path: &str,
4898        protocol: RequestProtocol,
4899        body: Option<&B>,
4900        timeout: Duration,
4901    ) -> Result<T> {
4902        let mut value: Value = self
4903            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4904            .await?;
4905        let protocol = match protocol {
4906            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4907                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4908            }
4909            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4910        };
4911        self.resolve_runtime_payloads(&mut value, path, protocol)
4912            .await?;
4913        Ok(serde_json::from_value(value)?)
4914    }
4915
4916    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
4917        Ok(match protocol {
4918            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4919                let selected = self.worker_protocol_version.as_str();
4920                if self.cooperative_worker_protocol
4921                    && !cooperative_cancellation::supports_protocol(selected)
4922                {
4923                    return Err(Error::CooperativeCancellationUnavailable(
4924                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4925                    ));
4926                }
4927                if let RequestProtocol::Worker(minimum) = protocol {
4928                    let supported = minimum
4929                        .strip_prefix("1.")
4930                        .and_then(|minor| minor.parse::<u64>().ok())
4931                        .zip(
4932                            selected
4933                                .strip_prefix("1.")
4934                                .and_then(|minor| minor.parse::<u64>().ok()),
4935                        )
4936                        .is_some_and(|(minimum, selected)| selected >= minimum);
4937                    if !supported {
4938                        return Err(Error::WorkerLoop(format!(
4939                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4940                        )));
4941                    }
4942                }
4943                RequestProtocol::Worker(selected)
4944            }
4945            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4946        })
4947    }
4948
4949    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
4950        match &self.activity_lease_authority {
4951            Some(authority) => authority.check(path, body),
4952            None => Ok(()),
4953        }
4954    }
4955
4956    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4957        &self,
4958        method: reqwest::Method,
4959        path: &str,
4960        protocol: RequestProtocol,
4961        body: Option<&B>,
4962        timeout: Duration,
4963    ) -> Result<T> {
4964        #[cfg(feature = "telemetry")]
4965        self.begin_observability_discovery(&method, path);
4966        let protocol = self.worker_request_protocol(protocol)?;
4967        let auth_token = self.auth_token(protocol)?;
4968        let mut request = self
4969            .http
4970            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4971            .timeout(timeout)
4972            .header(reqwest::header::ACCEPT, "application/json")
4973            .header(reqwest::header::CONTENT_TYPE, "application/json")
4974            .header("X-Namespace", &self.namespace);
4975
4976        match protocol {
4977            RequestProtocol::DefaultWorker => {
4978                request = request.header(
4979                    "X-Durable-Workflow-Protocol-Version",
4980                    self.worker_protocol_version.as_str(),
4981                );
4982            }
4983            RequestProtocol::Worker(version) => {
4984                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4985            }
4986            RequestProtocol::ControlPlane => {
4987                request = request.header(
4988                    "X-Durable-Workflow-Control-Plane-Version",
4989                    CONTROL_PLANE_VERSION,
4990                );
4991            }
4992        }
4993
4994        if let Some(token) = auth_token {
4995            request = request.bearer_auth(token);
4996        }
4997
4998        if let Some(body) = body {
4999            let mut body = serde_json::to_value(body)?;
5000            if matches!(
5001                method,
5002                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5003            ) {
5004                self.check_activity_lease_request(path, Some(&body))?;
5005                self.externalize_runtime_payloads(&mut body, path, protocol)
5006                    .await?;
5007                self.check_activity_lease_request(path, Some(&body))?;
5008            }
5009            request = request.json(&body);
5010        }
5011
5012        let request = request.build()?;
5013        let request_body = request
5014            .body()
5015            .and_then(reqwest::Body::as_bytes)
5016            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5017        let poll_request_id = path.ends_with("/poll").then(|| {
5018            request_body
5019                .as_ref()
5020                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5021                .unwrap_or_default()
5022        });
5023        let mut storage_retries = 0_usize;
5024        let mut deferred_workflow_completion = false;
5025
5026        loop {
5027            // Keep the serialized body and lease/poll identity across admission pauses.
5028            self.check_activity_lease_request(path, request_body.as_ref())?;
5029            let receive = async {
5030                let response = self
5031                    .http
5032                    .execute(request.try_clone().ok_or_else(|| {
5033                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5034                    })?)
5035                    .await?;
5036                let status = response.status();
5037                Ok::<_, Error>((status, response.bytes().await?))
5038            };
5039            let retry_deadline = self
5040                .worker_storage_admission
5041                .as_ref()
5042                .and_then(|admission| admission.workflow_completion_retry_deadline);
5043            if deferred_workflow_completion
5044                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5045            {
5046                return Err(Error::Timeout);
5047            }
5048            let received = async {
5049                match retry_deadline.filter(|_| deferred_workflow_completion) {
5050                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5051                        .await
5052                        .map_err(|_| Error::Timeout)?,
5053                    None => receive.await,
5054                }
5055            };
5056            let (status, bytes) = match self
5057                .activity_lease_authority
5058                .as_ref()
5059                .filter(|authority| authority.governs(path))
5060            {
5061                Some(authority) => authority.protect(received).await?,
5062                None => received.await?,
5063            };
5064
5065            if !status.is_success() {
5066                let body = String::from_utf8_lossy(&bytes).to_string();
5067                if let Some(protocol) = protocol_failure(status, &body) {
5068                    return Err(Error::Protocol(protocol));
5069                }
5070                let error = Error::Http { status, body };
5071                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5072                    &error,
5073                    path,
5074                    request_body.as_ref(),
5075                )
5076                .is_some();
5077                if self
5078                    .wait_for_storage_admission(
5079                        &error,
5080                        protocol,
5081                        Some(path),
5082                        poll_request_id.as_deref(),
5083                        request_body.as_ref(),
5084                        &mut storage_retries,
5085                    )
5086                    .await
5087                {
5088                    continue;
5089                }
5090                return Err(error);
5091            }
5092
5093            if bytes.is_empty() {
5094                return Ok(serde_json::from_value(Value::Null)?);
5095            }
5096
5097            #[cfg(feature = "telemetry")]
5098            return self.decode_observability_response(
5099                &method,
5100                path,
5101                request_body.as_ref(),
5102                &bytes,
5103            );
5104
5105            #[cfg(not(feature = "telemetry"))]
5106            return Ok(serde_json::from_slice(&bytes)?);
5107        }
5108    }
5109
5110    #[cfg(feature = "telemetry")]
5111    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5112        if *method == reqwest::Method::GET && path == "/cluster/info" {
5113            self.observability_context_supported
5114                .store(false, Ordering::SeqCst);
5115        }
5116    }
5117
5118    #[cfg(feature = "telemetry")]
5119    fn decode_observability_response<T: DeserializeOwned>(
5120        &self,
5121        method: &reqwest::Method,
5122        path: &str,
5123        request_body: Option<&Value>,
5124        bytes: &[u8],
5125    ) -> Result<T> {
5126        if *method == reqwest::Method::POST
5127            && self.execution_telemetry.is_some()
5128            && matches!(
5129                path,
5130                "/worker/workflow-tasks/poll"
5131                    | "/worker/activity-tasks/poll"
5132                    | "/worker/query-tasks/poll"
5133            )
5134        {
5135            let mut wire: Value = serde_json::from_slice(bytes)?;
5136            telemetry::carrier::retain_poll_observations(
5137                &mut wire,
5138                request_body.unwrap_or(&Value::Null),
5139                path,
5140                &self.namespace,
5141            );
5142            return Ok(serde_json::from_value(wire)?);
5143        }
5144        if *method == reqwest::Method::GET && path == "/cluster/info" {
5145            let info: Value = serde_json::from_slice(bytes)?;
5146            self.observability_context_supported
5147                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5148            return Ok(serde_json::from_value(info)?);
5149        }
5150        Ok(serde_json::from_slice(bytes)?)
5151    }
5152
5153    async fn wait_for_storage_admission(
5154        &self,
5155        error: &Error,
5156        protocol: RequestProtocol,
5157        path: Option<&str>,
5158        poll_request_id: Option<&str>,
5159        request_body: Option<&Value>,
5160        retries: &mut usize,
5161    ) -> bool {
5162        let Some(admission) = self
5163            .worker_storage_admission
5164            .as_ref()
5165            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5166        else {
5167            return false;
5168        };
5169        let completion_deferred = path.and_then(|path| {
5170            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5171        });
5172        let Some(advertised_delay) = completion_deferred
5173            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5174            .or_else(|| {
5175                path.and_then(|path| {
5176                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5177                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5178                })
5179            })
5180        else {
5181            return false;
5182        };
5183        *retries = retries.saturating_add(1);
5184        let delay = worker_retry_delay(admission.policy, *retries)
5185            .max(advertised_delay)
5186            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
5187        let delay = if completion_deferred.is_some() {
5188            delay.max(advertised_delay)
5189        } else {
5190            delay
5191        };
5192        let wait_deadline = tokio::time::Instant::now() + delay;
5193        loop {
5194            if admission.stop.load(Ordering::SeqCst) {
5195                return false;
5196            }
5197            let now = tokio::time::Instant::now();
5198            if admission
5199                .workflow_completion_retry_deadline
5200                .is_some_and(|deadline| now >= deadline)
5201            {
5202                return false;
5203            }
5204            let remaining = wait_deadline.saturating_duration_since(now);
5205            if remaining.is_zero() {
5206                return true;
5207            }
5208            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
5209        }
5210    }
5211
5212    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5213        &self,
5214        path: &str,
5215        protocol: RequestProtocol,
5216        body: &B,
5217        timeout: Duration,
5218        max_retries: usize,
5219    ) -> Result<T> {
5220        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
5221            .await
5222    }
5223
5224    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
5225        &self,
5226        path: &str,
5227        protocol: RequestProtocol,
5228        body: &B,
5229        timeout: Duration,
5230        max_retries: usize,
5231    ) -> Result<T> {
5232        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
5233            .await
5234    }
5235
5236    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
5237        &self,
5238        path: &str,
5239        protocol: RequestProtocol,
5240        body: &B,
5241        timeout: Duration,
5242        max_retries: usize,
5243        resolve: bool,
5244    ) -> Result<T> {
5245        let mut retries = 0;
5246
5247        loop {
5248            let response = if resolve {
5249                self.request_json_with_timeout(
5250                    reqwest::Method::POST,
5251                    path,
5252                    protocol,
5253                    Some(body),
5254                    timeout,
5255                )
5256                .await
5257            } else {
5258                self.request_json_unresolved_with_timeout(
5259                    reqwest::Method::POST,
5260                    path,
5261                    protocol,
5262                    Some(body),
5263                    timeout,
5264                )
5265                .await
5266            };
5267
5268            match response {
5269                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
5270                response => return worker_poll_response(response),
5271            }
5272        }
5273    }
5274
5275    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
5276        match protocol {
5277            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5278                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
5279                    return Ok(Some(token));
5280                }
5281                if self.control_token.is_some() {
5282                    return Err(Error::MissingRoleCredentials {
5283                        role: "worker",
5284                        opposite_role: "control",
5285                    });
5286                }
5287                Ok(None)
5288            }
5289            RequestProtocol::ControlPlane => {
5290                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
5291                    return Ok(Some(token));
5292                }
5293                if self.worker_token.is_some() {
5294                    return Err(Error::MissingRoleCredentials {
5295                        role: "control",
5296                        opposite_role: "worker",
5297                    });
5298                }
5299                Ok(None)
5300            }
5301        }
5302    }
5303}
5304
5305fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
5306    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5307    let reason = body
5308        .get("reason")
5309        .and_then(Value::as_str)
5310        .unwrap_or("query_rejected")
5311        .to_string();
5312    let message = body
5313        .get("message")
5314        .or_else(|| body.get("error"))
5315        .and_then(Value::as_str)
5316        .unwrap_or("workflow query was rejected")
5317        .to_string();
5318
5319    QueryFailure {
5320        status: status.as_u16(),
5321        reason,
5322        message,
5323        body,
5324    }
5325}
5326
5327fn workflow_command_result(
5328    command: WorkflowCommandKind,
5329    data: Value,
5330    workflow_id: &str,
5331    run_id: Option<&str>,
5332) -> WorkflowCommandResult {
5333    WorkflowCommandResult {
5334        command,
5335        workflow_id: data
5336            .get("workflow_id")
5337            .and_then(Value::as_str)
5338            .unwrap_or(workflow_id)
5339            .to_string(),
5340        run_id: data
5341            .get("run_id")
5342            .and_then(Value::as_str)
5343            .or(run_id)
5344            .map(str::to_string),
5345        outcome: data
5346            .get("outcome")
5347            .and_then(Value::as_str)
5348            .map(str::to_string),
5349        reason: data
5350            .get("reason")
5351            .and_then(Value::as_str)
5352            .map(str::to_string),
5353        command_status: data
5354            .get("command_status")
5355            .and_then(Value::as_str)
5356            .map(str::to_string),
5357        raw: data,
5358    }
5359}
5360
5361fn workflow_command_rejection(
5362    command: WorkflowCommandKind,
5363    status: reqwest::StatusCode,
5364    raw_body: String,
5365    workflow_id: &str,
5366    run_id: Option<&str>,
5367) -> WorkflowCommandRejection {
5368    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5369    WorkflowCommandRejection {
5370        command,
5371        status: status.as_u16(),
5372        reason: body
5373            .get("reason")
5374            .and_then(Value::as_str)
5375            .unwrap_or("workflow_command_rejected")
5376            .to_string(),
5377        message: body
5378            .get("message")
5379            .or_else(|| body.get("error"))
5380            .and_then(Value::as_str)
5381            .unwrap_or("workflow lifecycle command was rejected")
5382            .to_string(),
5383        workflow_id: body
5384            .get("workflow_id")
5385            .and_then(Value::as_str)
5386            .unwrap_or(workflow_id)
5387            .to_string(),
5388        run_id: body
5389            .get("run_id")
5390            .and_then(Value::as_str)
5391            .or(run_id)
5392            .map(str::to_string),
5393        target_scope: body
5394            .get("target_scope")
5395            .and_then(Value::as_str)
5396            .map(str::to_string),
5397        body,
5398    }
5399}
5400
5401fn query_task_response(response: Result<Value>) -> Result<Value> {
5402    match response {
5403        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
5404        response => response,
5405    }
5406}
5407
5408fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
5409    match response {
5410        Err(Error::Http { status, body })
5411            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5412        {
5413            Ok(serde_json::from_str(&body)?)
5414        }
5415        response => response,
5416    }
5417}
5418
5419fn worker_poll_body_is_stop(body: &str) -> bool {
5420    serde_json::from_str::<Value>(body)
5421        .ok()
5422        .is_some_and(|body| {
5423            worker_poll_is_stop(
5424                body.get("poll_status").and_then(Value::as_str),
5425                body.get("reason").and_then(Value::as_str),
5426            )
5427        })
5428}
5429
5430fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5431    matches!(poll_status, Some("draining" | "stopped"))
5432        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5433}
5434
5435fn query_task_rejection_is_final(error: &Error) -> bool {
5436    matches!(
5437        error,
5438        Error::QueryFailed(failure)
5439            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5440    )
5441}
5442
5443fn activity_task_response<T>(
5444    response: Result<T>,
5445    operation: &str,
5446    task_id: &str,
5447    activity_attempt_id: &str,
5448) -> Result<T> {
5449    match response {
5450        Err(Error::Http { status, body }) => {
5451            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5452            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5453                operation: operation.to_string(),
5454                status: status.as_u16(),
5455                reason: body
5456                    .get("reason")
5457                    .and_then(Value::as_str)
5458                    .unwrap_or("activity_task_rejected")
5459                    .to_string(),
5460                task_id: body
5461                    .get("task_id")
5462                    .and_then(Value::as_str)
5463                    .unwrap_or(task_id)
5464                    .to_string(),
5465                activity_attempt_id: body
5466                    .get("activity_attempt_id")
5467                    .and_then(Value::as_str)
5468                    .unwrap_or(activity_attempt_id)
5469                    .to_string(),
5470                cancel_requested: body
5471                    .get("cancel_requested")
5472                    .and_then(Value::as_bool)
5473                    .unwrap_or(false),
5474                can_continue: body.get("can_continue").and_then(Value::as_bool),
5475                run_closed_reason: body
5476                    .get("run_closed_reason")
5477                    .and_then(Value::as_str)
5478                    .map(str::to_string),
5479                body,
5480            }))
5481        }
5482        response => response,
5483    }
5484}
5485
5486fn activity_task_rejection_is_final(error: &Error) -> bool {
5487    matches!(
5488        error,
5489        Error::ActivityTaskRejected(rejection)
5490            if matches!(
5491                rejection.reason.as_str(),
5492                "run_cancelled"
5493                    | "run_terminated"
5494                    | "attempt_closed"
5495                    | "stale_attempt"
5496                    | "activity_cancelled"
5497                    | "task_cancelled"
5498                    | "run_closed"
5499                    | "activity_not_running"
5500                    | "attempt_not_found"
5501            )
5502    )
5503}
5504
5505fn workflow_task_completion_is_terminal_timeout(
5506    error: &Error,
5507    task_id: &str,
5508    workflow_task_attempt: u64,
5509    run_id: Option<&str>,
5510) -> bool {
5511    let Error::Http { status, body } = error else {
5512        return false;
5513    };
5514    if *status != reqwest::StatusCode::CONFLICT {
5515        return false;
5516    }
5517
5518    let Some(run_id) = run_id else {
5519        return false;
5520    };
5521    let Ok(body) = serde_json::from_str::<Value>(body) else {
5522        return false;
5523    };
5524
5525    body.get("recorded").and_then(Value::as_bool) == Some(false)
5526        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5527        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5528        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5529        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5530        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5531}
5532
5533fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5534    let body: Value = serde_json::from_str(raw_body).ok()?;
5535    let reason = body.get("reason")?.as_str()?;
5536    if !matches!(
5537        reason,
5538        "missing_protocol_version"
5539            | "unsupported_protocol_version"
5540            | "missing_control_plane_version"
5541            | "unsupported_control_plane_version"
5542    ) {
5543        return None;
5544    }
5545
5546    Some(ProtocolFailure {
5547        status: status.as_u16(),
5548        reason: reason.to_string(),
5549        message: body
5550            .get("message")
5551            .or_else(|| body.get("error"))
5552            .and_then(Value::as_str)
5553            .unwrap_or("protocol version rejected")
5554            .to_string(),
5555        supported_version: body
5556            .get("supported_version")
5557            .and_then(Value::as_str)
5558            .map(str::to_string),
5559        requested_version: body
5560            .get("requested_version")
5561            .and_then(Value::as_str)
5562            .map(str::to_string),
5563        body,
5564    })
5565}
5566
5567fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5568    timeout
5569        .as_secs()
5570        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5571        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5572}
5573
5574fn worker_operation_is_retryable(error: &Error) -> bool {
5575    if worker_poll_capacity_retry_after(error).is_some()
5576        || worker_storage_admission_body(error).is_some()
5577        || worker_backend_unavailable_body(error).is_some()
5578        || worker_operation_is_explicitly_non_retryable(error)
5579    {
5580        return false;
5581    }
5582
5583    match error {
5584        Error::Transport(error) => {
5585            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5586        }
5587        Error::Http { status, .. } => {
5588            matches!(
5589                *status,
5590                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5591            ) || status.is_server_error()
5592        }
5593        _ => false,
5594    }
5595}
5596
5597fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5598    let body: Value = match error {
5599        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5600        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5601        _ => return None,
5602    };
5603    matches!(
5604        body.get("reason").and_then(Value::as_str),
5605        Some("storage_pressure" | "storage_admission_unavailable")
5606    )
5607    .then_some(body)
5608}
5609
5610fn worker_storage_admission_retry_after(
5611    error: &Error,
5612    poll_request_id: Option<&str>,
5613) -> Option<Duration> {
5614    let Error::Http { status, .. } = error else {
5615        return None;
5616    };
5617    let body = worker_storage_admission_body(error)?;
5618    let delay = body.get("retry_after_seconds")?.as_u64()?;
5619    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5620        || delay == 0
5621        || body.get("retryable") != Some(&Value::Bool(true))
5622        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5623        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5624        || body
5625            .get("request_admitted")
5626            .is_some_and(|admitted| admitted != &Value::Bool(false))
5627    {
5628        return None;
5629    }
5630    match poll_request_id {
5631        Some(id) => {
5632            if id.is_empty()
5633                || body.get("task") != Some(&Value::Null)
5634                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5635                || body.get("poll_status") != body.get("reason")
5636                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5637                || body.get("claim_admitted") != Some(&Value::Bool(false))
5638            {
5639                return None;
5640            }
5641        }
5642        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5643        None => {}
5644    }
5645    Some(Duration::from_secs(delay))
5646}
5647
5648fn worker_backend_unavailable_retry_after(
5649    error: &Error,
5650    path: &str,
5651    poll_request_id: Option<&str>,
5652) -> Option<Duration> {
5653    let operation = match path {
5654        "/worker/register" => "register_worker",
5655        "/worker/heartbeat" => "heartbeat_worker",
5656        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5657        "/worker/activity-tasks/poll" => "poll_activity_task",
5658        "/worker/query-tasks/poll" => "poll_query_task",
5659        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5660        _ => return None,
5661    };
5662    let body = worker_backend_unavailable_body(error)?;
5663    let delay = body.get("retry_after_seconds")?.as_u64()?;
5664    if delay == 0
5665        || body.get("operation")?.as_str()? != operation
5666        || body.get("outcome")?.as_str()? != "unknown"
5667        || body.get("retryable") != Some(&Value::Bool(true))
5668        || body.get("worker_id")?.as_str()?.is_empty()
5669    {
5670        return None;
5671    }
5672    if let Some(id) = poll_request_id {
5673        if id.is_empty()
5674            || body.get("task") != Some(&Value::Null)
5675            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5676            || body.get("poll_request_id")?.as_str()? != id
5677            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5678        {
5679            return None;
5680        }
5681    } else if path.ends_with("/poll") {
5682        return None;
5683    }
5684    Some(Duration::from_secs(delay))
5685}
5686
5687fn worker_fenced_completion_retry_after(
5688    error: &Error,
5689    path: &str,
5690    request_body: Option<&Value>,
5691) -> Option<Duration> {
5692    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5693        .strip_prefix("/worker/workflow-tasks/")
5694        .and_then(|tail| tail.strip_suffix("/complete"))
5695    {
5696        ("complete_workflow_task", task_id, "workflow_task_attempt")
5697    } else if let Some(task_id) = path
5698        .strip_prefix("/worker/activity-tasks/")
5699        .and_then(|tail| tail.strip_suffix("/complete"))
5700    {
5701        ("complete_activity_task", task_id, "activity_attempt_id")
5702    } else {
5703        return None;
5704    };
5705    if task_id.is_empty() || task_id.contains('/') {
5706        return None;
5707    }
5708
5709    let request = request_body?.as_object()?;
5710    let lease_owner = request.get("lease_owner")?.as_str()?;
5711    if lease_owner.is_empty() {
5712        return None;
5713    }
5714    let attempt = request.get(attempt_field)?;
5715    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5716        || (attempt_field == "activity_attempt_id"
5717            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5718    {
5719        return None;
5720    }
5721
5722    let body = worker_backend_unavailable_body(error)?;
5723    let delay = body.get("retry_after_seconds")?.as_u64()?;
5724    if delay == 0
5725        || body.get("operation")?.as_str()? != operation
5726        || body.get("outcome")?.as_str()? != "unknown"
5727        || body.get("retryable") != Some(&Value::Bool(true))
5728        || body.get("worker_id")?.as_str()? != lease_owner
5729        || body.get("task_queue") != Some(&Value::Null)
5730        || body.get("task_id")?.as_str()? != task_id
5731        || body.get("lease_owner")?.as_str()? != lease_owner
5732        || body.get(attempt_field) != Some(attempt)
5733    {
5734        return None;
5735    }
5736
5737    Some(Duration::from_secs(delay))
5738}
5739
5740fn worker_deferred_workflow_completion_retry_after(
5741    error: &Error,
5742    path: &str,
5743    request_body: Option<&Value>,
5744) -> Option<Duration> {
5745    let task_id = path
5746        .strip_prefix("/worker/workflow-tasks/")?
5747        .strip_suffix("/complete")?;
5748    if task_id.is_empty() || task_id.contains('/') {
5749        return None;
5750    }
5751    let request = request_body?.as_object()?;
5752    let owner = request.get("lease_owner")?.as_str()?;
5753    let attempt = request.get("workflow_task_attempt")?;
5754    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5755        return None;
5756    }
5757    let Error::Http { status, body } = error else {
5758        return None;
5759    };
5760    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5761        return None;
5762    }
5763    let body: Value = serde_json::from_str(body).ok()?;
5764    let delay = body.get("retry_after_seconds")?.as_u64()?;
5765    if !(1..=5).contains(&delay)
5766        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5767        || body.get("operation")?.as_str()? != "complete_workflow_task"
5768        || body.get("outcome")?.as_str()? != "deferred"
5769        || body.get("recorded") != Some(&Value::Bool(false))
5770        || body.get("retryable") != Some(&Value::Bool(true))
5771        || body.get("task_id")?.as_str()? != task_id
5772        || body.get("lease_owner")?.as_str()? != owner
5773        || body.get("workflow_task_attempt") != Some(attempt)
5774        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5775    {
5776        return None;
5777    }
5778    Some(Duration::from_secs(delay))
5779}
5780
5781fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5782    let Error::Http { status, body } = error else {
5783        return None;
5784    };
5785    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5786        return None;
5787    }
5788    let body: Value = serde_json::from_str(body).ok()?;
5789    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5790}
5791
5792fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5793    let Error::Http { body, .. } = error else {
5794        return false;
5795    };
5796
5797    serde_json::from_str::<Value>(body)
5798        .ok()
5799        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5800        == Some(false)
5801}
5802
5803fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5804    let Error::Http { status, body } = error else {
5805        return None;
5806    };
5807    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5808        return None;
5809    }
5810
5811    let body = serde_json::from_str::<Value>(body).ok()?;
5812    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5813        == Some("long_poll_capacity_exhausted")
5814        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5815    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5816        return None;
5817    }
5818
5819    Some(Duration::from_secs(
5820        body.get("retry_after_seconds")
5821            .and_then(Value::as_u64)
5822            .unwrap_or_default(),
5823    ))
5824}
5825
5826fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5827    let exponent = retry.saturating_sub(1).min(31) as u32;
5828    policy
5829        .initial_backoff
5830        .saturating_mul(1_u32 << exponent)
5831        .min(policy.max_backoff)
5832}
5833
5834#[derive(Debug)]
5835pub struct ClientBuilder {
5836    base_url: String,
5837    token: Option<String>,
5838    control_token: Option<String>,
5839    worker_token: Option<String>,
5840    namespace: String,
5841    timeout: Duration,
5842    max_external_payload_bytes: usize,
5843    worker_protocol_version: WorkerProtocolVersion,
5844}
5845
5846impl ClientBuilder {
5847    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5848    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5849        self.worker_protocol_version = version;
5850        self
5851    }
5852
5853    pub fn token(mut self, token: Option<String>) -> Self {
5854        self.token = token;
5855        self
5856    }
5857
5858    pub fn control_token(mut self, token: Option<String>) -> Self {
5859        self.control_token = token;
5860        self
5861    }
5862
5863    pub fn worker_token(mut self, token: Option<String>) -> Self {
5864        self.worker_token = token;
5865        self
5866    }
5867
5868    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5869        self.namespace = namespace.into();
5870        self
5871    }
5872
5873    pub fn timeout(mut self, timeout: Duration) -> Self {
5874        self.timeout = timeout;
5875        self
5876    }
5877
5878    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5879    /// References are fetched only from this client's authenticated runtime.
5880    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5881        self.max_external_payload_bytes = bytes;
5882        self
5883    }
5884
5885    pub fn build(self) -> Result<Client> {
5886        let base_url = self.base_url.trim_end_matches('/').to_string();
5887        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5888            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5889            .unwrap_or_else(|_| base_url.ends_with("/api"));
5890
5891        if has_sdk_api_suffix {
5892            return Err(Error::InvalidBaseUrl);
5893        }
5894
5895        Ok(Client {
5896            http: reqwest::Client::builder()
5897                .timeout(self.timeout)
5898                .redirect(reqwest::redirect::Policy::none())
5899                .build()?,
5900            hydration_timeout: self.timeout,
5901            base_url,
5902            token: self.token,
5903            control_token: self.control_token,
5904            worker_token: self.worker_token,
5905            namespace: self.namespace,
5906            max_external_payload_bytes: self.max_external_payload_bytes,
5907            worker_storage_admission: None,
5908            cooperative_worker_protocol: false,
5909            worker_protocol_version: self.worker_protocol_version,
5910            local_activities_enabled: false,
5911            worker_sessions_enabled: false,
5912            max_concurrent_worker_sessions: 10,
5913            worker_build_id: None,
5914            sticky_cache: None,
5915            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5916            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
5917            activity_lease_authority: None,
5918            #[cfg(feature = "telemetry")]
5919            execution_telemetry: None,
5920            #[cfg(feature = "telemetry")]
5921            observability_context_supported: Arc::new(AtomicBool::new(false)),
5922        })
5923    }
5924}
5925
5926#[derive(Clone, Debug)]
5927pub struct WorkflowHandle {
5928    client: Client,
5929    pub workflow_id: String,
5930    pub run_id: Option<String>,
5931    pub workflow_type: String,
5932}
5933
5934impl WorkflowHandle {
5935    /// Describe whichever run is current for this stable workflow instance.
5936    pub async fn describe(&self) -> Result<WorkflowDescription> {
5937        self.client.describe_workflow(&self.workflow_id).await
5938    }
5939
5940    /// Describe the run identity originally selected by this handle.
5941    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5942        let run_id = self.run_id.as_deref().ok_or_else(|| {
5943            Error::Codec("run_id is required for selected-run description".to_string())
5944        })?;
5945        self.client
5946            .describe_workflow_run(&self.workflow_id, run_id)
5947            .await
5948    }
5949
5950    /// Signal this workflow with an SDK-generated caller command key.
5951    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5952        self.client
5953            .signal_workflow(&self.workflow_id, signal_name, input)
5954            .await
5955    }
5956
5957    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
5958    pub async fn signal_with_request_id<T: Serialize>(
5959        &self,
5960        signal_name: &str,
5961        input: T,
5962        request_id: &str,
5963    ) -> Result<Value> {
5964        self.client
5965            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
5966            .await
5967    }
5968
5969    pub async fn append_message<T: Serialize>(
5970        &self,
5971        stream_name: &str,
5972        message_id: &str,
5973        input: T,
5974    ) -> Result<Value> {
5975        self.client
5976            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5977            .await
5978    }
5979
5980    /// Signal only if this handle's selected run is still current, with an
5981    /// SDK-generated caller command key.
5982    pub async fn signal_selected_run<T: Serialize>(
5983        &self,
5984        signal_name: &str,
5985        input: T,
5986    ) -> Result<Value> {
5987        let run_id = self.run_id.as_deref().ok_or_else(|| {
5988            Error::Codec("run_id is required for selected-run signaling".to_string())
5989        })?;
5990        self.client
5991            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5992            .await
5993    }
5994
5995    /// Signal only if this handle's selected run is still current, with an
5996    /// explicit caller command key (1 to 255 Unicode characters).
5997    pub async fn signal_selected_run_with_request_id<T: Serialize>(
5998        &self,
5999        signal_name: &str,
6000        input: T,
6001        request_id: &str,
6002    ) -> Result<Value> {
6003        let run_id = self.run_id.as_deref().ok_or_else(|| {
6004            Error::Codec("run_id is required for selected-run signaling".to_string())
6005        })?;
6006        self.client
6007            .signal_workflow_run_with_request_id(
6008                &self.workflow_id,
6009                run_id,
6010                signal_name,
6011                input,
6012                request_id,
6013            )
6014            .await
6015    }
6016
6017    /// Close whichever run is current as cancelled, without workflow cleanup.
6018    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
6019        self.client
6020            .cancel_workflow(&self.workflow_id, options)
6021            .await
6022    }
6023
6024    /// Request cancellation only if this handle's selected run is still current.
6025    pub async fn cancel_selected_run(
6026        &self,
6027        options: WorkflowCommandOptions,
6028    ) -> Result<WorkflowCommandResult> {
6029        let run_id = self.run_id.as_deref().ok_or_else(|| {
6030            Error::Codec("run_id is required for selected-run cancellation".to_string())
6031        })?;
6032        self.client
6033            .cancel_workflow_run(&self.workflow_id, run_id, options)
6034            .await
6035    }
6036
6037    /// Forcefully terminate whichever run is current.
6038    pub async fn terminate(
6039        &self,
6040        options: WorkflowCommandOptions,
6041    ) -> Result<WorkflowCommandResult> {
6042        self.client
6043            .terminate_workflow(&self.workflow_id, options)
6044            .await
6045    }
6046
6047    /// Terminate only if this handle's selected run is still current.
6048    pub async fn terminate_selected_run(
6049        &self,
6050        options: WorkflowCommandOptions,
6051    ) -> Result<WorkflowCommandResult> {
6052        let run_id = self.run_id.as_deref().ok_or_else(|| {
6053            Error::Codec("run_id is required for selected-run termination".to_string())
6054        })?;
6055        self.client
6056            .terminate_workflow_run(&self.workflow_id, run_id, options)
6057            .await
6058    }
6059
6060    /// Continue this handle's failed run without repeating completed activities.
6061    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
6062        let run_id = self
6063            .run_id
6064            .as_deref()
6065            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
6066        self.client
6067            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
6068            .await
6069    }
6070
6071    /// Execute a named, read-only query against this workflow.
6072    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
6073        self.client
6074            .query_workflow(&self.workflow_id, query_name, input)
6075            .await
6076    }
6077
6078    pub async fn query_avro_value<T: Serialize>(
6079        &self,
6080        query_name: &str,
6081        input: T,
6082    ) -> Result<AvroValue> {
6083        self.client
6084            .query_workflow_avro_value(&self.workflow_id, query_name, input)
6085            .await
6086    }
6087
6088    pub async fn update<T: Serialize>(
6089        &self,
6090        update_name: &str,
6091        input: T,
6092        request_id: Option<&str>,
6093    ) -> Result<Value> {
6094        self.client
6095            .update_workflow(&self.workflow_id, update_name, input, request_id)
6096            .await
6097    }
6098
6099    pub async fn update_avro_value<T: Serialize>(
6100        &self,
6101        update_name: &str,
6102        input: T,
6103        request_id: Option<&str>,
6104    ) -> Result<AvroValue> {
6105        self.client
6106            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
6107            .await
6108    }
6109
6110    /// Query only if this handle's selected run is still current.
6111    pub async fn query_selected_run<T: Serialize>(
6112        &self,
6113        query_name: &str,
6114        input: T,
6115    ) -> Result<Value> {
6116        let run_id = self
6117            .run_id
6118            .as_deref()
6119            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
6120        self.client
6121            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
6122            .await
6123    }
6124
6125    /// Await the final terminal outcome of the current continue-as-new chain.
6126    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
6127        self.result_target(options, None).await
6128    }
6129
6130    /// Await the final result without projecting Avro bytes through JSON.
6131    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
6132        self.result_avro_value_target(options, None).await
6133    }
6134
6135    /// Await the final result and decode it into a Serde application type.
6136    pub async fn result_typed<T: DeserializeOwned>(
6137        &self,
6138        options: WorkflowResultOptions,
6139    ) -> Result<T> {
6140        let result = self.result_avro_value(options).await?;
6141        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6142    }
6143
6144    /// Await only the run identity originally selected by this handle.
6145    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
6146        let run_id = self.run_id.as_deref().ok_or_else(|| {
6147            Error::Codec("run_id is required for selected-run result".to_string())
6148        })?;
6149        self.result_target(options, Some(run_id)).await
6150    }
6151
6152    /// Await the selected run's result on the lossless Avro Value surface.
6153    pub async fn result_selected_run_avro_value(
6154        &self,
6155        options: WorkflowResultOptions,
6156    ) -> Result<AvroValue> {
6157        let run_id = self.run_id.as_deref().ok_or_else(|| {
6158            Error::Codec("run_id is required for selected-run result".to_string())
6159        })?;
6160        self.result_avro_value_target(options, Some(run_id)).await
6161    }
6162
6163    /// Await the selected run and decode its result into a Serde type.
6164    pub async fn result_selected_run_typed<T: DeserializeOwned>(
6165        &self,
6166        options: WorkflowResultOptions,
6167    ) -> Result<T> {
6168        let result = self.result_selected_run_avro_value(options).await?;
6169        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6170    }
6171
6172    async fn result_avro_value_target(
6173        &self,
6174        options: WorkflowResultOptions,
6175        selected_run_id: Option<&str>,
6176    ) -> Result<AvroValue> {
6177        let started = Instant::now();
6178
6179        loop {
6180            let description = match selected_run_id {
6181                Some(run_id) => {
6182                    self.client
6183                        .describe_workflow_run(&self.workflow_id, run_id)
6184                        .await?
6185                }
6186                None => self.describe().await?,
6187            };
6188            if description.is_completed() {
6189                return description.output_avro_value.ok_or_else(|| {
6190                    Error::Codec(
6191                        "missing_payload_envelope: typed workflow result requires output_envelope"
6192                            .to_string(),
6193                    )
6194                });
6195            }
6196            if description.is_terminal() {
6197                let outcome =
6198                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6199                return Err(match outcome.kind {
6200                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6201                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6202                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6203                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6204                });
6205            }
6206            if started.elapsed() >= options.timeout {
6207                return Err(Error::Timeout);
6208            }
6209            tokio::time::sleep(options.poll_interval).await;
6210        }
6211    }
6212
6213    async fn result_target(
6214        &self,
6215        options: WorkflowResultOptions,
6216        selected_run_id: Option<&str>,
6217    ) -> Result<Value> {
6218        let started = Instant::now();
6219
6220        loop {
6221            let description = match selected_run_id {
6222                Some(run_id) => {
6223                    self.client
6224                        .describe_workflow_run(&self.workflow_id, run_id)
6225                        .await?
6226                }
6227                None => self.describe().await?,
6228            };
6229            if description.is_completed() {
6230                return Ok(description.output.unwrap_or(Value::Null));
6231            }
6232
6233            if description.is_terminal() {
6234                let outcome =
6235                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6236                return Err(match outcome.kind {
6237                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6238                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6239                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6240                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6241                });
6242            }
6243
6244            if started.elapsed() >= options.timeout {
6245                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
6246                    kind: WorkflowTerminalKind::TimedOut,
6247                    workflow_id: description
6248                        .workflow_id
6249                        .clone()
6250                        .unwrap_or_else(|| self.workflow_id.clone()),
6251                    run_id: description
6252                        .run_id
6253                        .clone()
6254                        .or_else(|| selected_run_id.map(str::to_string)),
6255                    reason: "result_wait_timeout".to_string(),
6256                    failure_category: Some("client_timeout".to_string()),
6257                    failure_id: None,
6258                    exception_type: None,
6259                    exception_class: None,
6260                    non_retryable: None,
6261                    message: Some(format!(
6262                        "workflow result was not terminal within {:?}",
6263                        options.timeout
6264                    )),
6265                    exception: None,
6266                    raw: description.raw_value(),
6267                }));
6268            }
6269
6270            tokio::time::sleep(options.poll_interval).await;
6271        }
6272    }
6273}
6274
6275#[derive(Clone, Copy, Debug)]
6276pub struct WorkflowResultOptions {
6277    pub poll_interval: Duration,
6278    pub timeout: Duration,
6279}
6280
6281impl Default for WorkflowResultOptions {
6282    fn default() -> Self {
6283        Self {
6284            poll_interval: Duration::from_millis(500),
6285            timeout: Duration::from_secs(30),
6286        }
6287    }
6288}
6289
6290#[derive(Clone, Debug, Deserialize)]
6291pub struct WorkflowDescription {
6292    pub workflow_id: Option<String>,
6293    pub run_id: Option<String>,
6294    pub workflow_type: Option<String>,
6295    pub status: Option<String>,
6296    #[serde(default)]
6297    pub closed_reason: Option<String>,
6298    #[serde(default)]
6299    pub error: Option<String>,
6300    #[serde(default)]
6301    pub failure: Option<Value>,
6302    #[serde(default)]
6303    pub exception: Option<Value>,
6304    #[serde(default)]
6305    pub failures: Vec<Value>,
6306    #[serde(default)]
6307    pub output: Option<Value>,
6308    #[serde(default)]
6309    pub output_envelope: Option<Value>,
6310    #[serde(skip)]
6311    pub output_avro_value: Option<AvroValue>,
6312    #[serde(flatten)]
6313    pub raw: HashMap<String, Value>,
6314}
6315
6316/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
6317#[derive(Clone, Debug, Deserialize)]
6318pub struct WorkflowStreamDescription {
6319    pub stream_name: String,
6320    pub status: String,
6321    pub last_offset: i64,
6322    pub total_items: u64,
6323    pub pending_items: u64,
6324    #[serde(default)]
6325    pub opened_at: Option<String>,
6326    #[serde(default)]
6327    pub last_appended_at: Option<String>,
6328    #[serde(default)]
6329    pub closed_at: Option<String>,
6330    #[serde(default)]
6331    pub error_reason: Option<String>,
6332    #[serde(default)]
6333    pub retention_seconds: Option<u64>,
6334    #[serde(flatten)]
6335    pub raw: HashMap<String, Value>,
6336}
6337
6338impl WorkflowStreamDescription {
6339    pub fn is_terminal(&self) -> bool {
6340        matches!(self.status.as_str(), "closed" | "errored")
6341    }
6342}
6343
6344/// One item for direct or replay-safe append.
6345#[derive(Clone, Debug, Default)]
6346pub struct WorkflowStreamAppendItem {
6347    pub payload_envelope: Option<Value>,
6348    pub payload_reference: Option<String>,
6349    pub item_type: Option<String>,
6350    pub content_type: Option<String>,
6351    pub idempotency_key: Option<String>,
6352}
6353
6354impl WorkflowStreamAppendItem {
6355    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
6356    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
6357        let value = AvroValue::from_serialize(&payload)?;
6358        Ok(Self {
6359            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
6360            ..Self::default()
6361        })
6362    }
6363
6364    /// Preserve an external payload URI as an opaque service-contract reference.
6365    pub fn from_reference(reference: impl Into<String>) -> Self {
6366        Self {
6367            payload_reference: Some(reference.into()),
6368            ..Self::default()
6369        }
6370    }
6371
6372    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
6373        self.item_type = Some(item_type.into());
6374        self
6375    }
6376
6377    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
6378        self.content_type = Some(content_type.into());
6379        self
6380    }
6381
6382    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
6383        self.idempotency_key = Some(idempotency_key.into());
6384        self
6385    }
6386
6387    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
6388        let mut item = serde_json::Map::new();
6389        if let Some(payload) = &self.payload_envelope {
6390            item.insert("payload".to_string(), payload.clone());
6391            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
6392        }
6393        if let Some(reference) = &self.payload_reference {
6394            item.insert("payload_reference".to_string(), json!(reference));
6395        }
6396        if let Some(item_type) = &self.item_type {
6397            item.insert("item_type".to_string(), json!(item_type));
6398        }
6399        if let Some(content_type) = &self.content_type {
6400            item.insert("content_type".to_string(), json!(content_type));
6401        }
6402        if let Some(key) = derived_idempotency_key
6403            .as_ref()
6404            .or(self.idempotency_key.as_ref())
6405        {
6406            item.insert("idempotency_key".to_string(), json!(key));
6407        }
6408        Value::Object(item)
6409    }
6410}
6411
6412/// One durable item at its stable zero-based offset.
6413#[derive(Clone, Debug)]
6414pub struct WorkflowStreamItem {
6415    pub offset: u64,
6416    pub payload: Option<Value>,
6417    pub payload_envelope: Option<Value>,
6418    pub payload_reference: Option<String>,
6419    pub payload_codec: Option<String>,
6420    pub idempotency_key: Option<String>,
6421    pub item_type: Option<String>,
6422    pub content_type: Option<String>,
6423    pub origin: Option<String>,
6424    pub origin_reference: Option<String>,
6425    pub emitted_at: Option<String>,
6426    pub raw: Value,
6427}
6428
6429/// One bounded at-least-once subscription page.
6430#[derive(Clone, Debug)]
6431pub struct WorkflowStreamPage {
6432    pub stream: WorkflowStreamDescription,
6433    pub items: Vec<WorkflowStreamItem>,
6434    pub next_offset: u64,
6435    pub terminal: bool,
6436}
6437
6438/// Durable acceptance and deduplication outcome for an append request.
6439#[derive(Clone, Debug)]
6440pub struct WorkflowStreamAppendResult {
6441    pub stream: WorkflowStreamDescription,
6442    pub accepted_offsets: Vec<u64>,
6443    pub accepted: u64,
6444    pub deduped: u64,
6445}
6446
6447#[derive(Deserialize)]
6448struct WorkflowStreamListResponse {
6449    #[serde(default)]
6450    streams: Vec<WorkflowStreamDescription>,
6451}
6452
6453#[derive(Deserialize)]
6454struct WorkflowStreamDescriptionResponse {
6455    stream: WorkflowStreamDescription,
6456}
6457
6458#[derive(Deserialize)]
6459struct WorkflowStreamPageResponse {
6460    stream: WorkflowStreamDescription,
6461    #[serde(default)]
6462    items: Vec<Value>,
6463    next_offset: u64,
6464    terminal: bool,
6465}
6466
6467#[derive(Deserialize)]
6468struct WorkflowStreamAppendResponse {
6469    stream: WorkflowStreamDescription,
6470    #[serde(default)]
6471    accepted_offsets: Vec<u64>,
6472    accepted: u64,
6473    deduped: u64,
6474}
6475
6476impl WorkflowDescription {
6477    pub fn is_completed(&self) -> bool {
6478        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6479    }
6480
6481    pub fn is_terminal(&self) -> bool {
6482        matches!(
6483            self.status.as_deref(),
6484            Some(
6485                "completed"
6486                    | "Completed"
6487                    | "failed"
6488                    | "Failed"
6489                    | "cancelled"
6490                    | "Cancelled"
6491                    | "terminated"
6492                    | "Terminated"
6493                    | "timed_out"
6494                    | "TimedOut",
6495            )
6496        )
6497    }
6498
6499    fn decode_payloads(&mut self) -> Result<()> {
6500        if let Some(envelope) = &self.output_envelope {
6501            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6502            self.output = Some(value.clone().into_json()?);
6503            self.output_avro_value = Some(value);
6504        }
6505
6506        Ok(())
6507    }
6508
6509    fn raw_value(&self) -> Value {
6510        let mut data = self.raw.clone();
6511        data.insert(
6512            "workflow_id".to_string(),
6513            self.workflow_id
6514                .clone()
6515                .map(Value::String)
6516                .unwrap_or(Value::Null),
6517        );
6518        data.insert(
6519            "run_id".to_string(),
6520            self.run_id
6521                .clone()
6522                .map(Value::String)
6523                .unwrap_or(Value::Null),
6524        );
6525        data.insert(
6526            "workflow_type".to_string(),
6527            self.workflow_type
6528                .clone()
6529                .map(Value::String)
6530                .unwrap_or(Value::Null),
6531        );
6532        data.insert(
6533            "status".to_string(),
6534            self.status
6535                .clone()
6536                .map(Value::String)
6537                .unwrap_or(Value::Null),
6538        );
6539        data.insert(
6540            "closed_reason".to_string(),
6541            self.closed_reason
6542                .clone()
6543                .map(Value::String)
6544                .unwrap_or(Value::Null),
6545        );
6546        if let Some(failure) = &self.failure {
6547            data.insert("failure".to_string(), failure.clone());
6548        }
6549        if let Some(exception) = &self.exception {
6550            data.insert("exception".to_string(), exception.clone());
6551        }
6552        Value::Object(data.into_iter().collect())
6553    }
6554}
6555
6556fn workflow_terminal_outcome(
6557    description: &WorkflowDescription,
6558    workflow_id: &str,
6559    run_id: Option<&str>,
6560) -> WorkflowTerminalOutcome {
6561    let terminal_kind = description
6562        .closed_reason
6563        .as_deref()
6564        .or(description.status.as_deref())
6565        .unwrap_or("failed")
6566        .to_ascii_lowercase();
6567    let kind = match terminal_kind.as_str() {
6568        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6569        "terminated" => WorkflowTerminalKind::Terminated,
6570        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6571        _ => WorkflowTerminalKind::Failed,
6572    };
6573    let default_reason = match kind {
6574        WorkflowTerminalKind::Failed => "workflow_failed",
6575        WorkflowTerminalKind::Cancelled => "cancelled",
6576        WorkflowTerminalKind::Terminated => "terminated",
6577        WorkflowTerminalKind::TimedOut => "timed_out",
6578    };
6579    let failure = description
6580        .failure
6581        .as_ref()
6582        .filter(|value| value.is_object());
6583    let nested_failure = failure
6584        .and_then(|value| value.get("failures"))
6585        .and_then(Value::as_array)
6586        .and_then(|failures| failures.last())
6587        .or_else(|| description.failures.last());
6588    let exception = description
6589        .exception
6590        .clone()
6591        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6592        .or_else(|| {
6593            nested_failure
6594                .and_then(|value| value.get("exception_payload"))
6595                .cloned()
6596        });
6597    let string_field = |name: &str| {
6598        failure
6599            .and_then(|value| value.get(name))
6600            .and_then(Value::as_str)
6601            .or_else(|| {
6602                nested_failure
6603                    .and_then(|value| value.get(name))
6604                    .and_then(Value::as_str)
6605            })
6606            .map(str::to_string)
6607    };
6608    let exception_field = |name: &str| {
6609        exception
6610            .as_ref()
6611            .and_then(|value| value.get(name))
6612            .and_then(Value::as_str)
6613            .map(str::to_string)
6614    };
6615    let message = description
6616        .error
6617        .clone()
6618        .or_else(|| string_field("message"))
6619        .or_else(|| exception_field("message"));
6620    let reason = description
6621        .raw
6622        .get("reason")
6623        .and_then(Value::as_str)
6624        .map(str::to_string)
6625        .or_else(|| {
6626            failure
6627                .and_then(|value| value.get("reason"))
6628                .and_then(Value::as_str)
6629                .map(str::to_string)
6630        })
6631        .or_else(|| description.closed_reason.clone())
6632        .unwrap_or_else(|| default_reason.to_string());
6633    let failure_id = string_field("failure_id").or_else(|| {
6634        nested_failure
6635            .and_then(|value| value.get("id"))
6636            .and_then(Value::as_str)
6637            .map(str::to_string)
6638    });
6639
6640    WorkflowTerminalOutcome {
6641        kind,
6642        workflow_id: description
6643            .workflow_id
6644            .clone()
6645            .unwrap_or_else(|| workflow_id.to_string()),
6646        run_id: description
6647            .run_id
6648            .clone()
6649            .or_else(|| run_id.map(str::to_string)),
6650        reason,
6651        failure_category: string_field("failure_category")
6652            .or_else(|| Some(default_reason.to_string())),
6653        failure_id,
6654        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6655        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6656        non_retryable: failure
6657            .and_then(|value| value.get("non_retryable"))
6658            .and_then(Value::as_bool)
6659            .or_else(|| {
6660                nested_failure
6661                    .and_then(|value| value.get("non_retryable"))
6662                    .and_then(Value::as_bool)
6663            }),
6664        message,
6665        exception,
6666        raw: description.raw_value(),
6667    }
6668}
6669
6670#[derive(Clone, Debug, Deserialize)]
6671pub struct RegisterWorkerResponse {
6672    pub worker_id: String,
6673    pub registered: bool,
6674    #[serde(default)]
6675    pub heartbeat_interval_seconds: Option<u64>,
6676    #[serde(default)]
6677    pub protocol_version: Option<String>,
6678    #[serde(default)]
6679    pub server_capabilities: Option<Value>,
6680}
6681
6682/// Result of gracefully removing a worker-plane registration.
6683#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6684pub struct WorkerDeregistrationEnvelope {
6685    pub worker_id: String,
6686    pub outcome: String,
6687    pub recovered_workflow_task_count: u64,
6688}
6689
6690#[derive(Clone, Debug, Deserialize)]
6691pub struct PollWorkflowTaskResponse {
6692    #[serde(default)]
6693    pub task: Option<WorkflowTask>,
6694    #[serde(default)]
6695    pub poll_status: Option<String>,
6696    #[serde(default)]
6697    pub reason: Option<String>,
6698    #[serde(default)]
6699    pub protocol_version: Option<String>,
6700    #[serde(default)]
6701    pub server_capabilities: Option<Value>,
6702}
6703
6704impl PollWorkflowTaskResponse {
6705    /// Classify this response without parsing server display text.
6706    pub fn outcome(&self) -> WorkerPollOutcome {
6707        worker_poll_outcome(
6708            self.task.is_some(),
6709            self.poll_status.as_deref(),
6710            self.reason.as_deref(),
6711        )
6712    }
6713}
6714
6715fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6716    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6717        return false;
6718    };
6719    let supported = capabilities
6720        .get("workflow_memo_updates")
6721        .and_then(Value::as_object)
6722        .and_then(|memo| memo.get("supported"))
6723        .and_then(Value::as_bool)
6724        == Some(true);
6725    let command_advertised = capabilities
6726        .get("supported_workflow_task_commands")
6727        .and_then(Value::as_array)
6728        .is_some_and(|commands| {
6729            commands
6730                .iter()
6731                .any(|command| command.as_str() == Some("upsert_memo"))
6732        });
6733    supported && command_advertised
6734}
6735
6736fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6737    commands
6738        .iter()
6739        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6740}
6741
6742#[derive(Clone, Debug, Deserialize)]
6743pub struct PollActivityTaskResponse {
6744    #[serde(default)]
6745    pub task: Option<ActivityTask>,
6746    #[serde(default)]
6747    pub poll_status: Option<String>,
6748    #[serde(default)]
6749    pub reason: Option<String>,
6750}
6751
6752impl PollActivityTaskResponse {
6753    /// Classify this response without parsing server display text.
6754    pub fn outcome(&self) -> WorkerPollOutcome {
6755        worker_poll_outcome(
6756            self.task.is_some(),
6757            self.poll_status.as_deref(),
6758            self.reason.as_deref(),
6759        )
6760    }
6761}
6762
6763#[derive(Clone, Debug, Deserialize)]
6764pub struct PollQueryTaskResponse {
6765    #[serde(default)]
6766    pub task: Option<QueryTask>,
6767    #[serde(default)]
6768    pub poll_status: Option<String>,
6769    #[serde(default)]
6770    pub reason: Option<String>,
6771}
6772
6773impl PollQueryTaskResponse {
6774    /// Classify this response without parsing server display text.
6775    pub fn outcome(&self) -> WorkerPollOutcome {
6776        worker_poll_outcome(
6777            self.task.is_some(),
6778            self.poll_status.as_deref(),
6779            self.reason.as_deref(),
6780        )
6781    }
6782}
6783
6784/// Stable classification for worker poll responses.
6785#[derive(Clone, Debug, PartialEq, Eq)]
6786pub enum WorkerPollOutcome {
6787    /// A task was leased and is available on the response.
6788    Task,
6789    /// No task was leased, but the worker should continue polling.
6790    Idle {
6791        poll_status: Option<String>,
6792        reason: Option<String>,
6793    },
6794    /// The server asked this worker to stop claiming new work.
6795    Stop {
6796        poll_status: Option<String>,
6797        reason: Option<String>,
6798    },
6799}
6800
6801impl WorkerPollOutcome {
6802    pub fn should_stop(&self) -> bool {
6803        matches!(self, Self::Stop { .. })
6804    }
6805}
6806
6807fn worker_poll_outcome(
6808    has_task: bool,
6809    poll_status: Option<&str>,
6810    reason: Option<&str>,
6811) -> WorkerPollOutcome {
6812    if worker_poll_is_stop(poll_status, reason) {
6813        return WorkerPollOutcome::Stop {
6814            poll_status: poll_status.map(str::to_string),
6815            reason: reason.map(str::to_string),
6816        };
6817    }
6818
6819    if has_task {
6820        WorkerPollOutcome::Task
6821    } else {
6822        WorkerPollOutcome::Idle {
6823            poll_status: poll_status.map(str::to_string),
6824            reason: reason.map(str::to_string),
6825        }
6826    }
6827}
6828
6829/// An ephemeral server-routed query task.
6830#[derive(Clone, Debug, Deserialize)]
6831pub struct QueryTask {
6832    pub query_task_id: String,
6833    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6834    #[serde(default)]
6835    pub observability_context: Option<Value>,
6836    #[serde(default)]
6837    pub dispatch_observability_context: Option<Value>,
6838    #[serde(default)]
6839    pub observability_links: Option<Value>,
6840    #[serde(default = "default_workflow_task_attempt")]
6841    pub query_task_attempt: u64,
6842    #[serde(default)]
6843    pub lease_owner: Option<String>,
6844    #[serde(default)]
6845    pub workflow_id: Option<String>,
6846    #[serde(default)]
6847    pub run_id: Option<String>,
6848    pub workflow_type: String,
6849    pub query_name: String,
6850    #[serde(
6851        default = "missing_task_payload_codec",
6852        deserialize_with = "deserialize_task_payload_codec"
6853    )]
6854    pub payload_codec: String,
6855    #[serde(default)]
6856    pub workflow_arguments: Option<Value>,
6857    #[serde(default)]
6858    pub query_arguments: Option<Value>,
6859    #[serde(default)]
6860    pub history_events: Vec<HistoryEvent>,
6861    #[serde(default)]
6862    pub history_export: Option<Value>,
6863    #[serde(default)]
6864    pub run_status: Option<String>,
6865}
6866
6867#[derive(Clone, Debug, Deserialize)]
6868pub struct WorkflowTask {
6869    pub task_id: String,
6870    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6871    #[serde(default)]
6872    pub observability_context: Option<Value>,
6873    #[serde(default)]
6874    pub dispatch_observability_context: Option<Value>,
6875    #[serde(default)]
6876    pub observability_links: Option<Value>,
6877    #[serde(default)]
6878    pub workflow_command_id: Option<String>,
6879    #[serde(default)]
6880    pub workflow_id: Option<String>,
6881    #[serde(default)]
6882    pub run_id: Option<String>,
6883    pub workflow_type: String,
6884    #[serde(default)]
6885    pub cancel_requested: bool,
6886    #[serde(
6887        default = "missing_task_payload_codec",
6888        deserialize_with = "deserialize_task_payload_codec"
6889    )]
6890    pub payload_codec: String,
6891    #[serde(default)]
6892    pub arguments: Option<Value>,
6893    #[serde(default)]
6894    pub history_events: Vec<HistoryEvent>,
6895    #[serde(default)]
6896    pub total_history_events: Option<u64>,
6897    #[serde(default)]
6898    pub history_size_bytes: Option<u64>,
6899    #[serde(default)]
6900    pub continue_as_new_recommended: Option<bool>,
6901    #[serde(default)]
6902    pub history_budget_pressure: Option<String>,
6903    #[serde(default)]
6904    pub next_history_page_token: Option<String>,
6905    #[serde(default = "default_workflow_task_attempt")]
6906    pub workflow_task_attempt: u64,
6907    #[serde(default)]
6908    pub workflow_signal_id: Option<String>,
6909    #[serde(default)]
6910    pub signal_name: Option<String>,
6911    #[serde(default)]
6912    pub signal_arguments: Option<Value>,
6913    #[serde(default)]
6914    pub workflow_update_id: Option<String>,
6915    #[serde(default)]
6916    pub update_name: Option<String>,
6917    #[serde(default)]
6918    pub lease_owner: Option<String>,
6919}
6920
6921impl WorkflowTask {
6922    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6923        self.history_events.extend(page.history_events);
6924
6925        if page.total_history_events.is_some() {
6926            self.total_history_events = page.total_history_events;
6927        }
6928
6929        self.next_history_page_token = page
6930            .next_history_page_token
6931            .filter(|token| !token.is_empty());
6932    }
6933}
6934
6935#[derive(Clone, Debug, Deserialize)]
6936struct WorkflowTaskHistoryPage {
6937    #[serde(default)]
6938    history_events: Vec<HistoryEvent>,
6939    #[serde(default)]
6940    total_history_events: Option<u64>,
6941    #[serde(default)]
6942    next_history_page_token: Option<String>,
6943}
6944
6945#[derive(Clone, Debug, Deserialize)]
6946pub struct ActivityTask {
6947    pub task_id: String,
6948    #[serde(default)]
6949    pub workflow_id: Option<String>,
6950    #[serde(default)]
6951    pub run_id: Option<String>,
6952    #[serde(default)]
6953    pub activity_execution_id: Option<String>,
6954    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6955    #[serde(default)]
6956    pub observability_context: Option<Value>,
6957    #[serde(default)]
6958    pub dispatch_observability_context: Option<Value>,
6959    #[serde(default)]
6960    pub observability_links: Option<Value>,
6961    #[serde(default)]
6962    pub activity_attempt_id: Option<String>,
6963    #[serde(default)]
6964    pub attempt_id: Option<String>,
6965    pub activity_type: String,
6966    #[serde(
6967        default = "missing_task_payload_codec",
6968        deserialize_with = "deserialize_task_payload_codec"
6969    )]
6970    pub payload_codec: String,
6971    #[serde(default)]
6972    pub arguments: Option<Value>,
6973    #[serde(default = "default_attempt_number")]
6974    pub attempt_number: u64,
6975    #[serde(default)]
6976    pub lease_owner: Option<String>,
6977}
6978
6979#[derive(Clone, Debug, Serialize, Deserialize)]
6980pub struct HistoryEvent {
6981    #[serde(alias = "type")]
6982    pub event_type: String,
6983    #[serde(default)]
6984    pub payload: Value,
6985    #[serde(flatten)]
6986    pub raw: HashMap<String, Value>,
6987}
6988
6989/// One decoded signal in the committed workflow-history snapshot.
6990#[derive(Clone, Debug, PartialEq)]
6991pub struct QuerySignal {
6992    pub id: Option<String>,
6993    pub name: String,
6994    pub arguments: Vec<Value>,
6995    avro_arguments: Vec<AvroValue>,
6996    pub workflow_sequence: Option<u64>,
6997}
6998
6999impl QuerySignal {
7000    /// Lossless fixed Avro Value arguments for this committed signal.
7001    pub fn arguments_avro_value(&self) -> &[AvroValue] {
7002        &self.avro_arguments
7003    }
7004}
7005
7006/// Immutable state supplied to a registered query handler.
7007///
7008/// This context intentionally exposes no activity, signal-wait, or command
7009/// APIs. Query handlers inspect committed history and return a value; query
7010/// completion does not append an event or advance deterministic execution.
7011#[derive(Clone, Debug)]
7012pub struct QueryContext {
7013    pub workflow_id: Option<String>,
7014    pub run_id: Option<String>,
7015    pub workflow_type: String,
7016    pub run_status: Option<String>,
7017    workflow_input: Value,
7018    workflow_input_avro_value: AvroValue,
7019    history_events: Arc<Vec<HistoryEvent>>,
7020    signal_events: Arc<Vec<QuerySignal>>,
7021}
7022
7023impl QueryContext {
7024    /// The normalized argument list used to start the workflow.
7025    pub fn workflow_input(&self) -> &Value {
7026        &self.workflow_input
7027    }
7028
7029    /// The lossless fixed Avro Value argument list used to start the workflow.
7030    pub fn workflow_input_avro_value(&self) -> &AvroValue {
7031        &self.workflow_input_avro_value
7032    }
7033
7034    /// The immutable committed history used for this query snapshot.
7035    pub fn history_events(&self) -> &[HistoryEvent] {
7036        self.history_events.as_slice()
7037    }
7038
7039    /// All decoded signals in committed workflow order.
7040    pub fn signal_events(&self) -> &[QuerySignal] {
7041        self.signal_events.as_slice()
7042    }
7043
7044    /// Decoded argument lists for each committed signal with `signal_name`.
7045    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
7046        self.signal_events
7047            .iter()
7048            .filter(|signal| signal.name == signal_name)
7049            .map(|signal| signal.arguments.clone())
7050            .collect()
7051    }
7052
7053    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
7054    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
7055        self.signal_events
7056            .iter()
7057            .filter(|signal| signal.name == signal_name)
7058            .map(|signal| signal.avro_arguments.clone())
7059            .collect()
7060    }
7061}
7062
7063#[derive(Clone, Debug, Deserialize)]
7064pub struct ActivityHeartbeatResponse {
7065    #[serde(default)]
7066    pub cancel_requested: bool,
7067    #[serde(default)]
7068    pub heartbeat_recorded: bool,
7069    #[serde(default)]
7070    pub can_continue: Option<bool>,
7071    #[serde(default)]
7072    pub reason: Option<String>,
7073    #[serde(default)]
7074    pub run_closed_reason: Option<String>,
7075    #[serde(default)]
7076    pub run_closed_at: Option<String>,
7077    #[serde(default)]
7078    pub lease_expires_at: Option<String>,
7079    #[serde(default)]
7080    pub last_heartbeat_at: Option<String>,
7081}
7082
7083impl ActivityHeartbeatResponse {
7084    /// Whether the activity should stop instead of attempting completion.
7085    pub fn should_stop(&self) -> bool {
7086        self.cancel_requested || self.can_continue == Some(false)
7087    }
7088}
7089
7090fn missing_task_payload_codec() -> String {
7091    MISSING_TASK_PAYLOAD_CODEC.to_string()
7092}
7093
7094fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
7095where
7096    D: Deserializer<'de>,
7097{
7098    Ok(match Value::deserialize(deserializer)? {
7099        Value::String(codec) => codec,
7100        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
7101        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
7102    })
7103}
7104
7105fn default_workflow_task_attempt() -> u64 {
7106    1
7107}
7108
7109fn default_attempt_number() -> u64 {
7110    1
7111}
7112
7113type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7114type WorkflowHandler =
7115    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
7116type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
7117type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
7118type ReplayedWorkflowHandler =
7119    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
7120type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7121type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
7122type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7123type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7124type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7125type ReplayedQueryHandler = Arc<
7126    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
7127        + Send
7128        + Sync,
7129>;
7130type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
7131
7132struct ReplayedWorkflowInvocation {
7133    future: WorkflowFuture,
7134    snapshot: WorkflowStateSnapshot,
7135}
7136
7137#[derive(Clone)]
7138struct RegisteredWorkflow {
7139    execute: WorkflowHandler,
7140    replay: Option<ReplayedWorkflowHandler>,
7141    state_type: Option<TypeId>,
7142    definition_fingerprint: Option<String>,
7143}
7144
7145fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
7146    names
7147        .iter()
7148        .map(|name| {
7149            json!({
7150                "name": name,
7151                "parameters": [{
7152                    "name": "args",
7153                    "position": 0,
7154                    "required": false,
7155                    "variadic": true,
7156                    "type": null,
7157                    "allows_null": true,
7158                    "default_available": false,
7159                    "default": null,
7160                }],
7161            })
7162        })
7163        .collect()
7164}
7165
7166#[derive(Debug)]
7167struct WorkflowTaskDecision {
7168    commands: Vec<Value>,
7169    message_stream_cursors: Vec<Value>,
7170    message_stream_waits: Vec<Value>,
7171    cancellation_delivery: Option<CancellationDelivery>,
7172    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
7173    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
7174}
7175
7176enum PreparedWorkflowTask {
7177    Decision(WorkflowTaskDecision),
7178    Execution {
7179        task: WorkflowTask,
7180        context: WorkflowContext,
7181        future: WorkflowFuture,
7182    },
7183}
7184
7185impl WorkflowTaskDecision {
7186    fn without_message_streams(commands: Vec<Value>) -> Self {
7187        Self {
7188            commands,
7189            message_stream_cursors: Vec::new(),
7190            message_stream_waits: Vec::new(),
7191            cancellation_delivery: None,
7192            cancellation_scope_opening: None,
7193            cancellation_scope_delivery: None,
7194        }
7195    }
7196}
7197
7198#[derive(Clone)]
7199enum RegisteredQuery {
7200    Snapshot(QueryHandler),
7201    Replayed {
7202        state_type: TypeId,
7203        handler: ReplayedQueryHandler,
7204    },
7205}
7206
7207#[derive(Clone, Debug)]
7208pub struct WorkerHeartbeatObservation {
7209    pub worker_id: String,
7210    pub task_queue: String,
7211    pub acknowledged_at_unix_millis: u64,
7212    pub acknowledgement: Value,
7213}
7214
7215/// Bounded retry policy for worker poll acquisition and worker heartbeats.
7216///
7217/// Expected empty long polls and explicit Server capacity backpressure are
7218/// normal worker states. Capacity backpressure honors the advertised retry
7219/// delay without consuming this retry budget. Other transport failures,
7220/// retryable HTTP 408/429 responses, and server errors are retried with capped
7221/// exponential backoff. Authentication, protocol, codec, and handler failures
7222/// are never retried by the worker.
7223/// Explicit storage admission pauses also preserve the already-serialized worker
7224/// request without consuming this budget or rerunning its handler. The delay is
7225/// capped by `max_backoff`, except an explicit completion deferral must honor
7226/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
7227/// completion retries remain bounded by the original cleanup deadline.
7228/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
7229/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
7230/// and `max_retries = 0` disables ordinary retries in either mode.
7231#[derive(Clone, Copy, Debug)]
7232pub struct WorkerRetryPolicy {
7233    /// Number of retries after the initial request fails.
7234    pub max_retries: usize,
7235    /// Delay before the first retry.
7236    pub initial_backoff: Duration,
7237    /// Maximum delay between retries.
7238    pub max_backoff: Duration,
7239}
7240
7241impl Default for WorkerRetryPolicy {
7242    fn default() -> Self {
7243        Self {
7244            max_retries: 5,
7245            initial_backoff: Duration::from_millis(100),
7246            max_backoff: Duration::from_secs(5),
7247        }
7248    }
7249}
7250
7251#[derive(Clone, Debug)]
7252struct WorkerStorageAdmission {
7253    policy: WorkerRetryPolicy,
7254    stop: Arc<AtomicBool>,
7255    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
7256}
7257
7258struct StopWorkerOnDrop(Arc<AtomicBool>);
7259
7260impl Drop for StopWorkerOnDrop {
7261    fn drop(&mut self) {
7262        self.0.store(true, Ordering::SeqCst);
7263    }
7264}
7265
7266async fn wait_for_worker_stop(stop: &AtomicBool) {
7267    while !stop.load(Ordering::SeqCst) {
7268        tokio::time::sleep(Duration::from_millis(100)).await;
7269    }
7270}
7271
7272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7273enum ManagedPollOutcome {
7274    Idle,
7275    Handled,
7276    Stop,
7277}
7278
7279#[derive(Clone)]
7280pub struct Worker {
7281    #[cfg(feature = "telemetry")]
7282    telemetry: Option<telemetry::ExecutionTelemetry>,
7283    client: Client,
7284    worker_id: String,
7285    task_queue: String,
7286    workflows: HashMap<String, RegisteredWorkflow>,
7287    activities: HashMap<String, ActivityHandler>,
7288    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
7289    signals: HashMap<String, Vec<String>>,
7290    updates: HashMap<String, HashMap<String, UpdateHandler>>,
7291    registration_definitions:
7292        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
7293    registration_error: Option<DuplicateRegistrationError>,
7294    max_concurrent_workflow_tasks: usize,
7295    max_concurrent_activity_tasks: usize,
7296    poll_timeout: Duration,
7297    heartbeat_interval: Duration,
7298    retry_policy: WorkerRetryPolicy,
7299    recover_transient_outages: bool,
7300    run_stop: Option<Arc<AtomicBool>>,
7301    heartbeat_observer: Option<WorkerHeartbeatObserver>,
7302    cooperative_cancellation_enabled: bool,
7303    nexus_cooperative_cancellation_enabled: bool,
7304    allow_cancellation_scope_authoring: bool,
7305    allow_cancellation_scope_delivery: bool,
7306    cooperative_registration_confirmed: Arc<AtomicBool>,
7307    nexus_registration_confirmed: Arc<AtomicBool>,
7308    local_registration_confirmed: Arc<AtomicBool>,
7309    session_registration_confirmed: Arc<AtomicBool>,
7310    sticky_registration_confirmed: Arc<AtomicBool>,
7311    require_query_task_authority: bool,
7312    query_authority_confirmed: Arc<AtomicBool>,
7313    resource_capabilities: Vec<String>,
7314    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
7315}
7316
7317impl Worker {
7318    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
7319        Self {
7320            #[cfg(feature = "telemetry")]
7321            telemetry: None,
7322            client,
7323            worker_id: default_worker_id(),
7324            task_queue: task_queue.into(),
7325            workflows: HashMap::new(),
7326            activities: HashMap::new(),
7327            queries: HashMap::new(),
7328            signals: HashMap::new(),
7329            updates: HashMap::new(),
7330            registration_definitions: HashMap::new(),
7331            registration_error: None,
7332            max_concurrent_workflow_tasks: 10,
7333            max_concurrent_activity_tasks: 10,
7334            poll_timeout: Duration::from_secs(30),
7335            heartbeat_interval: Duration::from_secs(60),
7336            retry_policy: WorkerRetryPolicy::default(),
7337            recover_transient_outages: false,
7338            run_stop: None,
7339            heartbeat_observer: None,
7340            cooperative_cancellation_enabled: false,
7341            nexus_cooperative_cancellation_enabled: false,
7342            allow_cancellation_scope_authoring: false,
7343            allow_cancellation_scope_delivery: false,
7344            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
7345            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
7346            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
7347            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
7348            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
7349            require_query_task_authority: false,
7350            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
7351            resource_capabilities: Vec::new(),
7352            sessions: Arc::new(Mutex::new(HashMap::new())),
7353        }
7354    }
7355
7356    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
7357        self.worker_id = worker_id.into();
7358        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7359        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7360        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7361        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
7362        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
7363        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
7364        self.client.reset_sticky_cache();
7365        self.sessions = Arc::new(Mutex::new(HashMap::new()));
7366        self
7367    }
7368
7369    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
7370        self.poll_timeout = timeout;
7371        self
7372    }
7373
7374    /// Opt in to execution spans using application-owned OpenTelemetry providers.
7375    /// No exporter, logging bridge, global provider or Server carrier is installed.
7376    #[cfg(feature = "telemetry")]
7377    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
7378        self.client.execution_telemetry = Some(telemetry.clone());
7379        self.telemetry = Some(telemetry);
7380        self
7381    }
7382
7383    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
7384        self.heartbeat_interval = interval;
7385        self
7386    }
7387
7388    /// Require original query timing and non-renewing runtime observation.
7389    ///
7390    /// Registration refuses before creating a Worker unless protocol 1.20 and
7391    /// the runtime's `query_task_authority` capability are available. By default,
7392    /// older Servers retain their weaker, disclosed local-timing behavior.
7393    pub fn require_query_task_authority(mut self, required: bool) -> Self {
7394        self.require_query_task_authority = required;
7395        self
7396    }
7397
7398    /// Explicitly enable inline local activities in this workflow worker.
7399    ///
7400    /// The worker advertises the capability to Server only when enabled.
7401    /// These callbacks must yield to Tokio and have idempotent side effects.
7402    /// Cooperative prepared local supervision is a separate capability.
7403    pub fn local_activities(mut self, enabled: bool) -> Self {
7404        self.client.local_activities_enabled = enabled;
7405        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7406        self
7407    }
7408
7409    /// Opt in to separate cooperative workflow cancellation requests.
7410    ///
7411    /// Registration requires the Server to acknowledge this exact worker,
7412    /// namespace, queue and capabilities with compatible protocol 1.20. Task
7413    /// processing uses canonical delivery and activity ownership fences.
7414    /// Existing terminal cancel and terminate operations remain terminal.
7415    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
7416    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
7417    /// and [`Worker::run_until`] register automatically.
7418    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
7419        self.cooperative_cancellation_enabled = enabled;
7420        self.client.cooperative_worker_protocol = enabled;
7421        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7422        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7423        if !enabled {
7424            self.nexus_cooperative_cancellation_enabled = false;
7425        }
7426        self
7427    }
7428
7429    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
7430    ///
7431    /// This also enables ordinary cooperative cancellation. Registration checks
7432    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
7433    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
7434        let mut worker = if enabled {
7435            self.cooperative_cancellation(true)
7436        } else {
7437            self
7438        };
7439        worker.nexus_cooperative_cancellation_enabled = enabled;
7440        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7441        worker
7442    }
7443
7444    /// Enable candidate scope authoring without advertising scoped execution.
7445    #[doc(hidden)]
7446    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
7447        self.allow_cancellation_scope_authoring = enabled;
7448        self
7449    }
7450
7451    /// Enable the candidate scoped call consumer with canonical authoring.
7452    #[doc(hidden)]
7453    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
7454        self.allow_cancellation_scope_delivery = enabled;
7455        self
7456    }
7457
7458    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
7459    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
7460        self.retry_policy = policy;
7461        self
7462    }
7463
7464    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7465    ///
7466    /// Retries preserve the poll request identity and use capped exponential
7467    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7468    /// An in-flight poll is allowed to finish so leased work is not discarded.
7469    /// Authentication, protocol, codec, handler and task settlement failures
7470    /// remain errors. Registration and deregistration are not retried here.
7471    ///
7472    /// The default is disabled, preserving the bounded retry contract.
7473    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7474    /// even when this option is enabled.
7475    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7476        self.recover_transient_outages = enabled;
7477        self
7478    }
7479
7480    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7481    where
7482        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7483    {
7484        self.heartbeat_observer = Some(Arc::new(observer));
7485        self
7486    }
7487
7488    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7489        self.max_concurrent_workflow_tasks = count.max(1);
7490        self
7491    }
7492
7493    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7494        self.max_concurrent_activity_tasks = count.max(1);
7495        self
7496    }
7497
7498    /// Validate local handler admission without making a Server request.
7499    ///
7500    /// Registration methods retain their existing signatures. A duplicate keeps
7501    /// the original handler and makes this Worker invalid, including its clones.
7502    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7503    /// any network request. Build a new Worker to correct an invalid configuration.
7504    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7505        match &self.registration_error {
7506            Some(error) => Err(error.clone()),
7507            None => Ok(()),
7508        }
7509    }
7510
7511    #[track_caller]
7512    fn admit_registration<F>(
7513        &mut self,
7514        handler_kind: RegistrationKind,
7515        workflow_type: Option<&str>,
7516        handler_name: &str,
7517        method: &'static str,
7518    ) -> bool {
7519        let location = std::panic::Location::caller();
7520        let definition = HandlerRegistration {
7521            method,
7522            handler_type: type_name::<F>(),
7523            file: location.file(),
7524            line: location.line(),
7525            column: location.column(),
7526        };
7527        let key = (
7528            handler_kind,
7529            workflow_type.map(str::to_owned),
7530            handler_name.to_owned(),
7531        );
7532        if let Some(first_definition) = self.registration_definitions.get(&key) {
7533            if self.registration_error.is_none() {
7534                self.registration_error = Some(DuplicateRegistrationError {
7535                    handler_kind,
7536                    workflow_type: key.1.clone(),
7537                    handler_name: key.2.clone(),
7538                    first_definition: first_definition.clone(),
7539                    second_definition: definition,
7540                });
7541            }
7542            return false;
7543        }
7544        self.registration_definitions.insert(key, definition);
7545        true
7546    }
7547
7548    /// Register a workflow handler.
7549    ///
7550    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7551    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7552    /// while acquiring or decoding a worker task remain worker-operation
7553    /// failures and do not get converted into workflow outcomes.
7554    #[track_caller]
7555    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7556    where
7557        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7558        Fut: Future<Output = Result<Value>> + Send + 'static,
7559    {
7560        let workflow_type = workflow_type.into();
7561        if !self.admit_registration::<F>(
7562            RegistrationKind::Workflow,
7563            None,
7564            &workflow_type,
7565            "register_workflow",
7566        ) {
7567            return;
7568        }
7569        let handler = Arc::new(handler);
7570        self.workflows.insert(
7571            workflow_type,
7572            RegisteredWorkflow {
7573                execute: Arc::new(move |ctx, input| {
7574                    let handler = Arc::clone(&handler);
7575                    Ok(Box::pin(async move {
7576                        let result = handler(ctx, input.into_json()?).await?;
7577                        AvroValue::from_serialize(&result)
7578                    }))
7579                }),
7580                replay: None,
7581                state_type: None,
7582                definition_fingerprint: None,
7583            },
7584        );
7585    }
7586
7587    /// Register a workflow with one Serde request value and a Serde result.
7588    ///
7589    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7590    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7591    /// workflow-specific schema. A task must contain zero arguments for a unit
7592    /// request or exactly one argument for every other request type.
7593    ///
7594    /// See the runnable
7595    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7596    /// for typed workflow and activity contracts with retry and timeout policy.
7597    #[track_caller]
7598    pub fn register_typed_workflow<I, O, F, Fut>(
7599        &mut self,
7600        workflow_type: impl Into<String>,
7601        handler: F,
7602    ) where
7603        I: DeserializeOwned + Send + 'static,
7604        O: Serialize + Send + 'static,
7605        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7606        Fut: Future<Output = Result<O>> + Send + 'static,
7607    {
7608        let workflow_type = workflow_type.into();
7609        if !self.admit_registration::<F>(
7610            RegistrationKind::Workflow,
7611            None,
7612            &workflow_type,
7613            "register_typed_workflow",
7614        ) {
7615            return;
7616        }
7617        let handler_name = workflow_type.clone();
7618        let handler = Arc::new(handler);
7619        self.workflows.insert(
7620            workflow_type,
7621            RegisteredWorkflow {
7622                execute: Arc::new(move |ctx, input| {
7623                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7624                    let handler = Arc::clone(&handler);
7625                    let handler_name = handler_name.clone();
7626                    Ok(Box::pin(async move {
7627                        let result = handler(ctx, input).await?;
7628                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7629                    }))
7630                }),
7631                replay: None,
7632                state_type: None,
7633                definition_fingerprint: None,
7634            },
7635        );
7636    }
7637
7638    /// Register a workflow on the lossless fixed Avro Value surface.
7639    #[track_caller]
7640    pub fn register_workflow_avro_value<F, Fut>(
7641        &mut self,
7642        workflow_type: impl Into<String>,
7643        handler: F,
7644    ) where
7645        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7646        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7647    {
7648        let workflow_type = workflow_type.into();
7649        if !self.admit_registration::<F>(
7650            RegistrationKind::Workflow,
7651            None,
7652            &workflow_type,
7653            "register_workflow_avro_value",
7654        ) {
7655            return;
7656        }
7657        self.workflows.insert(
7658            workflow_type,
7659            RegisteredWorkflow {
7660                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7661                replay: None,
7662                state_type: None,
7663                definition_fingerprint: None,
7664            },
7665        );
7666    }
7667
7668    /// Register a workflow whose typed instance state can be reconstructed for queries.
7669    ///
7670    /// `state_factory` creates a fresh instance for every normal workflow task and
7671    /// query replay. The workflow handler is the single source of truth for state
7672    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7673    /// resolve. Query replay runs this same handler over committed history and
7674    /// discards any commands it would emit.
7675    #[track_caller]
7676    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7677        &mut self,
7678        workflow_type: impl Into<String>,
7679        state_factory: Factory,
7680        handler: F,
7681    ) where
7682        S: Clone + Send + Sync + 'static,
7683        Factory: Fn() -> S + Send + Sync + 'static,
7684        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7685        Fut: Future<Output = Result<Value>> + Send + 'static,
7686    {
7687        let workflow_type = workflow_type.into();
7688        if !self.admit_registration::<F>(
7689            RegistrationKind::Workflow,
7690            None,
7691            &workflow_type,
7692            "register_replayed_workflow",
7693        ) {
7694            return;
7695        }
7696        let state_factory = Arc::new(state_factory);
7697        let handler = Arc::new(handler);
7698
7699        let execute_factory = Arc::clone(&state_factory);
7700        let execute_handler = Arc::clone(&handler);
7701        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7702            let state = WorkflowInstance::new(execute_factory());
7703            let handler = Arc::clone(&execute_handler);
7704            Ok(Box::pin(async move {
7705                let result = handler(ctx, input.into_json()?, state).await?;
7706                AvroValue::from_serialize(&result)
7707            }) as WorkflowFuture)
7708        });
7709
7710        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7711            let state = WorkflowInstance::new(state_factory());
7712            let snapshot_state = state.clone();
7713            let snapshot: WorkflowStateSnapshot =
7714                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7715            let replay_handler = Arc::clone(&handler);
7716            let future = async move {
7717                let result = replay_handler(ctx, input.into_json()?, state).await?;
7718                AvroValue::from_serialize(&result)
7719            };
7720            Ok(ReplayedWorkflowInvocation {
7721                future: Box::pin(future),
7722                snapshot,
7723            })
7724        });
7725
7726        self.workflows.insert(
7727            workflow_type,
7728            RegisteredWorkflow {
7729                execute,
7730                replay: Some(replay),
7731                state_type: Some(TypeId::of::<S>()),
7732                definition_fingerprint: None,
7733            },
7734        );
7735    }
7736
7737    /// Register a replayable workflow with one Serde request value and result.
7738    ///
7739    /// Normal task execution and instance-state query replay both decode and
7740    /// encode through the fixed Avro Value codec. The state factory and handler
7741    /// otherwise follow [`Worker::register_replayed_workflow`].
7742    #[track_caller]
7743    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7744        &mut self,
7745        workflow_type: impl Into<String>,
7746        state_factory: Factory,
7747        handler: F,
7748    ) where
7749        I: DeserializeOwned + Send + 'static,
7750        O: Serialize + Send + 'static,
7751        S: Clone + Send + Sync + 'static,
7752        Factory: Fn() -> S + Send + Sync + 'static,
7753        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7754        Fut: Future<Output = Result<O>> + Send + 'static,
7755    {
7756        let workflow_type = workflow_type.into();
7757        if !self.admit_registration::<F>(
7758            RegistrationKind::Workflow,
7759            None,
7760            &workflow_type,
7761            "register_typed_replayed_workflow",
7762        ) {
7763            return;
7764        }
7765        let state_factory = Arc::new(state_factory);
7766        let handler = Arc::new(handler);
7767
7768        let execute_name = workflow_type.clone();
7769        let execute_factory = Arc::clone(&state_factory);
7770        let execute_handler = Arc::clone(&handler);
7771        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7772            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7773            let state = WorkflowInstance::new(execute_factory());
7774            let handler = Arc::clone(&execute_handler);
7775            let handler_name = execute_name.clone();
7776            Ok(Box::pin(async move {
7777                let result = handler(ctx, input, state).await?;
7778                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7779            }) as WorkflowFuture)
7780        });
7781
7782        let replay_name = workflow_type.clone();
7783        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7784            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7785            let state = WorkflowInstance::new(state_factory());
7786            let snapshot_state = state.clone();
7787            let snapshot: WorkflowStateSnapshot =
7788                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7789            let handler = Arc::clone(&handler);
7790            let handler_name = replay_name.clone();
7791            let future = async move {
7792                let result = handler(ctx, input, state).await?;
7793                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7794            };
7795            Ok(ReplayedWorkflowInvocation {
7796                future: Box::pin(future),
7797                snapshot,
7798            })
7799        });
7800
7801        self.workflows.insert(
7802            workflow_type,
7803            RegisteredWorkflow {
7804                execute,
7805                replay: Some(replay),
7806                state_type: Some(TypeId::of::<S>()),
7807                definition_fingerprint: None,
7808            },
7809        );
7810    }
7811
7812    /// Declare the signal names consumed by a registered workflow.
7813    ///
7814    /// Call this after registering the workflow and before starting the worker.
7815    /// Names read through `wait_signal` or `signals` need a declaration for
7816    /// Server command admission. Arguments remain arbitrary positional values,
7817    /// including lossless Avro values. This replaces the previous declaration;
7818    /// an empty slice declares no signals. Names are sorted and deduplicated.
7819    /// Existing runs retain the declarations captured when they started.
7820    pub fn declare_workflow_signals(
7821        &mut self,
7822        workflow_type: &str,
7823        signal_names: &[&str],
7824    ) -> Result<()> {
7825        if !self.workflows.contains_key(workflow_type) {
7826            return Err(Error::Codec(format!(
7827                "workflow type {workflow_type:?} is not registered"
7828            )));
7829        }
7830        if signal_names
7831            .iter()
7832            .any(|name| name.is_empty() || *name != name.trim())
7833        {
7834            return Err(Error::Codec(
7835                "signal names must be non-empty and have no surrounding whitespace".into(),
7836            ));
7837        }
7838        let mut names = signal_names
7839            .iter()
7840            .map(|name| (*name).to_string())
7841            .collect::<Vec<_>>();
7842        names.sort();
7843        names.dedup();
7844        self.signals.insert(workflow_type.to_string(), names);
7845        Ok(())
7846    }
7847
7848    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7849    ///
7850    /// Supply `include_str!` values for the workflow body and every helper whose
7851    /// behavior can affect replay. Register the workflow once, then set its
7852    /// identity before starting the worker. Duplicate registrations are invalid. The server
7853    /// rejects reusing a worker ID when its prior fingerprint disappears.
7854    /// Workflows without source identity remain runnable but cannot be safely redriven.
7855    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7856    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7857    pub fn set_workflow_definition_sources(
7858        &mut self,
7859        workflow_type: &str,
7860        sources: &[&str],
7861    ) -> Result<()> {
7862        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7863            return Err(Error::Codec(
7864                "workflow definition sources must be non-empty".to_string(),
7865            ));
7866        }
7867        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7868            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7869        })?;
7870        let mut hasher = Sha256::new();
7871        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7872        hasher.update((workflow_type.len() as u64).to_be_bytes());
7873        hasher.update(workflow_type.as_bytes());
7874        for source in sources {
7875            hasher.update((source.len() as u64).to_be_bytes());
7876            hasher.update(source.as_bytes());
7877        }
7878        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7879        Ok(())
7880    }
7881
7882    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7883    #[track_caller]
7884    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7885        &mut self,
7886        workflow_type: impl Into<String>,
7887        state_factory: Factory,
7888        handler: F,
7889    ) where
7890        S: Clone + Send + Sync + 'static,
7891        Factory: Fn() -> S + Send + Sync + 'static,
7892        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7893        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7894    {
7895        let workflow_type = workflow_type.into();
7896        if !self.admit_registration::<F>(
7897            RegistrationKind::Workflow,
7898            None,
7899            &workflow_type,
7900            "register_replayed_workflow_avro_value",
7901        ) {
7902            return;
7903        }
7904        let state_factory = Arc::new(state_factory);
7905        let handler = Arc::new(handler);
7906
7907        let execute_factory = Arc::clone(&state_factory);
7908        let execute_handler = Arc::clone(&handler);
7909        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7910            let state = WorkflowInstance::new(execute_factory());
7911            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7912        });
7913
7914        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7915            let state = WorkflowInstance::new(state_factory());
7916            let snapshot_state = state.clone();
7917            let snapshot: WorkflowStateSnapshot =
7918                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7919            Ok(ReplayedWorkflowInvocation {
7920                future: Box::pin(handler(ctx, input, state)),
7921                snapshot,
7922            })
7923        });
7924
7925        self.workflows.insert(
7926            workflow_type,
7927            RegisteredWorkflow {
7928                execute,
7929                replay: Some(replay),
7930                state_type: Some(TypeId::of::<S>()),
7931                definition_fingerprint: None,
7932            },
7933        );
7934    }
7935
7936    #[track_caller]
7937    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7938    where
7939        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7940        Fut: Future<Output = Result<Value>> + Send + 'static,
7941    {
7942        let activity_type = activity_type.into();
7943        if !self.admit_registration::<F>(
7944            RegistrationKind::Activity,
7945            None,
7946            &activity_type,
7947            "register_activity",
7948        ) {
7949            return;
7950        }
7951        let handler = Arc::new(handler);
7952        self.activities.insert(
7953            activity_type,
7954            Arc::new(move |ctx, args| {
7955                let handler = Arc::clone(&handler);
7956                Box::pin(async move {
7957                    let result = handler(ctx, args.into_json()?).await?;
7958                    AvroValue::from_serialize(&result)
7959                })
7960            }),
7961        );
7962    }
7963
7964    /// Register an activity with one Serde request value and a Serde result.
7965    ///
7966    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7967    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7968    /// with the activity name and Rust type.
7969    #[track_caller]
7970    pub fn register_typed_activity<I, O, F, Fut>(
7971        &mut self,
7972        activity_type: impl Into<String>,
7973        handler: F,
7974    ) where
7975        I: DeserializeOwned + Send + 'static,
7976        O: Serialize + Send + 'static,
7977        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7978        Fut: Future<Output = Result<O>> + Send + 'static,
7979    {
7980        let activity_type = activity_type.into();
7981        if !self.admit_registration::<F>(
7982            RegistrationKind::Activity,
7983            None,
7984            &activity_type,
7985            "register_typed_activity",
7986        ) {
7987            return;
7988        }
7989        let handler_name = activity_type.clone();
7990        let handler = Arc::new(handler);
7991        self.activities.insert(
7992            activity_type,
7993            Arc::new(move |ctx, input| {
7994                let handler = Arc::clone(&handler);
7995                let handler_name = handler_name.clone();
7996                Box::pin(async move {
7997                    let input =
7998                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7999                    let result = handler(ctx, input).await?;
8000                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
8001                })
8002            }),
8003        );
8004    }
8005
8006    /// Register an activity on the lossless fixed Avro Value surface.
8007    #[track_caller]
8008    pub fn register_activity_avro_value<F, Fut>(
8009        &mut self,
8010        activity_type: impl Into<String>,
8011        handler: F,
8012    ) where
8013        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
8014        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8015    {
8016        let activity_type = activity_type.into();
8017        if !self.admit_registration::<F>(
8018            RegistrationKind::Activity,
8019            None,
8020            &activity_type,
8021            "register_activity_avro_value",
8022        ) {
8023            return;
8024        }
8025        self.activities.insert(
8026            activity_type,
8027            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8028        );
8029    }
8030
8031    /// Register a named, read-only query handler for a workflow type.
8032    ///
8033    /// The workflow type must also be registered with [`Worker::register_workflow`]
8034    /// before the worker runs. The handler receives only an immutable committed
8035    /// state snapshot and normalized query arguments.
8036    #[track_caller]
8037    pub fn register_query<F, Fut>(
8038        &mut self,
8039        workflow_type: impl Into<String>,
8040        query_name: impl Into<String>,
8041        handler: F,
8042    ) where
8043        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8044        Fut: Future<Output = Result<Value>> + Send + 'static,
8045    {
8046        let workflow_type = workflow_type.into();
8047        let query_name = query_name.into();
8048        if !self.admit_registration::<F>(
8049            RegistrationKind::Query,
8050            Some(&workflow_type),
8051            &query_name,
8052            "register_query",
8053        ) {
8054            return;
8055        }
8056        let handler = Arc::new(handler);
8057        self.queries.entry(workflow_type).or_default().insert(
8058            query_name,
8059            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
8060                let handler = Arc::clone(&handler);
8061                Box::pin(async move {
8062                    let result = handler(ctx, args.into_json()?).await?;
8063                    AvroValue::from_serialize(&result)
8064                })
8065            })),
8066        );
8067    }
8068
8069    /// Register a query handler on the lossless fixed Avro Value surface.
8070    #[track_caller]
8071    pub fn register_query_avro_value<F, Fut>(
8072        &mut self,
8073        workflow_type: impl Into<String>,
8074        query_name: impl Into<String>,
8075        handler: F,
8076    ) where
8077        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8078        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8079    {
8080        let workflow_type = workflow_type.into();
8081        let query_name = query_name.into();
8082        if !self.admit_registration::<F>(
8083            RegistrationKind::Query,
8084            Some(&workflow_type),
8085            &query_name,
8086            "register_query_avro_value",
8087        ) {
8088            return;
8089        }
8090        self.queries.entry(workflow_type).or_default().insert(
8091            query_name,
8092            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
8093        );
8094    }
8095
8096    /// Register a named query against deterministically replayed instance state.
8097    ///
8098    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
8099    /// same state type `S`. The handler receives an immutable, detached state
8100    /// clone, so successful and failed queries cannot affect workflow execution
8101    /// or the state reconstructed by a later query.
8102    #[track_caller]
8103    pub fn register_replayed_query<S, F, Fut>(
8104        &mut self,
8105        workflow_type: impl Into<String>,
8106        query_name: impl Into<String>,
8107        handler: F,
8108    ) where
8109        S: Clone + Send + Sync + 'static,
8110        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
8111        Fut: Future<Output = Result<Value>> + Send + 'static,
8112    {
8113        let workflow_type = workflow_type.into();
8114        let query_name = query_name.into();
8115        if !self.admit_registration::<F>(
8116            RegistrationKind::Query,
8117            Some(&workflow_type),
8118            &query_name,
8119            "register_replayed_query",
8120        ) {
8121            return;
8122        }
8123        let handler = Arc::new(handler);
8124        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8125            let state = state.downcast::<S>().map_err(|_| {
8126                "registered query state type does not match the replayed workflow state".to_string()
8127            })?;
8128            let handler = Arc::clone(&handler);
8129            Ok(Box::pin(async move {
8130                let result = handler(ctx, state, args.into_json()?).await?;
8131                AvroValue::from_serialize(&result)
8132            }))
8133        });
8134
8135        self.queries.entry(workflow_type).or_default().insert(
8136            query_name,
8137            RegisteredQuery::Replayed {
8138                state_type: TypeId::of::<S>(),
8139                handler: erased_handler,
8140            },
8141        );
8142    }
8143
8144    /// Register a replayed-state query on the lossless fixed Avro Value surface.
8145    #[track_caller]
8146    pub fn register_replayed_query_avro_value<S, F, Fut>(
8147        &mut self,
8148        workflow_type: impl Into<String>,
8149        query_name: impl Into<String>,
8150        handler: F,
8151    ) where
8152        S: Clone + Send + Sync + 'static,
8153        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
8154        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8155    {
8156        let workflow_type = workflow_type.into();
8157        let query_name = query_name.into();
8158        if !self.admit_registration::<F>(
8159            RegistrationKind::Query,
8160            Some(&workflow_type),
8161            &query_name,
8162            "register_replayed_query_avro_value",
8163        ) {
8164            return;
8165        }
8166        let handler = Arc::new(handler);
8167        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8168            let state = state.downcast::<S>().map_err(|_| {
8169                "registered query state type does not match the replayed workflow state".to_string()
8170            })?;
8171            Ok(Box::pin(handler(ctx, state, args)))
8172        });
8173
8174        self.queries.entry(workflow_type).or_default().insert(
8175            query_name,
8176            RegisteredQuery::Replayed {
8177                state_type: TypeId::of::<S>(),
8178                handler: erased_handler,
8179            },
8180        );
8181    }
8182
8183    /// Register a synchronous workflow update handler.
8184    #[track_caller]
8185    pub fn register_update<F, Fut>(
8186        &mut self,
8187        workflow_type: impl Into<String>,
8188        update_name: impl Into<String>,
8189        handler: F,
8190    ) where
8191        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8192        Fut: Future<Output = Result<Value>> + Send + 'static,
8193    {
8194        let workflow_type = workflow_type.into();
8195        let update_name = update_name.into();
8196        if !self.admit_registration::<F>(
8197            RegistrationKind::Update,
8198            Some(&workflow_type),
8199            &update_name,
8200            "register_update",
8201        ) {
8202            return;
8203        }
8204        let handler = Arc::new(handler);
8205        self.updates.entry(workflow_type).or_default().insert(
8206            update_name,
8207            Arc::new(move |ctx, args| {
8208                let handler = Arc::clone(&handler);
8209                Box::pin(async move {
8210                    let result = handler(ctx, args.into_json()?).await?;
8211                    AvroValue::from_serialize(&result)
8212                })
8213            }),
8214        );
8215    }
8216
8217    /// Register an update handler on the lossless fixed Avro Value surface.
8218    #[track_caller]
8219    pub fn register_update_avro_value<F, Fut>(
8220        &mut self,
8221        workflow_type: impl Into<String>,
8222        update_name: impl Into<String>,
8223        handler: F,
8224    ) where
8225        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8226        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8227    {
8228        let workflow_type = workflow_type.into();
8229        let update_name = update_name.into();
8230        if !self.admit_registration::<F>(
8231            RegistrationKind::Update,
8232            Some(&workflow_type),
8233            &update_name,
8234            "register_update_avro_value",
8235        ) {
8236            return;
8237        }
8238        self.updates.entry(workflow_type).or_default().insert(
8239            update_name,
8240            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8241        );
8242    }
8243
8244    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
8245        self.validate_registration()?;
8246        self.nexus_registration_confirmed
8247            .store(false, Ordering::SeqCst);
8248        self.query_authority_confirmed
8249            .store(false, Ordering::SeqCst);
8250        if self.nexus_cooperative_cancellation_enabled {
8251            let info: Value = self
8252                .client
8253                .request_json(
8254                    reqwest::Method::GET,
8255                    "/cluster/info",
8256                    RequestProtocol::Worker("1.20"),
8257                    Option::<&Value>::None,
8258                )
8259                .await?;
8260            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
8261                return Err(Error::CooperativeCancellationUnavailable(
8262                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
8263                ));
8264            }
8265        }
8266        if self.require_query_task_authority {
8267            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
8268                return Err(Error::WorkerLoop(
8269                    "query authority requires worker protocol 1.20".into(),
8270                ));
8271            }
8272            // Discovery uses the Worker credential, including worker-only Clients.
8273            let discovery: Value = self
8274                .client
8275                .request_json_unresolved_with_timeout::<Value, Value>(
8276                    reqwest::Method::GET,
8277                    "/cluster/info",
8278                    RequestProtocol::Worker("1.20"),
8279                    None,
8280                    Duration::from_secs(5),
8281                )
8282                .await?;
8283            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
8284                return Err(Error::WorkerLoop(
8285                    "runtime does not advertise query_task_authority".into(),
8286                ));
8287            }
8288        }
8289        self.sticky_registration_confirmed
8290            .store(false, Ordering::SeqCst);
8291        self.session_registration_confirmed
8292            .store(false, Ordering::SeqCst);
8293        for capability in &self.resource_capabilities {
8294            worker_session::validate_resource_capability(capability)?;
8295        }
8296        self.local_registration_confirmed
8297            .store(false, Ordering::SeqCst);
8298        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
8299            return Err(Error::CooperativeCancellationUnavailable(
8300                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
8301            ));
8302        }
8303        let mut command_contracts = serde_json::Map::new();
8304        for workflow_type in self.workflows.keys() {
8305            let mut queries = self
8306                .queries
8307                .get(workflow_type)
8308                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8309                .unwrap_or_default();
8310            queries.sort();
8311            let mut updates = self
8312                .updates
8313                .get(workflow_type)
8314                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8315                .unwrap_or_default();
8316            updates.sort();
8317            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
8318            command_contracts.insert(
8319                workflow_type.clone(),
8320                json!({
8321                    "queries": queries,
8322                    "query_contracts": argument_vector_contracts(&queries),
8323                    "signals": signals,
8324                    "signal_contracts": argument_vector_contracts(&signals),
8325                    "updates": updates,
8326                    "update_contracts": argument_vector_contracts(&updates),
8327                    "update_validators": [],
8328                }),
8329            );
8330        }
8331
8332        self.cooperative_registration_confirmed
8333            .store(false, Ordering::SeqCst);
8334        #[cfg(feature = "telemetry")]
8335        if self
8336            .telemetry
8337            .as_ref()
8338            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
8339            && !self
8340                .client
8341                .observability_context_supported
8342                .load(Ordering::SeqCst)
8343        {
8344            // Optional startup discovery is bounded and cached. Its failure
8345            // cannot refuse registration or add retries to a business command.
8346            let _ = self
8347                .client
8348                .request_json_unresolved_with_timeout::<Value, Value>(
8349                    reqwest::Method::GET,
8350                    "/cluster/info",
8351                    RequestProtocol::DefaultWorker,
8352                    None,
8353                    Duration::from_secs(5),
8354                )
8355                .await;
8356        }
8357        let response = self
8358            .client
8359            .register_worker_with_definition_fingerprints(
8360                &self.worker_id,
8361                &self.task_queue,
8362                self.workflows.keys().cloned().collect(),
8363                self.activities.keys().cloned().collect(),
8364                self.max_concurrent_workflow_tasks,
8365                self.max_concurrent_activity_tasks,
8366                [
8367                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
8368                    Some("workflow_entry_arguments_validation".to_string()),
8369                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
8370                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
8371                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
8372                    self.client
8373                        .local_activities_enabled
8374                        .then(|| "local_activities".to_string()),
8375                    self.client
8376                        .worker_sessions_enabled
8377                        .then(|| "worker_sessions".to_string()),
8378                    self.client
8379                        .sticky_cache
8380                        .is_some()
8381                        .then(|| "sticky_execution".to_string()),
8382                    self.cooperative_cancellation_enabled
8383                        .then(|| "cooperative_cancellation".to_string()),
8384                    self.nexus_cooperative_cancellation_enabled
8385                        .then(|| "nexus_cooperative_cancellation".to_string()),
8386                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
8387                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
8388                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
8389                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
8390                ]
8391                .into_iter()
8392                .flatten()
8393                .chain(self.resource_capabilities.iter().cloned())
8394                .collect(),
8395                Value::Object(command_contracts),
8396                Some(
8397                    self.workflows
8398                        .iter()
8399                        .filter_map(|(workflow_type, workflow)| {
8400                            workflow
8401                                .definition_fingerprint
8402                                .as_ref()
8403                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
8404                        })
8405                        .collect(),
8406                ),
8407            )
8408            .await?;
8409        if self.cooperative_cancellation_enabled && response.registered {
8410            self.cooperative_registration_confirmed
8411                .store(true, Ordering::SeqCst);
8412        }
8413        if self.nexus_cooperative_cancellation_enabled && response.registered {
8414            self.nexus_registration_confirmed
8415                .store(true, Ordering::SeqCst);
8416        }
8417        if self.client.local_activities_enabled && response.registered {
8418            self.local_registration_confirmed
8419                .store(true, Ordering::SeqCst);
8420        }
8421        if self.client.worker_sessions_enabled && response.registered {
8422            self.session_registration_confirmed
8423                .store(true, Ordering::SeqCst);
8424        }
8425        if self.client.sticky_cache.is_some() && response.registered {
8426            self.sticky_registration_confirmed
8427                .store(true, Ordering::SeqCst);
8428        }
8429        self.query_authority_confirmed.store(
8430            response.registered
8431                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
8432                && response
8433                    .server_capabilities
8434                    .as_ref()
8435                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
8436            Ordering::SeqCst,
8437        );
8438        Ok(response)
8439    }
8440
8441    /// Run until shutdown or a terminal worker error occurs.
8442    ///
8443    /// Empty long-poll expirations do not stop the worker. Retryable poll and
8444    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
8445    /// authentication, protocol, and other non-retryable failures are returned.
8446    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
8447    /// poll and heartbeat outages beyond the ordinary retry budget.
8448    pub async fn run(&self) -> Result<()> {
8449        self.run_until(std::future::pending::<()>()).await
8450    }
8451
8452    /// Run until `shutdown` resolves or a terminal worker error occurs.
8453    ///
8454    /// This has the same liveness and terminal-error contract as [`Worker::run`].
8455    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
8456    where
8457        F: Future<Output = ()>,
8458    {
8459        let _clear_cache_on_drop =
8460            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
8461        let stop = Arc::new(AtomicBool::new(false));
8462        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
8463        let mut worker = self.with_storage_admission(Arc::clone(&stop));
8464        worker.run_stop = Some(Arc::clone(&stop));
8465        let run = worker.run_with_storage_admission(Arc::clone(&stop));
8466        tokio::pin!(run);
8467        tokio::pin!(shutdown);
8468        tokio::select! {
8469            result = &mut run => result,
8470            _ = &mut shutdown => {
8471                stop.store(true, Ordering::SeqCst);
8472                run.await
8473            }
8474        }
8475    }
8476
8477    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
8478        let mut worker = self.clone();
8479        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
8480            policy: self.retry_policy,
8481            stop,
8482            workflow_completion_retry_deadline: None,
8483        });
8484        worker
8485    }
8486
8487    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8488        let registration = self.register().await?;
8489        if !registration.registered {
8490            return Err(Error::WorkerLoop(format!(
8491                "worker registration for {:?} was not accepted",
8492                self.worker_id
8493            )));
8494        }
8495        let registered_worker_id = registration.worker_id.clone();
8496        let primary = self.run_registered_until(stop, registration).await;
8497        let primary = match (primary, self.close_worker_sessions().await) {
8498            (Ok(()), result) => result,
8499            (Err(error), Ok(())) => Err(error),
8500            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8501                primary: Box::new(primary),
8502                deregistration: Box::new(close),
8503            }),
8504        };
8505        self.session_registration_confirmed
8506            .store(false, Ordering::SeqCst);
8507        self.cooperative_registration_confirmed
8508            .store(false, Ordering::SeqCst);
8509        self.local_registration_confirmed
8510            .store(false, Ordering::SeqCst);
8511        let deregistration = self
8512            .client
8513            .deregister_worker_registration(&registered_worker_id)
8514            .await;
8515        self.sticky_registration_confirmed
8516            .store(false, Ordering::SeqCst);
8517        self.client.clear_sticky_cache()?;
8518
8519        match (primary, deregistration) {
8520            (Ok(()), Ok(_)) => Ok(()),
8521            (Ok(()), Err(deregistration)) => Err(deregistration),
8522            (Err(primary), Ok(_)) => Err(primary),
8523            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8524                primary: Box::new(primary),
8525                deregistration: Box::new(deregistration),
8526            }),
8527        }
8528    }
8529
8530    async fn run_registered_until(
8531        &self,
8532        stop: Arc<AtomicBool>,
8533        registration: RegisterWorkerResponse,
8534    ) -> Result<()> {
8535        if self.require_query_task_authority
8536            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8537        {
8538            return Err(Error::WorkerLoop(
8539                "registration did not confirm query_task_authority".into(),
8540            ));
8541        }
8542        let heartbeat_interval = Duration::from_secs(
8543            registration
8544                .heartbeat_interval_seconds
8545                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8546        );
8547        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8548        // from the completion of the preceding attempt, including its bounded
8549        // retries. A fixed-epoch interval can leave an already-due tick queued
8550        // while an acknowledgement is slow, producing a catch-up heartbeat as
8551        // soon as that request completes.
8552        let heartbeat = tokio::time::sleep(Duration::ZERO);
8553        tokio::pin!(heartbeat);
8554        // Poll responses may already have leased server-side work by the time
8555        // they become ready, so each poller owns its responses through
8556        // completion or failure instead of racing raw polls in this select.
8557        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
8558            let worker = self.clone();
8559            let stop = Arc::clone(&stop);
8560            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
8561        });
8562        let mut activity_poller = (!self.activities.is_empty()).then(|| {
8563            let worker = self.clone();
8564            let stop = Arc::clone(&stop);
8565            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
8566        });
8567        let mut query_poller = (!self.queries.is_empty()).then(|| {
8568            let worker = self.clone();
8569            let stop = Arc::clone(&stop);
8570            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
8571        });
8572
8573        loop {
8574            tokio::select! {
8575                _ = wait_for_worker_stop(&stop) => {
8576                    stop.store(true, Ordering::SeqCst);
8577                    break;
8578                }
8579                _ = &mut heartbeat => {
8580                    let result = self.retry_worker_operation(|| {
8581                        self.client.heartbeat_worker_with_sessions(
8582                            &self.worker_id,
8583                            self.max_concurrent_workflow_tasks,
8584                            self.max_concurrent_activity_tasks,
8585                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8586                        )
8587                    }).await;
8588                    heartbeat
8589                        .as_mut()
8590                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8591                    match result {
8592                        Ok(Some(acknowledgement)) => {
8593                            if let Some(observer) = &self.heartbeat_observer {
8594                                observer(&WorkerHeartbeatObservation {
8595                                    worker_id: self.worker_id.clone(),
8596                                    task_queue: self.task_queue.clone(),
8597                                    acknowledged_at_unix_millis: SystemTime::now()
8598                                        .duration_since(UNIX_EPOCH)
8599                                        .unwrap_or_default()
8600                                        .as_millis()
8601                                        .min(u64::MAX as u128)
8602                                        as u64,
8603                                    acknowledgement,
8604                                });
8605                            }
8606                        }
8607                        Ok(None) => break,
8608                        Err(error) => {
8609                            stop.store(true, Ordering::SeqCst);
8610                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8611                            return Err(error);
8612                        }
8613                    }
8614                }
8615                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8616                    workflow_poller = None;
8617                    let stopped_by_server = stop.load(Ordering::SeqCst);
8618                    stop.store(true, Ordering::SeqCst);
8619                    let poller_result = optional_poller_result("workflow", result);
8620                    let join_result =
8621                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8622                    poller_result?;
8623                    join_result?;
8624                    if stopped_by_server {
8625                        return Ok(());
8626                    }
8627                    return Err(Error::WorkerLoop(
8628                        "workflow poller stopped unexpectedly".to_string(),
8629                    ));
8630                }
8631                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8632                    activity_poller = None;
8633                    let stopped_by_server = stop.load(Ordering::SeqCst);
8634                    stop.store(true, Ordering::SeqCst);
8635                    let poller_result = optional_poller_result("activity", result);
8636                    let join_result =
8637                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8638                    poller_result?;
8639                    join_result?;
8640                    if stopped_by_server {
8641                        return Ok(());
8642                    }
8643                    return Err(Error::WorkerLoop(
8644                        "activity poller stopped unexpectedly".to_string(),
8645                    ));
8646                }
8647                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8648                    query_poller = None;
8649                    let stopped_by_server = stop.load(Ordering::SeqCst);
8650                    stop.store(true, Ordering::SeqCst);
8651                    let poller_result = optional_poller_result("query", 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                        "query poller stopped unexpectedly".to_string(),
8661                    ));
8662                }
8663            }
8664        }
8665
8666        join_pollers(
8667            workflow_poller.take(),
8668            activity_poller.take(),
8669            query_poller.take(),
8670        )
8671        .await
8672    }
8673
8674    /// Poll and settle at most one task from each enabled task family.
8675    ///
8676    /// A workflow may reach its server-enforced run deadline while this worker
8677    /// holds a task. When the completion endpoint authoritatively rejects that
8678    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8679    /// terminal `run_status=failed`, the workflow tick is considered settled:
8680    /// the late command was not recorded and cannot replace the terminal run.
8681    /// Every other completion rejection remains an error. This worker-level
8682    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8683    /// only bounds how long a client waits for a result.
8684    ///
8685    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8686    /// the original [`Error::Http`] status and response body.
8687    pub async fn run_once(&self) -> Result<usize> {
8688        self.validate_registration()?;
8689        if self.client.worker_sessions_enabled {
8690            self.require_session_registration()?;
8691        }
8692        if self.cooperative_cancellation_enabled
8693            && !self
8694                .cooperative_registration_confirmed
8695                .load(Ordering::SeqCst)
8696        {
8697            return Err(Error::CooperativeCancellationUnavailable(
8698                "register this cooperative worker before polling tasks".into(),
8699            ));
8700        }
8701        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8702        let mut handled = 0;
8703        match worker.poll_workflow_once().await? {
8704            ManagedPollOutcome::Handled => handled += 1,
8705            ManagedPollOutcome::Stop => return Ok(handled),
8706            ManagedPollOutcome::Idle => {}
8707        }
8708        match worker.poll_activity_once().await? {
8709            ManagedPollOutcome::Handled => handled += 1,
8710            ManagedPollOutcome::Stop => return Ok(handled),
8711            ManagedPollOutcome::Idle => {}
8712        }
8713        if !self.queries.is_empty() {
8714            match worker.poll_query_once().await? {
8715                ManagedPollOutcome::Handled => handled += 1,
8716                ManagedPollOutcome::Stop => return Ok(handled),
8717                ManagedPollOutcome::Idle => {}
8718            }
8719        }
8720        Ok(handled)
8721    }
8722
8723    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
8724        if self.client.sticky_cache.is_some()
8725            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8726        {
8727            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8728        }
8729        if self.client.local_activities_enabled
8730            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8731        {
8732            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8733        }
8734        if self.cooperative_cancellation_enabled {
8735            return self.poll_cooperative_workflow_once().await;
8736        }
8737        let poll_request_id = unique_request_id("rust-workflow-poll");
8738        let response = self
8739            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8740            .await;
8741        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8742            return Ok(ManagedPollOutcome::Idle);
8743        };
8744        if response.outcome().should_stop() {
8745            return Ok(ManagedPollOutcome::Stop);
8746        }
8747        let memo_updates_supported =
8748            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8749        let Some(task) = response.task else {
8750            return Ok(ManagedPollOutcome::Idle);
8751        };
8752
8753        let task_id = task.task_id.clone();
8754        let attempt = task.workflow_task_attempt;
8755        let run_id = task.run_id.clone();
8756        let lease_owner = task
8757            .lease_owner
8758            .clone()
8759            .unwrap_or_else(|| self.worker_id.clone());
8760
8761        let decision = match self.execute_workflow_with_local_activities(task).await {
8762            Ok(Some(decision)) => Ok(decision),
8763            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8764            Err(error) => Err(error),
8765        };
8766        self.settle_workflow_task_decision(
8767            &task_id,
8768            &lease_owner,
8769            attempt,
8770            run_id.as_deref(),
8771            decision,
8772            memo_updates_supported,
8773            snapshot,
8774        )
8775        .await
8776    }
8777
8778    #[allow(clippy::too_many_arguments)]
8779    async fn settle_workflow_task_decision(
8780        &self,
8781        task_id: &str,
8782        lease_owner: &str,
8783        attempt: u64,
8784        run_id: Option<&str>,
8785        decision: Result<WorkflowTaskDecision>,
8786        memo_updates_supported: bool,
8787        snapshot: Option<sticky_worker::StickySnapshot>,
8788    ) -> Result<ManagedPollOutcome> {
8789        match decision {
8790            Ok(decision)
8791                if decision.cancellation_delivery.is_some()
8792                    || decision.cancellation_scope_delivery.is_some()
8793                    || decision.cancellation_scope_opening.is_some() =>
8794            {
8795                return Err(Error::CooperativeCancellationUnavailable(
8796                    "worker cancellation delivery has not been negotiated".into(),
8797                ));
8798            }
8799            Ok(decision)
8800                if commands_use_workflow_memo_updates(&decision.commands)
8801                    && !memo_updates_supported =>
8802            {
8803                self.client
8804                    .fail_workflow_task(
8805                        task_id,
8806                        lease_owner,
8807                        attempt,
8808                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8809                    )
8810                    .await?;
8811            }
8812            Ok(decision) if decision.commands.is_empty() => {
8813                // A replay can consume a recorded pending durable command
8814                // without producing a new command. The standalone protocol
8815                // acknowledges that state through the typed waiting outcome;
8816                // an empty completion is rejected by servers that require at
8817                // least one executable command.
8818                self.client
8819                    .fail_workflow_task_with_type(
8820                        task_id,
8821                        lease_owner,
8822                        attempt,
8823                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8824                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8825                    )
8826                    .await?;
8827            }
8828            Ok(decision) => {
8829                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8830                let completion = self
8831                    .client
8832                    .complete_workflow_task_with_message_streams(
8833                        task_id,
8834                        lease_owner,
8835                        attempt,
8836                        decision.commands,
8837                        decision.message_stream_cursors,
8838                        decision.message_stream_waits,
8839                        sticky_claim,
8840                    )
8841                    .await;
8842                if let Err(error) = completion {
8843                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8844                    if !workflow_task_completion_is_terminal_timeout(
8845                        &error, task_id, attempt, run_id,
8846                    ) {
8847                        return Err(error);
8848                    }
8849                }
8850            }
8851            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8852            Err(error) => {
8853                self.discard_sticky_snapshot(snapshot.as_ref())?;
8854                if matches!(
8855                    error,
8856                    Error::HandlerType {
8857                        handler_kind: HandlerKind::Workflow,
8858                        value_kind: HandlerValueKind::Input,
8859                        ..
8860                    }
8861                ) {
8862                    self.client
8863                        .fail_workflow_task_with_failure(
8864                            task_id,
8865                            lease_owner,
8866                            attempt,
8867                            json!({
8868                                "message": error.to_string(),
8869                                "type": "WorkflowEntryArgumentsMismatch",
8870                                "reason": "workflow_entry_arguments_mismatch",
8871                            }),
8872                        )
8873                        .await?;
8874                } else {
8875                    self.client
8876                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8877                        .await?;
8878                }
8879            }
8880        }
8881
8882        Ok(ManagedPollOutcome::Handled)
8883    }
8884
8885    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8886        while !stop.load(Ordering::SeqCst) {
8887            match self.poll_workflow_once().await {
8888                Ok(ManagedPollOutcome::Stop) => {
8889                    stop.store(true, Ordering::SeqCst);
8890                    break;
8891                }
8892                Err(error) => {
8893                    stop.store(true, Ordering::SeqCst);
8894                    return Err(error);
8895                }
8896                _ => {}
8897            }
8898        }
8899
8900        Ok(())
8901    }
8902
8903    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8904        if self.client.worker_sessions_enabled {
8905            self.require_session_registration()?;
8906        }
8907        let poll_request_id = unique_request_id("rust-activity-poll");
8908        let response = self
8909            .retry_worker_operation(|| {
8910                self.client.poll_activity_task_response_with_request_id(
8911                    &self.worker_id,
8912                    &self.task_queue,
8913                    self.poll_timeout,
8914                    &poll_request_id,
8915                    0,
8916                )
8917            })
8918            .await;
8919        let response = match response {
8920            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8921            response => response,
8922        };
8923        let Some(response) = self.settle_worker_poll_response(response).await? else {
8924            return Ok(ManagedPollOutcome::Idle);
8925        };
8926        if response.outcome().should_stop() {
8927            return Ok(ManagedPollOutcome::Stop);
8928        }
8929        let Some(task) = response.task else {
8930            return Ok(ManagedPollOutcome::Idle);
8931        };
8932
8933        self.settle_polled_activity(task).await
8934    }
8935
8936    async fn settle_polled_activity(
8937        &self,
8938        task: worker_session::SessionActivityTask,
8939    ) -> Result<ManagedPollOutcome> {
8940        let lease = task.activity_lease.clone();
8941        let mut worker = self.clone();
8942        worker.client = self.client.with_activity_lease_authority(
8943            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
8944        );
8945        let operation = worker.execute_polled_activity(task);
8946        let result = match lease.as_ref() {
8947            Some(lease) => lease.authority.protect(operation).await,
8948            None => operation.await,
8949        };
8950        match result {
8951            Err(Error::ActivityExecutionAbandoned(_)) => Ok(ManagedPollOutcome::Handled),
8952            result => result,
8953        }
8954    }
8955
8956    async fn execute_polled_activity(
8957        &self,
8958        task: worker_session::SessionActivityTask,
8959    ) -> Result<ManagedPollOutcome> {
8960        if self.cooperative_cancellation_enabled {
8961            return self.settle_cooperative_activity(task).await;
8962        }
8963        let session = self.track_session_task(task.worker_session.as_ref())?;
8964        let hydration_claim = task.hydration_claim;
8965        let task = task.task;
8966
8967        let task_id = task.task_id.clone();
8968        let attempt_id = task
8969            .activity_attempt_id
8970            .clone()
8971            .or(task.attempt_id.clone())
8972            .unwrap_or_default();
8973        let lease_owner = task
8974            .lease_owner
8975            .clone()
8976            .unwrap_or_else(|| self.worker_id.clone());
8977        let codec = task.payload_codec.clone();
8978        let result = self
8979            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8980            .await;
8981        match result {
8982            Err(Error::ActivityExecutionAbandoned(_)) => {}
8983            Err(error) if activity_hydration::stopped(&error) => {}
8984            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8985            Ok(value) => {
8986                let completion = self
8987                    .client
8988                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8989                    .await;
8990                if let Err(error) = completion {
8991                    if !activity_task_rejection_is_final(&error) {
8992                        return Err(error);
8993                    }
8994                }
8995            }
8996            Err(error) => {
8997                let failure = self
8998                    .client
8999                    .fail_activity_task_with_error(
9000                        &task_id,
9001                        &attempt_id,
9002                        &lease_owner,
9003                        &ActivityError::from_error(&error, "RustActivityFailure"),
9004                    )
9005                    .await;
9006                if let Err(error) = failure {
9007                    if !activity_task_rejection_is_final(&error) {
9008                        return Err(error);
9009                    }
9010                }
9011            }
9012        }
9013
9014        Ok(ManagedPollOutcome::Handled)
9015    }
9016
9017    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
9018        // Each lane retains its leased response through callback settlement.
9019        // A bounded independent activity must not occupy the cleanup lane too.
9020        // Preserve the existing serial loop unless cooperation is enabled.
9021        let lane_count = if self.cooperative_cancellation_enabled {
9022            self.max_concurrent_activity_tasks
9023        } else {
9024            1
9025        };
9026        let mut lanes = FuturesUnordered::new();
9027        for _ in 0..lane_count {
9028            let worker = self.clone();
9029            let stop = Arc::clone(&stop);
9030            lanes.push(async move {
9031                while !stop.load(Ordering::SeqCst) {
9032                    match worker.poll_activity_once().await {
9033                        Ok(ManagedPollOutcome::Stop) => {
9034                            stop.store(true, Ordering::SeqCst);
9035                            break;
9036                        }
9037                        Err(error) => {
9038                            stop.store(true, Ordering::SeqCst);
9039                            return Err(error);
9040                        }
9041                        _ => {}
9042                    }
9043                }
9044                Ok(())
9045            });
9046        }
9047        // Join every lane before deregistration, including after one fails.
9048        let mut first_error = None;
9049        while let Some(result) = lanes.next().await {
9050            if let Err(error) = result {
9051                first_error.get_or_insert(error);
9052            }
9053        }
9054        first_error.map_or(Ok(()), Err)
9055    }
9056
9057    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
9058        let poll_request_id = unique_request_id("rust-query-poll");
9059        let response = self
9060            .retry_worker_operation(|| {
9061                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
9062                    "poll_request_id":poll_request_id,
9063                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
9064                async move {
9065                    self.client
9066                        .poll_request_json_unresolved::<Value, Value>(
9067                            "/worker/query-tasks/poll",
9068                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
9069                            &body,
9070                            self.poll_timeout + Duration::from_secs(5),
9071                            0,
9072                        )
9073                        .await
9074                }
9075            })
9076            .await;
9077        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
9078            return Ok(ManagedPollOutcome::Idle);
9079        };
9080        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
9081            match query_authority::Authority::capture(&wire["task"], self) {
9082                Ok(authority) => authority,
9083                Err(_) => return Ok(ManagedPollOutcome::Handled),
9084            }
9085        } else {
9086            None
9087        };
9088        let loading = self.client.resolve_runtime_payloads(
9089            &mut wire,
9090            "/worker/query-tasks/poll",
9091            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
9092        );
9093        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
9094            Err(_) => return Ok(ManagedPollOutcome::Handled),
9095            Ok(result) => result?,
9096        }
9097        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
9098        if response.outcome().should_stop() {
9099            return Ok(ManagedPollOutcome::Stop);
9100        }
9101        let Some(task) = response.task else {
9102            return Ok(ManagedPollOutcome::Idle);
9103        };
9104
9105        let query_task_id = task.query_task_id.clone();
9106        let attempt = task.query_task_attempt;
9107        let lease_owner = task
9108            .lease_owner
9109            .clone()
9110            .unwrap_or_else(|| self.worker_id.clone());
9111        let codec = task.payload_codec.clone();
9112
9113        let execution = query_authority::Authority::protect(
9114            authority.as_ref(),
9115            self,
9116            self.execute_query_task_with_authority(task, authority.as_ref()),
9117        )
9118        .await;
9119        let execution = match execution {
9120            Err(_) => return Ok(ManagedPollOutcome::Handled),
9121            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
9122                return Ok(ManagedPollOutcome::Handled)
9123            }
9124            Ok(result) => result,
9125        };
9126        match execution {
9127            Ok(value) => {
9128                let result_envelope = match encode_typed_envelope(&value, &codec) {
9129                    Ok(result_envelope) => result_envelope,
9130                    Err(error) => {
9131                        let failure = query_authority::Authority::protect(
9132                            authority.as_ref(),
9133                            self,
9134                            self.client.fail_query_task(
9135                                &query_task_id,
9136                                &lease_owner,
9137                                attempt,
9138                                error.to_string(),
9139                                "query_result_encode_failed",
9140                                "QueryResultEncodeFailed",
9141                            ),
9142                        )
9143                        .await;
9144                        let Ok(failure) = failure else {
9145                            return Ok(ManagedPollOutcome::Handled);
9146                        };
9147                        if let Err(error) = failure {
9148                            if !query_task_rejection_is_final(&error) {
9149                                return Err(error);
9150                            }
9151                        }
9152                        return Ok(ManagedPollOutcome::Handled);
9153                    }
9154                };
9155
9156                let completion = query_authority::Authority::protect(
9157                    authority.as_ref(),
9158                    self,
9159                    self.client.complete_query_task_with_envelope(
9160                        &query_task_id,
9161                        &lease_owner,
9162                        attempt,
9163                        value.clone().into_json()?,
9164                        result_envelope,
9165                    ),
9166                )
9167                .await;
9168                let Ok(completion) = completion else {
9169                    return Ok(ManagedPollOutcome::Handled);
9170                };
9171                if let Err(error) = completion {
9172                    if !query_task_rejection_is_final(&error) {
9173                        return Err(error);
9174                    }
9175                }
9176            }
9177            Err(failure) => {
9178                let result = query_authority::Authority::protect(
9179                    authority.as_ref(),
9180                    self,
9181                    self.client.fail_query_task(
9182                        &query_task_id,
9183                        &lease_owner,
9184                        attempt,
9185                        failure.message,
9186                        failure.reason,
9187                        failure.failure_type,
9188                    ),
9189                )
9190                .await;
9191                let Ok(result) = result else {
9192                    return Ok(ManagedPollOutcome::Handled);
9193                };
9194                if let Err(error) = result {
9195                    if !query_task_rejection_is_final(&error) {
9196                        return Err(error);
9197                    }
9198                }
9199            }
9200        }
9201
9202        Ok(ManagedPollOutcome::Handled)
9203    }
9204
9205    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
9206        while !stop.load(Ordering::SeqCst) {
9207            match self.poll_query_once().await {
9208                Ok(ManagedPollOutcome::Stop) => {
9209                    stop.store(true, Ordering::SeqCst);
9210                    break;
9211                }
9212                Err(error) => {
9213                    stop.store(true, Ordering::SeqCst);
9214                    return Err(error);
9215                }
9216                _ => {}
9217            }
9218        }
9219
9220        Ok(())
9221    }
9222
9223    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
9224    where
9225        F: FnMut() -> Fut,
9226        Fut: Future<Output = Result<T>>,
9227    {
9228        let mut retries = 0;
9229
9230        loop {
9231            if self
9232                .run_stop
9233                .as_ref()
9234                .is_some_and(|stop| stop.load(Ordering::SeqCst))
9235            {
9236                return Ok(None);
9237            }
9238            match operation().await {
9239                Err(error)
9240                    if (workflow_hydration::stopped(&error)
9241                        || activity_hydration::stopped(&error))
9242                        && self
9243                            .run_stop
9244                            .as_ref()
9245                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
9246                {
9247                    return Ok(None);
9248                }
9249                Err(error)
9250                    if worker_operation_is_retryable(&error)
9251                        && (retries < self.retry_policy.max_retries
9252                            || (self.recover_transient_outages
9253                                && self.run_stop.is_some()
9254                                && self.retry_policy.max_retries > 0)) =>
9255                {
9256                    retries = retries.saturating_add(1);
9257                    let delay = worker_retry_delay(self.retry_policy, retries)
9258                        .max(Duration::from_millis(1));
9259                    if let Some(stop) = &self.run_stop {
9260                        tokio::select! {
9261                            _ = tokio::time::sleep(delay) => {}
9262                            _ = wait_for_worker_stop(stop) => return Ok(None),
9263                        }
9264                    } else {
9265                        tokio::time::sleep(delay).await;
9266                    }
9267                }
9268                result => return result.map(Some),
9269            }
9270        }
9271    }
9272
9273    async fn settle_worker_poll_response<T>(
9274        &self,
9275        response: Result<Option<T>>,
9276    ) -> Result<Option<T>> {
9277        match response {
9278            Ok(response) => Ok(response),
9279            Err(error) => {
9280                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
9281                    return Err(error);
9282                };
9283                let minimum_delay = self
9284                    .retry_policy
9285                    .initial_backoff
9286                    .max(Duration::from_millis(1));
9287                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
9288                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
9289                Ok(None)
9290            }
9291        }
9292    }
9293
9294    #[cfg(test)]
9295    async fn execute_query_task(
9296        &self,
9297        task: QueryTask,
9298    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9299        self.execute_query_task_with_authority(task, None).await
9300    }
9301
9302    async fn execute_query_task_with_authority(
9303        &self,
9304        task: QueryTask,
9305        authority: Option<&query_authority::Authority>,
9306    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9307        #[cfg(feature = "telemetry")]
9308        if let Some(telemetry) = &self.telemetry {
9309            return telemetry
9310                .run_observed(
9311                    "durable.query.task",
9312                    self.query_telemetry_fields(&task),
9313                    false,
9314                    authority.and_then(|_| self.query_observations(&task)),
9315                    self.execute_query_task_inner(task, authority),
9316                )
9317                .await;
9318        }
9319        self.execute_query_task_inner(task, authority).await
9320    }
9321
9322    async fn execute_query_task_inner(
9323        &self,
9324        mut task: QueryTask,
9325        authority: Option<&query_authority::Authority>,
9326    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9327        validate_query_task_payloads(&task).map_err(|error| {
9328            QueryTaskExecutionFailure::new(
9329                "query_payload_decode_failed",
9330                error.to_string(),
9331                "QueryPayloadDecodeFailed",
9332            )
9333        })?;
9334
9335        if !self.workflows.contains_key(&task.workflow_type) {
9336            return Err(QueryTaskExecutionFailure::new(
9337                "query_workflow_type_not_registered",
9338                format!("no workflow registered for type {:?}", task.workflow_type),
9339                "WorkflowTypeNotRegistered",
9340            ));
9341        }
9342
9343        let Some(handlers) = self.queries.get(&task.workflow_type) else {
9344            return Err(QueryTaskExecutionFailure::new(
9345                "query_handler_unavailable",
9346                format!(
9347                    "query handlers are unavailable for workflow type {:?}",
9348                    task.workflow_type
9349                ),
9350                "QueryHandlerUnavailable",
9351            ));
9352        };
9353        let Some(query) = handlers.get(&task.query_name) else {
9354            return Err(QueryTaskExecutionFailure::new(
9355                "rejected_unknown_query",
9356                format!("unknown query {:?}", task.query_name),
9357                "QueryFailed",
9358            ));
9359        };
9360
9361        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
9362            .map_err(|error| {
9363            QueryTaskExecutionFailure::new(
9364                "query_payload_decode_failed",
9365                format!("cannot decode query arguments: {error}"),
9366                "QueryPayloadDecodeFailed",
9367            )
9368        })?;
9369        let workflow_input_typed =
9370            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
9371                .map_err(|error| {
9372                    QueryTaskExecutionFailure::new(
9373                        "query_workflow_state_unavailable",
9374                        format!("cannot decode workflow start input: {error}"),
9375                        "QueryWorkflowStateUnavailable",
9376                    )
9377                })?;
9378        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
9379            QueryTaskExecutionFailure::new(
9380                "query_workflow_state_unavailable",
9381                format!("cannot project workflow start input: {error}"),
9382                "QueryWorkflowStateUnavailable",
9383            )
9384        })?;
9385        hydrate_query_history_from_export(&mut task).map_err(|error| {
9386            QueryTaskExecutionFailure::new(
9387                "query_workflow_state_unavailable",
9388                format!("cannot restore query history snapshot: {error}"),
9389                "QueryWorkflowStateUnavailable",
9390            )
9391        })?;
9392        enrich_query_history_from_export(&mut task).map_err(|error| {
9393            QueryTaskExecutionFailure::new(
9394                "query_workflow_state_unavailable",
9395                format!("cannot restore compact query history payloads: {error}"),
9396                "QueryWorkflowStateUnavailable",
9397            )
9398        })?;
9399        let signal_events = query_signal_events(&task).map_err(|error| {
9400            QueryTaskExecutionFailure::new(
9401                "query_workflow_state_unavailable",
9402                format!("cannot decode committed workflow signals: {error}"),
9403                "QueryWorkflowStateUnavailable",
9404            )
9405        })?;
9406        let history_events = Arc::new(std::mem::take(&mut task.history_events));
9407        let context = QueryContext {
9408            workflow_id: task.workflow_id,
9409            run_id: task.run_id,
9410            workflow_type: task.workflow_type.clone(),
9411            run_status: task.run_status,
9412            workflow_input,
9413            workflow_input_avro_value: workflow_input_typed.clone(),
9414            history_events: Arc::clone(&history_events),
9415            signal_events: Arc::new(signal_events),
9416        };
9417
9418        let future = match query {
9419            RegisteredQuery::Snapshot(handler) => {
9420                query_authority::before_handler(authority, &self.client).await?;
9421                handler(context, args)
9422            }
9423            RegisteredQuery::Replayed {
9424                state_type,
9425                handler,
9426            } => {
9427                let workflow = self
9428                    .workflows
9429                    .get(&task.workflow_type)
9430                    .expect("workflow registration was checked above");
9431                if workflow.state_type != Some(*state_type) {
9432                    return Err(QueryTaskExecutionFailure::new(
9433                        "query_workflow_state_unavailable",
9434                        "replayed query state type does not match its workflow registration",
9435                        "QueryWorkflowStateUnavailable",
9436                    ));
9437                }
9438                let replay = workflow.replay.as_ref().ok_or_else(|| {
9439                    QueryTaskExecutionFailure::new(
9440                        "query_workflow_state_unavailable",
9441                        format!(
9442                            "workflow type {:?} is not registered for instance-state replay",
9443                            task.workflow_type
9444                        ),
9445                        "QueryWorkflowStateUnavailable",
9446                    )
9447                })?;
9448                let workflow_state = Arc::new(Mutex::new(
9449                    WorkflowState::new_with_identity(
9450                        history_events.as_ref().clone(),
9451                        context.workflow_id.clone(),
9452                        context.run_id.clone(),
9453                        self.task_queue.clone(),
9454                        task.payload_codec,
9455                        None,
9456                    )
9457                    .map_err(|error| {
9458                        QueryTaskExecutionFailure::new(
9459                            "query_workflow_state_unavailable",
9460                            format!("workflow replay failed before query: {error}"),
9461                            "QueryWorkflowStateUnavailable",
9462                        )
9463                    })?,
9464                ));
9465                let workflow_context = WorkflowContext {
9466                    state: workflow_state,
9467                    cancellation_scope_id: "root".into(),
9468                };
9469                query_authority::before_handler(authority, &self.client).await?;
9470                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone())
9471                    .map_err(|error| {
9472                        QueryTaskExecutionFailure::new(
9473                            "query_workflow_state_unavailable",
9474                            error.to_string(),
9475                            "QueryWorkflowStateUnavailable",
9476                        )
9477                    })?;
9478                let outcome = {
9479                    let mut cx = TaskContext::from_waker(noop_waker_ref());
9480                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
9481                        .map_err(|error| {
9482                            QueryTaskExecutionFailure::new(
9483                                "query_workflow_state_unavailable",
9484                                error.to_string(),
9485                                "QueryWorkflowStateUnavailable",
9486                            )
9487                        })?;
9488                    invocation.future.as_mut().poll(&mut cx)
9489                };
9490                match outcome {
9491                    Poll::Ready(Ok(_)) => {
9492                        workflow_context
9493                            .ensure_history_consumed()
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                    Poll::Ready(Err(error)) => {
9503                        return Err(QueryTaskExecutionFailure::new(
9504                            "query_workflow_state_unavailable",
9505                            format!("workflow replay failed before query: {error}"),
9506                            "QueryWorkflowStateUnavailable",
9507                        ));
9508                    }
9509                    Poll::Pending => {
9510                        let commands = workflow_context.take_commands().map_err(|error| {
9511                            QueryTaskExecutionFailure::new(
9512                                "query_workflow_state_unavailable",
9513                                format!("workflow replay failed before query: {error}"),
9514                                "QueryWorkflowStateUnavailable",
9515                            )
9516                        })?;
9517                        if commands.is_empty()
9518                            && !workflow_context
9519                                .matched_recorded_pending()
9520                                .map_err(|error| {
9521                                    QueryTaskExecutionFailure::new(
9522                                        "query_workflow_state_unavailable",
9523                                        format!("workflow replay failed before query: {error}"),
9524                                        "QueryWorkflowStateUnavailable",
9525                                    )
9526                                })?
9527                        {
9528                            return Err(QueryTaskExecutionFailure::new(
9529                                "query_workflow_state_unavailable",
9530                                "workflow replay yielded without a durable command",
9531                                "QueryWorkflowStateUnavailable",
9532                            ));
9533                        }
9534                    }
9535                }
9536                let state = (invocation.snapshot)().map_err(|error| {
9537                    QueryTaskExecutionFailure::new(
9538                        "query_workflow_state_unavailable",
9539                        format!("cannot snapshot replayed workflow state: {error}"),
9540                        "QueryWorkflowStateUnavailable",
9541                    )
9542                })?;
9543                query_authority::before_handler(authority, &self.client).await?;
9544                handler(context, state, args).map_err(|message| {
9545                    QueryTaskExecutionFailure::new(
9546                        "query_workflow_state_unavailable",
9547                        message,
9548                        "QueryWorkflowStateUnavailable",
9549                    )
9550                })?
9551            }
9552        };
9553
9554        future.await.map_err(|error| {
9555            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
9556        })
9557    }
9558
9559    #[cfg(test)]
9560    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
9561        Ok(self.execute_workflow_task_decision(task)?.commands)
9562    }
9563
9564    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
9565        self.execute_workflow_task_decision_with_cancellation(task, None)
9566    }
9567
9568    fn execute_workflow_task_decision_with_cancellation(
9569        &self,
9570        task: WorkflowTask,
9571        observation: Option<&CancellationRequest>,
9572    ) -> Result<WorkflowTaskDecision> {
9573        #[cfg(feature = "telemetry")]
9574        if let Some(telemetry) = &self.telemetry {
9575            return telemetry.run_sync_observed(
9576                "durable.workflow.task",
9577                self.workflow_telemetry_fields(&task),
9578                self.workflow_observations(&task),
9579                || {
9580                    let mut decision =
9581                        self.execute_workflow_task_decision_inner(task, observation)?;
9582                    self.stamp_observability_commands(&mut decision.commands);
9583                    Ok(decision)
9584                },
9585            );
9586        }
9587        self.execute_workflow_task_decision_inner(task, observation)
9588    }
9589
9590    fn execute_workflow_task_decision_inner(
9591        &self,
9592        task: WorkflowTask,
9593        observation: Option<&CancellationRequest>,
9594    ) -> Result<WorkflowTaskDecision> {
9595        match self.prepare_workflow_task_execution(task, observation)? {
9596            PreparedWorkflowTask::Decision(decision) => Ok(decision),
9597            PreparedWorkflowTask::Execution {
9598                task,
9599                context,
9600                mut future,
9601            } => {
9602                let outcome = Self::poll_workflow_future(&context, &mut future)?;
9603                self.finish_workflow_task_execution(&task, &context, outcome)
9604            }
9605        }
9606    }
9607
9608    fn prepare_workflow_task_execution(
9609        &self,
9610        task: WorkflowTask,
9611        observation: Option<&CancellationRequest>,
9612    ) -> Result<PreparedWorkflowTask> {
9613        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
9614            && !self.cooperative_cancellation_enabled
9615        {
9616            return Err(Error::CancellationScopeExecutionUnavailable);
9617        }
9618        validate_workflow_task_payloads(&task)?;
9619        cooperative_cancellation::assert_cancellation_scope_replay_supported(
9620            &task.history_events,
9621            self.allow_cancellation_scope_authoring,
9622            self.allow_cancellation_scope_delivery,
9623        )?;
9624        let cancellation_history = if let Some(observation) = observation {
9625            observation.validate_observation()?;
9626            cooperative_cancellation::cancellation_claim(&task)?;
9627            let canonical = CancellationHistory::from_events(
9628                &task.history_events,
9629                task.run_id.as_deref().unwrap_or_default(),
9630                Some(observation),
9631            )?;
9632            if canonical.request_index >= task.history_events.len() {
9633                return Err(Error::InvalidCooperativeCancellation(
9634                    "workflow replay requires the observed canonical request".into(),
9635                ));
9636            }
9637            Some(canonical)
9638        } else {
9639            None
9640        };
9641        if let Some(update_id) = task
9642            .workflow_update_id
9643            .as_deref()
9644            .filter(|update_id| !update_id.is_empty())
9645        {
9646            if self.allow_cancellation_scope_delivery {
9647                return Err(Error::CancellationScopeExecutionUnavailable);
9648            }
9649            CancellationHistory::from_events(
9650                &task.history_events,
9651                task.run_id.as_deref().unwrap_or_default(),
9652                None,
9653            )?;
9654            return self
9655                .execute_update_task(&task, update_id)
9656                .map(WorkflowTaskDecision::without_message_streams)
9657                .map(PreparedWorkflowTask::Decision);
9658        }
9659
9660        let workflow = self
9661            .workflows
9662            .get(&task.workflow_type)
9663            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
9664        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9665        let resume_signal = decode_resume_signal(&task)?;
9666        let history_budget = WorkflowHistoryBudget {
9667            event_count: task
9668                .total_history_events
9669                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
9670            size_bytes: task.history_size_bytes,
9671            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
9672            pressure: task.history_budget_pressure.clone(),
9673        };
9674        let workflow_command_identity = task
9675            .workflow_command_id
9676            .clone()
9677            .filter(|identity| !identity.is_empty())
9678            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
9679            .unwrap_or_default();
9680        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
9681            task.history_events.clone(),
9682            task.workflow_id.clone(),
9683            task.run_id.clone(),
9684            self.task_queue.clone(),
9685            task.payload_codec.clone(),
9686            resume_signal,
9687            self.allow_cancellation_scope_authoring,
9688            self.allow_cancellation_scope_delivery,
9689        )?;
9690        workflow_state.history_budget = history_budget;
9691        workflow_state.workflow_command_identity = workflow_command_identity;
9692        if let Some(canonical) = cancellation_history {
9693            workflow_state.cancellation_history = canonical;
9694            workflow_state.cancellation_delivery_enabled = true;
9695        }
9696        if workflow_state.cancellation_history.request.is_none() {
9697            workflow_state.cancel_requested = task.cancel_requested;
9698        }
9699        let state = Arc::new(Mutex::new(workflow_state));
9700        let ctx = WorkflowContext {
9701            state,
9702            cancellation_scope_id: "root".into(),
9703        };
9704        let future = (workflow.execute)(ctx.clone(), input)?;
9705        Ok(PreparedWorkflowTask::Execution {
9706            task,
9707            context: ctx,
9708            future,
9709        })
9710    }
9711
9712    fn poll_workflow_future(
9713        ctx: &WorkflowContext,
9714        future: &mut WorkflowFuture,
9715    ) -> Result<Poll<Result<AvroValue>>> {
9716        let mut cx = TaskContext::from_waker(noop_waker_ref());
9717        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9718        Ok(future.as_mut().poll(&mut cx))
9719    }
9720
9721    fn finish_workflow_task_execution(
9722        &self,
9723        task: &WorkflowTask,
9724        ctx: &WorkflowContext,
9725        outcome: Poll<Result<AvroValue>>,
9726    ) -> Result<WorkflowTaskDecision> {
9727        if !ctx
9728            .state
9729            .lock()
9730            .map_err(|_| Error::WorkflowStatePoisoned)?
9731            .local_activity_requests
9732            .is_empty()
9733        {
9734            return Err(Error::CooperativeCancellationUnavailable(
9735                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9736            ));
9737        }
9738        let awaiting_canonical_boundary = {
9739            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9740            state.cancellation_delivery_intent.is_some()
9741                || state.cancellation_scope_opening.is_some()
9742                || state
9743                    .scope_delivery
9744                    .as_ref()
9745                    .is_some_and(|replay| replay.intent.is_some())
9746        };
9747        if awaiting_canonical_boundary {
9748            // A private delivery intent never becomes an application error.
9749            // Even a custom future which ignores a pending durable call cannot
9750            // publish terminal commands before canonical delivery and replay.
9751            if let Poll::Ready(Err(error)) = outcome {
9752                if workflow_task_integrity_error(&error) {
9753                    return Err(error);
9754                }
9755            }
9756            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9757        }
9758
9759        match outcome {
9760            Poll::Ready(Ok(result)) => {
9761                ctx.ensure_history_consumed()?;
9762                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9763                let mut commands = ctx.take_commands()?;
9764                commands.push(json!({
9765                    "type": "complete_workflow",
9766                    "result": result
9767                }));
9768                self.message_stream_decision(&ctx, commands)
9769            }
9770            Poll::Ready(Err(error)) => {
9771                if let Error::ContinueAsNew(request) = error {
9772                    let mut commands = ctx.take_commands()?;
9773                    if let Some(command) = ctx.continue_as_new_command(request)? {
9774                        commands.push(command);
9775                    }
9776                    ctx.ensure_history_consumed()?;
9777                    return self.message_stream_decision(&ctx, commands);
9778                }
9779                if workflow_task_integrity_error(&error) {
9780                    // Replay and protocol failures describe the workflow-task
9781                    // decision itself. Preserve their specific failure reason
9782                    // instead of replacing it with the derivative fact that
9783                    // recorded commands remain unconsumed.
9784                    return Err(error);
9785                }
9786                // A handler error must not hide a committed durable command that
9787                // upgraded workflow code no longer consumes.
9788                ctx.ensure_history_consumed()?;
9789                let mut commands = ctx.take_commands()?;
9790                commands.push(workflow_failure_command(
9791                    &error,
9792                    recorded_activity_failure_boundary(&ctx, &error),
9793                ));
9794                self.message_stream_decision(&ctx, commands)
9795            }
9796            Poll::Pending => {
9797                let commands = ctx.take_commands()?;
9798                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9799                    Err(Error::WorkflowYieldedWithoutCommand)
9800                } else {
9801                    self.message_stream_decision(&ctx, commands)
9802                }
9803            }
9804        }
9805    }
9806
9807    fn message_stream_decision(
9808        &self,
9809        ctx: &WorkflowContext,
9810        commands: Vec<Value>,
9811    ) -> Result<WorkflowTaskDecision> {
9812        if !self.cooperative_cancellation_enabled
9813            && commands.iter().any(|command| {
9814                command["type"] == "schedule_activity"
9815                    && command.get("cancellation_policy").is_some()
9816            })
9817        {
9818            return Err(Error::CooperativeCancellationUnavailable(format!(
9819                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9820                self.worker_id,
9821            )));
9822        }
9823        if !self.cooperative_cancellation_enabled
9824            && commands.iter().any(|command| {
9825                command["type"] == "start_child_workflow"
9826                    && (command["parent_close_policy"] == "request_cancellation"
9827                        || matches!(
9828                            command["cancellation_policy"].as_str(),
9829                            Some("try_cancel" | "wait_cancellation_completed")
9830                        ))
9831            })
9832        {
9833            return Err(Error::CooperativeCancellationUnavailable(format!(
9834                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9835                self.worker_id,
9836            )));
9837        }
9838        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9839        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9840        let scope_delivery = state
9841            .scope_delivery
9842            .as_ref()
9843            .and_then(|replay| replay.intent.clone());
9844        if scope_delivery
9845            .as_ref()
9846            .is_some_and(|intent| commands.len() != intent.command_count)
9847        {
9848            return Err(invalid_recorded_history(
9849                "cancellation_scope_pending_call_escaped",
9850                scope_delivery.as_ref().unwrap().boundary.sequence,
9851                "commands preceding the pending scoped call",
9852                "commands after suspension",
9853                "workflow cannot publish beyond an uncommitted scope delivery",
9854            ));
9855        }
9856        if let Some(opening) = &state.cancellation_scope_opening {
9857            if commands.len() != opening.command_count {
9858                return Err(invalid_recorded_history(
9859                    "cancellation_scope_pending_call_escaped",
9860                    opening.sequence,
9861                    "commands before original scope opening",
9862                    "commands after suspended opening",
9863                    "workflow cannot publish beyond an uncommitted scope opening",
9864                ));
9865            }
9866        }
9867        if state.cancellation_delivery_intent.is_some()
9868            && commands.len() != state.cancellation_delivery_command_count
9869        {
9870            return Err(invalid_recorded_history(
9871                "cooperative_cancellation_pending_call_escaped",
9872                state
9873                    .cancellation_delivery_intent
9874                    .as_ref()
9875                    .expect("pending delivery")
9876                    .sequence,
9877                "only commands preceding the pending cancellation call",
9878                "commands authored after a suspended call",
9879                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9880            ));
9881        }
9882        Ok(WorkflowTaskDecision {
9883            commands,
9884            message_stream_cursors,
9885            message_stream_waits,
9886            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9887            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9888            cancellation_scope_delivery: scope_delivery,
9889        })
9890    }
9891
9892    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9893        if !self.workflows.contains_key(&task.workflow_type) {
9894            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9895        }
9896
9897        let accepted = task.history_events.iter().rev().find_map(|event| {
9898            (event.event_type == "UpdateAccepted"
9899                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9900            .then_some(&event.payload)
9901        });
9902        let update_name = accepted
9903            .and_then(|payload| payload.get("update_name"))
9904            .and_then(Value::as_str)
9905            .or(task.update_name.as_deref())
9906            .unwrap_or_default();
9907        let Some(handler) = self
9908            .updates
9909            .get(&task.workflow_type)
9910            .and_then(|handlers| handlers.get(update_name))
9911        else {
9912            return Ok(vec![json!({
9913                "type": "fail_update",
9914                "update_id": update_id,
9915                "message": format!(
9916                    "no update handler is registered for {}.{update_name}",
9917                    task.workflow_type
9918                ),
9919                "exception_type": "UnknownUpdate",
9920                "non_retryable": true,
9921            })]);
9922        };
9923        let arguments = accepted
9924            .and_then(|payload| payload.get("arguments"))
9925            .or(task.arguments.as_ref());
9926        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9927        let workflow_input_avro_value =
9928            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9929        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9930        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9931        let context = QueryContext {
9932            workflow_id: task.workflow_id.clone(),
9933            run_id: task.run_id.clone(),
9934            workflow_type: task.workflow_type.clone(),
9935            run_status: Some("running".to_string()),
9936            workflow_input,
9937            workflow_input_avro_value,
9938            history_events: Arc::new(task.history_events.clone()),
9939            signal_events: Arc::new(signal_events),
9940        };
9941        let mut future = handler(context, arguments);
9942        let mut cx = TaskContext::from_waker(noop_waker_ref());
9943
9944        match future.as_mut().poll(&mut cx) {
9945            Poll::Ready(Ok(result)) => Ok(vec![json!({
9946                "type": "complete_update",
9947                "update_id": update_id,
9948                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9949            })]),
9950            Poll::Ready(Err(error)) => Ok(vec![json!({
9951                "type": "fail_update",
9952                "update_id": update_id,
9953                "message": error.to_string(),
9954                "exception_type": "UpdateFailed",
9955                "non_retryable": true,
9956            })]),
9957            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9958        }
9959    }
9960
9961    #[cfg(test)]
9962    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9963        self.execute_session_activity_task(task, None, None).await
9964    }
9965
9966    async fn execute_session_activity_task(
9967        &self,
9968        task: ActivityTask,
9969        worker_session: Option<WorkerSession>,
9970        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9971    ) -> Result<AvroValue> {
9972        #[cfg(feature = "telemetry")]
9973        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
9974            !self
9975                .client
9976                .observability_context_supported
9977                .load(Ordering::SeqCst)
9978        }) {
9979            return telemetry
9980                .run(
9981                    "durable.activity.task",
9982                    self.activity_telemetry_fields(&task),
9983                    false,
9984                    self.execute_session_activity_task_inner(task, worker_session, hydration_claim),
9985                )
9986                .await;
9987        }
9988        self.execute_session_activity_task_inner(task, worker_session, hydration_claim)
9989            .await
9990    }
9991
9992    async fn execute_session_activity_task_inner(
9993        &self,
9994        task: ActivityTask,
9995        worker_session: Option<WorkerSession>,
9996        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9997    ) -> Result<AvroValue> {
9998        validate_activity_task_payloads(&task)?;
9999        if worker_session.is_some() {
10000            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
10001                || task
10002                    .activity_attempt_id
10003                    .as_deref()
10004                    .or(task.attempt_id.as_deref())
10005                    .is_none_or(str::is_empty)
10006                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
10007            {
10008                return Err(Error::ActivityExecutionAbandoned(
10009                    "session activity requires this worker's exact immutable claim".into(),
10010                ));
10011            }
10012        }
10013
10014        let handler = self
10015            .activities
10016            .get(&task.activity_type)
10017            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
10018        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10019        let attempt_id = task
10020            .activity_attempt_id
10021            .clone()
10022            .or(task.attempt_id.clone())
10023            .unwrap_or_default();
10024        let lease_owner = task
10025            .lease_owner
10026            .clone()
10027            .unwrap_or_else(|| self.worker_id.clone());
10028        let session = worker_session.clone();
10029        if let Some(claim) = hydration_claim {
10030            claim.confirm(&self.client).await?;
10031        }
10032        #[cfg(feature = "telemetry")]
10033        let observations = self.activity_observations(&task);
10034        #[cfg(feature = "telemetry")]
10035        let fields = self.activity_telemetry_fields(&task);
10036        let ctx = ActivityContext {
10037            client: self.client.clone(),
10038            task_id: task.task_id,
10039            activity_attempt_id: attempt_id,
10040            lease_owner,
10041            activity_type: task.activity_type,
10042            attempt_number: task.attempt_number,
10043            task_queue: self.task_queue.clone(),
10044            worker_id: self.worker_id.clone(),
10045            claim_guard: None,
10046            local_heartbeats: None,
10047            worker_session,
10048        };
10049
10050        let operation = async {
10051            let callback = self.activity_callback(handler, ctx, args, false);
10052            if let Some(session) = session {
10053                tokio::select! {
10054                    biased;
10055                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10056                    result = callback => if session.active() { result } else {
10057                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10058                    },
10059                }
10060            } else {
10061                callback.await
10062            }
10063        };
10064        #[cfg(feature = "telemetry")]
10065        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10066            self.client
10067                .observability_context_supported
10068                .load(Ordering::SeqCst)
10069        }) {
10070            return telemetry
10071                .run_observed(
10072                    "durable.activity.task",
10073                    fields,
10074                    false,
10075                    observations,
10076                    operation,
10077                )
10078                .await;
10079        }
10080        operation.await
10081    }
10082
10083    fn activity_callback(
10084        &self,
10085        handler: &ActivityHandler,
10086        context: ActivityContext,
10087        args: AvroValue,
10088        local: bool,
10089    ) -> ActivityFuture {
10090        #[cfg(feature = "telemetry")]
10091        if let Some(telemetry) = &self.telemetry {
10092            let telemetry = telemetry.clone();
10093            let fields = self.callback_telemetry_fields(&context, local);
10094            let handler = handler.clone();
10095            let name = if local {
10096                "durable.local_activity.attempt"
10097            } else {
10098                "durable.activity.attempt"
10099            };
10100            return Box::pin(async move {
10101                telemetry
10102                    .run(
10103                        name,
10104                        fields,
10105                        true,
10106                        async move { handler(context, args).await },
10107                    )
10108                    .await
10109            });
10110        }
10111        #[cfg(not(feature = "telemetry"))]
10112        let _ = local;
10113        handler(context, args)
10114    }
10115}
10116
10117fn poller_result(
10118    kind: &str,
10119    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10120) -> Result<()> {
10121    match result {
10122        Ok(result) => result,
10123        Err(error) => Err(Error::WorkerLoop(format!(
10124            "{kind} poller join error: {error}"
10125        ))),
10126    }
10127}
10128
10129fn optional_poller_result(
10130    kind: &str,
10131    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10132) -> Result<()> {
10133    match result {
10134        Some(result) => poller_result(kind, result),
10135        None => Ok(()),
10136    }
10137}
10138
10139async fn join_pollers(
10140    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10141    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10142    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10143) -> Result<()> {
10144    let mut first_error = None;
10145
10146    if let Some(handle) = workflow_poller {
10147        if let Err(error) = poller_result("workflow", handle.await) {
10148            first_error.get_or_insert(error);
10149        }
10150    }
10151
10152    if let Some(handle) = activity_poller {
10153        if let Err(error) = poller_result("activity", handle.await) {
10154            first_error.get_or_insert(error);
10155        }
10156    }
10157
10158    if let Some(handle) = query_poller {
10159        if let Err(error) = poller_result("query", handle.await) {
10160            first_error.get_or_insert(error);
10161        }
10162    }
10163
10164    if let Some(error) = first_error {
10165        Err(error)
10166    } else {
10167        Ok(())
10168    }
10169}
10170
10171fn default_worker_id() -> String {
10172    let millis = SystemTime::now()
10173        .duration_since(UNIX_EPOCH)
10174        .unwrap_or_default()
10175        .as_millis();
10176    format!("rust-worker-{}-{millis}", std::process::id())
10177}
10178
10179fn percent_encode_path_segment(segment: &str) -> String {
10180    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10181    let mut encoded = String::with_capacity(segment.len());
10182
10183    for byte in segment.bytes() {
10184        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10185            encoded.push(char::from(byte));
10186        } else {
10187            encoded.push('%');
10188            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10189            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10190        }
10191    }
10192
10193    encoded
10194}
10195
10196fn unique_request_id(prefix: &str) -> String {
10197    let nanos = SystemTime::now()
10198        .duration_since(UNIX_EPOCH)
10199        .unwrap_or_default()
10200        .as_nanos();
10201    format!("{prefix}-{}-{nanos}", std::process::id())
10202}
10203
10204#[derive(Debug)]
10205struct QueryTaskExecutionFailure {
10206    reason: String,
10207    message: String,
10208    failure_type: String,
10209}
10210
10211impl QueryTaskExecutionFailure {
10212    fn new(
10213        reason: impl Into<String>,
10214        message: impl Into<String>,
10215        failure_type: impl Into<String>,
10216    ) -> Self {
10217        Self {
10218            reason: reason.into(),
10219            message: message.into(),
10220            failure_type: failure_type.into(),
10221        }
10222    }
10223}
10224
10225/// Typed local state owned by one deterministic workflow invocation.
10226///
10227/// Use [`WorkflowInstance::update`] for the same state transitions during
10228/// ordinary execution and replay. A replayed query receives a detached
10229/// immutable `Arc<S>` rather than this mutation-capable handle.
10230#[derive(Clone, Debug)]
10231pub struct WorkflowInstance<S> {
10232    state: Arc<Mutex<S>>,
10233}
10234
10235impl<S> WorkflowInstance<S> {
10236    fn new(state: S) -> Self {
10237        Self {
10238            state: Arc::new(Mutex::new(state)),
10239        }
10240    }
10241
10242    /// Read the current workflow-instance state without changing it.
10243    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10244        let state = self
10245            .state
10246            .lock()
10247            .map_err(|_| Error::WorkflowStatePoisoned)?;
10248        Ok(reader(&state))
10249    }
10250
10251    /// Apply one deterministic workflow-instance state transition.
10252    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10253        let mut state = self
10254            .state
10255            .lock()
10256            .map_err(|_| Error::WorkflowStatePoisoned)?;
10257        Ok(transition(&mut state))
10258    }
10259}
10260
10261impl<S: Clone> WorkflowInstance<S> {
10262    fn snapshot(&self) -> Result<S> {
10263        self.read(Clone::clone)
10264    }
10265}
10266
10267#[derive(Clone, Debug, PartialEq)]
10268pub struct MessageStreamMessage {
10269    pub stream_name: String,
10270    pub message_id: String,
10271    pub position: u64,
10272    pub arguments: Vec<AvroValue>,
10273}
10274
10275#[derive(Clone, Debug)]
10276pub struct MessageStream {
10277    ctx: WorkflowContext,
10278    name: String,
10279}
10280
10281impl MessageStream {
10282    /// Wait for one message, then return a bounded currently-available batch.
10283    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10284        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10285            return Err(Error::Codec(format!(
10286                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10287            )));
10288        }
10289        loop {
10290            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10291                return Ok(batch);
10292            }
10293
10294            self.ctx.record_message_stream_wait(&self.name)?;
10295            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10296            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10297            self.ctx.buffer_message_stream_delivery(arguments)?;
10298            if let Some(sequence) = replay_wait_sequence {
10299                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10300            }
10301        }
10302    }
10303
10304    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10305        self.receive(1)
10306            .await?
10307            .into_iter()
10308            .next()
10309            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10310    }
10311}
10312
10313#[derive(Clone, Debug)]
10314pub struct WorkflowContext {
10315    state: Arc<Mutex<WorkflowState>>,
10316    cancellation_scope_id: String,
10317}
10318
10319fn valid_memo_key(key: &str) -> bool {
10320    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10321
10322    !key.is_empty()
10323        && key.len() <= 64
10324        && (numeric_candidate.is_empty()
10325            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10326        && key
10327            .bytes()
10328            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10329}
10330
10331fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10332    BASE64
10333        .decode(encode_avro_value(value)?.blob)
10334        .map(|bytes| bytes.len())
10335        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10336}
10337
10338fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10339    let AvroValue::Map(entries) = value else {
10340        return Err(Error::InvalidMemoUpdate(
10341            "entries must serialize to an Avro string-keyed map".to_string(),
10342        ));
10343    };
10344    if require_entries && entries.is_empty() {
10345        return Err(Error::InvalidMemoUpdate(
10346            "at least one entry is required".to_string(),
10347        ));
10348    }
10349    if entries.len() > MAX_MEMO_ENTRIES {
10350        return Err(Error::InvalidMemoUpdate(format!(
10351            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10352        )));
10353    }
10354
10355    for (key, value) in &entries {
10356        if !valid_memo_key(&key) {
10357            return Err(Error::InvalidMemoUpdate(
10358                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10359            ));
10360        }
10361        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10362            return Err(Error::InvalidMemoUpdate(format!(
10363                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10364            )));
10365        }
10366    }
10367
10368    let value = AvroValue::Map(entries);
10369    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10370        return Err(Error::InvalidMemoUpdate(format!(
10371            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10372        )));
10373    }
10374    Ok(value)
10375}
10376
10377fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10378    let object = envelope.as_object().ok_or_else(|| {
10379        Error::InvalidMemoUpdate(
10380            "history field must use the public {codec, blob} payload envelope".to_string(),
10381        )
10382    })?;
10383    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10384        return Err(Error::InvalidMemoUpdate(
10385            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10386        ));
10387    }
10388
10389    canonical_memo_entries(
10390        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10391        require_entries,
10392    )
10393}
10394
10395impl WorkflowContext {
10396    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10397        let name = name.into();
10398        if name.is_empty()
10399            || name.len() > 128
10400            || !name.bytes().all(|byte| {
10401                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10402            })
10403        {
10404            return Err(Error::Codec(
10405                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10406                    .to_string(),
10407            ));
10408        }
10409        Ok(MessageStream {
10410            ctx: self.clone(),
10411            name,
10412        })
10413    }
10414
10415    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10416        let mut state = self
10417            .state
10418            .lock()
10419            .map_err(|_| Error::WorkflowStatePoisoned)?;
10420        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10421        state
10422            .message_stream_waits
10423            .insert(name.to_string(), position);
10424        Ok(())
10425    }
10426
10427    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
10428        let mut state = self
10429            .state
10430            .lock()
10431            .map_err(|_| Error::WorkflowStatePoisoned)?;
10432        let cursor = state
10433            .message_stream_cursors
10434            .get(&message.stream_name)
10435            .copied()
10436            .unwrap_or(0);
10437        if message.position <= cursor {
10438            return Ok(());
10439        }
10440        let pending = state
10441            .message_stream_messages
10442            .entry(message.stream_name.clone())
10443            .or_default();
10444        if pending.iter().any(|candidate| {
10445            candidate.position == message.position || candidate.message_id == message.message_id
10446        }) {
10447            return Ok(());
10448        }
10449        pending.push(message);
10450        pending.sort_by_key(|candidate| candidate.position);
10451        Ok(())
10452    }
10453
10454    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
10455        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
10456            match delivery {
10457                MessageStreamDelivery::Message(message) => {
10458                    let stream_name = message.stream_name.clone();
10459                    self.buffer_message_stream(message)?;
10460                    return Ok(Some(stream_name));
10461                }
10462                MessageStreamDelivery::Cursor {
10463                    stream_name,
10464                    through_position,
10465                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
10466            }
10467        }
10468        Ok(None)
10469    }
10470
10471    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
10472        let state = self
10473            .state
10474            .lock()
10475            .map_err(|_| Error::WorkflowStatePoisoned)?;
10476        Ok(match state.recorded_commands.get(state.command_cursor) {
10477            Some(RecordedCommand::SignalWait {
10478                sequence,
10479                signal_name,
10480                ..
10481            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
10482            _ => None,
10483        })
10484    }
10485
10486    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
10487        let (history, payload_codec) = {
10488            let state = self
10489                .state
10490                .lock()
10491                .map_err(|_| Error::WorkflowStatePoisoned)?;
10492            (
10493                Arc::clone(&state.history_events),
10494                state.payload_codec.clone(),
10495            )
10496        };
10497
10498        let Some(opened_index) = history.iter().position(|event| {
10499            event.event_type == "SignalWaitOpened"
10500                && durable_event_sequence(event) == Some(wait_sequence)
10501                && event.payload.get("signal_name").and_then(Value::as_str)
10502                    == Some(MESSAGE_STREAM_SIGNAL)
10503        }) else {
10504            return Ok(());
10505        };
10506        let boundary_index = history
10507            .iter()
10508            .enumerate()
10509            .skip(opened_index + 1)
10510            .find_map(|(index, event)| {
10511                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
10512                    && is_authored_command_open_event(event))
10513                .then_some(index)
10514            })
10515            .unwrap_or(history.len());
10516
10517        for event in history[opened_index + 1..boundary_index]
10518            .iter()
10519            .filter(|event| {
10520                event.event_type == "SignalReceived"
10521                    && event.payload.get("signal_name").and_then(Value::as_str)
10522                        == Some(MESSAGE_STREAM_SIGNAL)
10523            })
10524        {
10525            let arguments = decode_signal_event_arguments(event, &payload_codec)?
10526                .into_iter()
10527                .map(AvroValue::into_json)
10528                .collect::<Result<Vec<_>>>()?;
10529            self.buffer_message_stream_delivery(arguments)?;
10530        }
10531        Ok(())
10532    }
10533
10534    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
10535        let mut state = self
10536            .state
10537            .lock()
10538            .map_err(|_| Error::WorkflowStatePoisoned)?;
10539        let cursor = state
10540            .message_stream_cursors
10541            .entry(name.to_string())
10542            .or_default();
10543        *cursor = (*cursor).max(through_position);
10544        if let Some(pending) = state.message_stream_messages.get_mut(name) {
10545            pending.retain(|message| message.position > through_position);
10546        }
10547        Ok(())
10548    }
10549
10550    fn take_message_stream_batch(
10551        &self,
10552        name: &str,
10553        max_items: usize,
10554    ) -> Result<Option<Vec<MessageStreamMessage>>> {
10555        let mut state = self
10556            .state
10557            .lock()
10558            .map_err(|_| Error::WorkflowStatePoisoned)?;
10559        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10560        let pending = state
10561            .message_stream_messages
10562            .entry(name.to_string())
10563            .or_default();
10564        let count = contiguous_message_stream_count(pending, cursor, max_items);
10565        if count == 0 {
10566            return Ok(None);
10567        }
10568        let batch = pending.drain(..count).collect::<Vec<_>>();
10569        let position = batch.last().map(|message| message.position).unwrap_or(0);
10570        state
10571            .message_stream_cursors
10572            .insert(name.to_string(), position);
10573        state.message_stream_waits.remove(name);
10574        Ok(Some(batch))
10575    }
10576
10577    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
10578        let state = self
10579            .state
10580            .lock()
10581            .map_err(|_| Error::WorkflowStatePoisoned)?;
10582        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
10583        cursors.sort_by_key(|(name, _)| *name);
10584        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
10585        waits.sort_by_key(|(name, _)| *name);
10586        Ok((
10587            cursors
10588                .into_iter()
10589                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
10590                .collect(),
10591            waits
10592                .into_iter()
10593                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
10594                .collect(),
10595        ))
10596    }
10597    /// Identity of the parent workflow currently being replayed.
10598    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
10599        let state = self
10600            .state
10601            .lock()
10602            .map_err(|_| Error::WorkflowStatePoisoned)?;
10603        Ok(WorkflowIdentity {
10604            workflow_id: state.workflow_id.clone(),
10605            run_id: state.run_id.clone(),
10606        })
10607    }
10608
10609    /// Return the server-published history budget for this workflow task.
10610    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
10611        let state = self
10612            .state
10613            .lock()
10614            .map_err(|_| Error::WorkflowStatePoisoned)?;
10615        Ok(state.history_budget.clone())
10616    }
10617
10618    /// Continue this workflow instance as a fresh run with replacement arguments.
10619    ///
10620    /// Return this value directly from the workflow handler. The worker converts
10621    /// it to the terminal protocol command only after replay has consumed every
10622    /// recorded durable command.
10623    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
10624        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
10625    }
10626
10627    /// Continue as new with optional workflow-type and task-queue overrides.
10628    pub fn continue_as_new_with_options<T: Serialize>(
10629        &self,
10630        options: ContinueAsNewOptions,
10631        args: T,
10632    ) -> Result<Value> {
10633        options.validate()?;
10634        Err(Error::ContinueAsNew(ContinueAsNewRequest {
10635            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
10636            options,
10637        }))
10638    }
10639
10640    pub fn activity<T: Serialize>(
10641        &self,
10642        activity_type: impl Into<String>,
10643        args: T,
10644    ) -> ActivityCall {
10645        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10646    }
10647
10648    pub fn activity_on_queue<T, Q>(
10649        &self,
10650        activity_type: impl Into<String>,
10651        task_queue: Option<Q>,
10652        args: T,
10653    ) -> ActivityCall
10654    where
10655        T: Serialize,
10656        Q: Into<String>,
10657    {
10658        let mut options = ActivityOptions::new();
10659        options.task_queue = task_queue.map(Into::into);
10660        self.activity_with_options(activity_type, options, args)
10661    }
10662
10663    /// Schedule one durable activity with retry, routing, and timeout options.
10664    ///
10665    /// Options are validated before the command is emitted. Once the command is
10666    /// recorded, replay consumes the same activity lifecycle at this command
10667    /// position and never emits a duplicate schedule.
10668    ///
10669    /// ```no_run
10670    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10671    /// # use std::time::Duration;
10672    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10673    /// let result = ctx
10674    ///     .activity_with_options(
10675    ///         "charge-card",
10676    ///         ActivityOptions::new()
10677    ///             .task_queue("payments")
10678    ///             .retry_policy(
10679    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10680    ///                     Duration::from_secs(1),
10681    ///                     2,
10682    ///                     Some(Duration::from_secs(30)),
10683    ///                 ),
10684    ///             )
10685    ///             .start_to_close_timeout(Duration::from_secs(60))
10686    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10687    ///             .heartbeat_timeout(Duration::from_secs(15)),
10688    ///         json!([{"order_id": "order-42"}]),
10689    ///     )
10690    ///     .await;
10691    /// match result {
10692    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10693    ///         "reason": failure.reason,
10694    ///         "timeout_kind": failure.timeout_kind,
10695    ///     })),
10696    ///     other => other,
10697    /// }
10698    /// # }
10699    /// ```
10700    pub fn activity_with_options<T: Serialize>(
10701        &self,
10702        activity_type: impl Into<String>,
10703        options: ActivityOptions,
10704        args: T,
10705    ) -> ActivityCall {
10706        ActivityCall {
10707            ctx: self.clone(),
10708            activity_type: activity_type.into(),
10709            options,
10710            worker_session: None,
10711            args: Some(AvroValue::from_serialize(&args)),
10712            scheduled: false,
10713            local: false,
10714            local_result: None,
10715            parallel_group_path: Vec::new(),
10716        }
10717    }
10718
10719    pub async fn activity_avro_value<T: Serialize>(
10720        &self,
10721        activity_type: impl Into<String>,
10722        args: T,
10723    ) -> Result<AvroValue> {
10724        let mut call = self.activity(activity_type, args);
10725        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10726    }
10727
10728    pub async fn activity_avro_value_with_options<T: Serialize>(
10729        &self,
10730        activity_type: impl Into<String>,
10731        options: ActivityOptions,
10732        args: T,
10733    ) -> Result<AvroValue> {
10734        let mut call = self.activity_with_options(activity_type, options, args);
10735        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10736    }
10737
10738    /// Schedule an activity with a Serde request and decode its Serde result.
10739    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10740    where
10741        I: Serialize,
10742        O: DeserializeOwned,
10743    {
10744        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10745            .await
10746    }
10747
10748    /// Schedule an activity with options and decode its result into `O`.
10749    ///
10750    /// Both directions use the fixed Avro Value codec. In particular, this
10751    /// method does not deserialize the JSON-safe inspection projection returned
10752    /// by the dynamic [`ActivityCall`] future.
10753    pub async fn activity_typed_with_options<I, O>(
10754        &self,
10755        activity_type: impl Into<String>,
10756        options: ActivityOptions,
10757        args: I,
10758    ) -> Result<O>
10759    where
10760        I: Serialize,
10761        O: DeserializeOwned,
10762    {
10763        let activity_type = activity_type.into();
10764        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10765            handler_type_error::<I>(
10766                HandlerKind::Activity,
10767                &activity_type,
10768                HandlerValueKind::Input,
10769                error.to_string(),
10770            )
10771        });
10772        let mut call = ActivityCall {
10773            ctx: self.clone(),
10774            activity_type: activity_type.clone(),
10775            options,
10776            worker_session: None,
10777            args: Some(encoded),
10778            scheduled: false,
10779            local: false,
10780            local_result: None,
10781            parallel_group_path: Vec::new(),
10782        };
10783        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10784        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10785    }
10786
10787    /// Schedule and join a deterministic activity/child/timer group.
10788    ///
10789    /// Nested groups retain their input shape. Every durable leaf is scheduled
10790    /// before this future yields, results are assembled by declaration order,
10791    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10792    /// declaration path, stable group metadata, and completed siblings.
10793    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10794        ParallelCall::new(self.clone(), operations)
10795    }
10796
10797    /// Alias for [`WorkflowContext::parallel`].
10798    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10799        self.parallel(operations)
10800    }
10801
10802    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10803    pub async fn parallel_avro_value(
10804        &self,
10805        operations: Vec<ParallelOperation>,
10806    ) -> Result<Vec<ParallelAvroResult>> {
10807        let mut call = self.parallel(operations);
10808        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10809    }
10810
10811    /// Start every durable operation and resume from the one winner persisted
10812    /// by Server. Non-winning operations continue and remain addressable.
10813    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10814        let operations = operations
10815            .into_iter()
10816            .enumerate()
10817            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10818            .collect();
10819        SelectCall::new(self.clone(), operations)
10820    }
10821
10822    /// Named-key variant of [`WorkflowContext::select`].
10823    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10824    where
10825        K: Into<SelectionKey>,
10826    {
10827        SelectCall::new(
10828            self.clone(),
10829            operations
10830                .into_iter()
10831                .map(|(key, operation)| (key.into(), operation))
10832                .collect(),
10833        )
10834    }
10835
10836    /// Create a workflow-local deterministic compensation registry.
10837    pub fn saga(&self) -> Saga {
10838        Saga::new(self.clone())
10839    }
10840
10841    /// Whether cancellation has reached this replay's authored boundary.
10842    ///
10843    /// Server's current `/cancel` route is terminal and does not set this flag.
10844    /// A canonical service request remains pending until its committed delivery
10845    /// is consumed. Request observation alone does not authorize an exception.
10846    pub fn is_cancellation_requested(&self) -> Result<bool> {
10847        let state = self
10848            .state
10849            .lock()
10850            .map_err(|_| Error::WorkflowStatePoisoned)?;
10851        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10852            return Ok(state
10853                .scope_delivery
10854                .as_ref()
10855                .unwrap()
10856                .contexts
10857                .contains_key(&self.cancellation_scope_id));
10858        }
10859        Ok(state.cancel_requested
10860            || state
10861                .scope_delivery
10862                .as_ref()
10863                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10864    }
10865
10866    /// Raise a typed cooperative cancellation at an author-controlled point.
10867    ///
10868    /// Passing this result to [`Saga::finish`] compensates already registered
10869    /// forward steps before the cancellation remains the initiating outcome.
10870    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10871        let mut state = self
10872            .state
10873            .lock()
10874            .map_err(|_| Error::WorkflowStatePoisoned)?;
10875        if state.cancellation_shield_depth == 0 {
10876            if let Some(replay) = &state.scope_delivery {
10877                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10878                    let delivered = replay
10879                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10880                        .ok_or_else(|| {
10881                            Error::InvalidCooperativeCancellation(
10882                                "scoped request lacks its consumed original delivery".into(),
10883                            )
10884                        })?;
10885                    return Err(Error::CancellationScopeRequested(
10886                        CancellationScopeRequested {
10887                            context: context
10888                                .clone()
10889                                .with_replay(Some(Arc::downgrade(&self.state))),
10890                            delivery: delivered.boundary.clone(),
10891                        },
10892                    ));
10893                }
10894            }
10895        }
10896        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10897            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10898                return Ok(());
10899            }
10900            return Err(state.cancellation_error());
10901        }
10902        Ok(())
10903    }
10904
10905    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10906        SignalCall {
10907            ctx: self.clone(),
10908            signal_name: signal_name.into(),
10909            runtime_reserved_allowed: false,
10910            opened_wait: false,
10911            matched_pending: false,
10912            parallel_group_path: Vec::new(),
10913        }
10914    }
10915
10916    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10917        SignalCall {
10918            ctx: self.clone(),
10919            signal_name: signal_name.into(),
10920            runtime_reserved_allowed: true,
10921            opened_wait: false,
10922            matched_pending: false,
10923            parallel_group_path: Vec::new(),
10924        }
10925    }
10926
10927    pub async fn wait_signal_avro_value(
10928        &self,
10929        signal_name: impl Into<String>,
10930    ) -> Result<Vec<AvroValue>> {
10931        let mut call = self.wait_signal(signal_name);
10932        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10933    }
10934
10935    /// Return every committed signal argument list with the given name.
10936    ///
10937    /// This history-backed view is deterministic and is intended for
10938    /// condition predicates that must be re-evaluated after a signal while the
10939    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10940    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10941        self.signals_avro_value(signal_name)?
10942            .into_iter()
10943            .map(|arguments| {
10944                arguments
10945                    .into_iter()
10946                    .map(AvroValue::into_json)
10947                    .collect::<Result<Vec<_>>>()
10948            })
10949            .collect()
10950    }
10951
10952    /// Lossless fixed Avro Value view of committed signals with the given name.
10953    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10954        let state = self
10955            .state
10956            .lock()
10957            .map_err(|_| Error::WorkflowStatePoisoned)?;
10958        state
10959            .history_events
10960            .iter()
10961            .filter(|event| {
10962                event.event_type == "SignalReceived"
10963                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10964            })
10965            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10966            .collect()
10967    }
10968
10969    /// Return every committed update argument list with the given name.
10970    ///
10971    /// Accepted and applied records for the same update ID are de-duplicated.
10972    /// A Server task created after an update therefore replays the workflow and
10973    /// re-evaluates an open condition without application polling.
10974    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10975        self.updates_avro_value(update_name)?
10976            .into_iter()
10977            .map(|arguments| {
10978                arguments
10979                    .into_iter()
10980                    .map(AvroValue::into_json)
10981                    .collect::<Result<Vec<_>>>()
10982            })
10983            .collect()
10984    }
10985
10986    /// Lossless fixed Avro Value view of committed updates with the given name.
10987    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10988        let state = self
10989            .state
10990            .lock()
10991            .map_err(|_| Error::WorkflowStatePoisoned)?;
10992        let mut seen = Vec::new();
10993        let mut updates = Vec::new();
10994        for event in state.history_events.iter() {
10995            if !matches!(
10996                event.event_type.as_str(),
10997                "UpdateAccepted" | "UpdateApplied"
10998            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10999                || event.payload.get("arguments").is_none()
11000            {
11001                continue;
11002            }
11003            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
11004                if seen.iter().any(|recorded| recorded == update_id) {
11005                    continue;
11006                }
11007                seen.push(update_id.to_string());
11008            }
11009            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
11010        }
11011        Ok(updates)
11012    }
11013
11014    /// Wait for a deterministic predicate to become true or for its durable
11015    /// timeout to elapse.
11016    ///
11017    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
11018    /// predicate tokens automatically change the recorded definition
11019    /// fingerprint. Direct callers must provide an equally stable identity in
11020    /// [`ConditionWaitOptions`].
11021    pub fn wait_condition<F>(
11022        &self,
11023        options: ConditionWaitOptions,
11024        predicate: F,
11025    ) -> ConditionWaitCall
11026    where
11027        F: Fn() -> Result<bool> + Send + 'static,
11028    {
11029        ConditionWaitCall {
11030            ctx: self.clone(),
11031            options,
11032            predicate: Box::new(predicate),
11033            occurrence_id: None,
11034            opened_wait: false,
11035            parallel_group_path: Vec::new(),
11036        }
11037    }
11038
11039    /// Wait for server-backed durable time without blocking the worker executor.
11040    ///
11041    /// Polling this future emits one `start_timer` command and yields. The
11042    /// server records the deadline, so neither worker nor server restarts reset
11043    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11044    /// `TimerFired` pair at the same position in the shared durable-command
11045    /// stream, with matching sequence, timer identity, and delay. Sub-second
11046    /// durations round up because protocol deadlines use whole seconds.
11047    ///
11048    /// ```no_run
11049    /// # use durable_workflow::{json, Client, Worker};
11050    /// # use std::time::Duration;
11051    /// # fn configure(client: Client) {
11052    /// let mut worker = Worker::new(client, "rust-workers");
11053    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11054    ///     ctx.sleep(Duration::from_secs(5)).await?;
11055    ///     Ok(json!({"status": "timer fired"}))
11056    /// });
11057    /// # }
11058    /// ```
11059    pub fn sleep(&self, duration: Duration) -> TimerCall {
11060        let delay_seconds = duration
11061            .as_secs()
11062            .checked_add(u64::from(duration.subsec_nanos() > 0));
11063        TimerCall {
11064            ctx: self.clone(),
11065            delay_seconds,
11066            scheduled: false,
11067            matched_pending: false,
11068            parallel_group_path: Vec::new(),
11069        }
11070    }
11071
11072    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11073    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11074        self.sleep(duration)
11075    }
11076
11077    /// Evaluate a non-deterministic callback once and durably record its typed value.
11078    ///
11079    /// On replay the callback is not invoked: the value is decoded from the
11080    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11081    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11082    /// small values that must remain fixed for the lifetime of a workflow run.
11083    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11084    where
11085        T: Serialize + DeserializeOwned,
11086        F: FnOnce() -> T,
11087    {
11088        {
11089            let mut state = self
11090                .state
11091                .lock()
11092                .map_err(|_| Error::WorkflowStatePoisoned)?;
11093            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11094                return match recorded {
11095                    RecordedCommand::SideEffect { sequence, value } => {
11096                        state.command_cursor += 1;
11097                        value.deserialize().map_err(|error| {
11098                            Error::NonDeterministicReplay(ReplayFailure::new(
11099                                "side_effect_type_mismatch",
11100                                Some(sequence),
11101                                Some(std::any::type_name::<T>().to_string()),
11102                                Some(error.to_string()),
11103                                "recorded side-effect value is incompatible with the requested Rust type",
11104                            ))
11105                        })
11106                    }
11107                    other => Err(command_mismatch(&other, "side effect")),
11108                };
11109            }
11110        }
11111
11112        let value = callback();
11113        let avro_value = AvroValue::from_serialize(&value)?;
11114        let mut state = self
11115            .state
11116            .lock()
11117            .map_err(|_| Error::WorkflowStatePoisoned)?;
11118        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11119        state.commands.push(json!({
11120            "type": "record_side_effect",
11121            "result": result,
11122        }));
11123        Ok(value)
11124    }
11125
11126    /// Record or replay a lossless fixed Avro Value side effect.
11127    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11128    where
11129        F: FnOnce() -> AvroValue,
11130    {
11131        {
11132            let mut state = self
11133                .state
11134                .lock()
11135                .map_err(|_| Error::WorkflowStatePoisoned)?;
11136            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11137                return match recorded {
11138                    RecordedCommand::SideEffect { value, .. } => {
11139                        state.command_cursor += 1;
11140                        Ok(value)
11141                    }
11142                    other => Err(command_mismatch(&other, "side effect")),
11143                };
11144            }
11145        }
11146
11147        let value = callback();
11148        let mut state = self
11149            .state
11150            .lock()
11151            .map_err(|_| Error::WorkflowStatePoisoned)?;
11152        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11153        state.commands.push(json!({
11154            "type": "record_side_effect",
11155            "result": result,
11156        }));
11157        Ok(value)
11158    }
11159
11160    /// Append output items at a deterministic workflow command boundary.
11161    ///
11162    /// Stable idempotency keys are derived from the server-provided durable
11163    /// workflow command identity, command ordinal, and item index. Replay
11164    /// consumes the recorded side effect and never emits another append.
11165    pub fn append_workflow_stream(
11166        &self,
11167        stream_name: impl Into<String>,
11168        items: &[WorkflowStreamAppendItem],
11169        max_pending_items: Option<u64>,
11170    ) -> Result<()> {
11171        if items.is_empty() {
11172            return Err(Error::Codec(
11173                "workflow_stream_items_empty: append requires at least one item".to_string(),
11174            ));
11175        }
11176        if max_pending_items == Some(0) {
11177            return Err(Error::Codec(
11178                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11179                    .to_string(),
11180            ));
11181        }
11182        let stream_name = stream_name.into();
11183        if stream_name.is_empty() {
11184            return Err(Error::Codec(
11185                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11186            ));
11187        }
11188
11189        let mut state = self
11190            .state
11191            .lock()
11192            .map_err(|_| Error::WorkflowStatePoisoned)?;
11193        let command_ordinal = state.workflow_stream_command_counter;
11194        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11195            state.workflow_stream_command_counter += 1;
11196            return match recorded {
11197                RecordedCommand::SideEffect { .. } => {
11198                    state.command_cursor += 1;
11199                    Ok(())
11200                }
11201                other => Err(command_mismatch(&other, "workflow stream append")),
11202            };
11203        }
11204
11205        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11206        state.workflow_stream_command_counter += 1;
11207        let wire_items = items
11208            .iter()
11209            .enumerate()
11210            .map(|(item_index, item)| {
11211                item.wire_value(Some(format!(
11212                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11213                )))
11214            })
11215            .collect::<Vec<_>>();
11216        let mut directive = json!({
11217            "operation": "append",
11218            "stream_name": stream_name,
11219            "command_identity": identity,
11220            "command_ordinal": command_ordinal,
11221            "items": wire_items,
11222        });
11223        if let Some(max_pending_items) = max_pending_items {
11224            directive["max_pending_items"] = json!(max_pending_items);
11225        }
11226        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11227        state.commands.push(json!({
11228            "type": "record_side_effect",
11229            "result": result,
11230            "workflow_stream": directive,
11231        }));
11232        Ok(())
11233    }
11234
11235    /// Close a run-scoped output stream at a deterministic command boundary.
11236    pub fn close_workflow_stream(
11237        &self,
11238        stream_name: impl Into<String>,
11239        retention_seconds: Option<u64>,
11240    ) -> Result<()> {
11241        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11242    }
11243
11244    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11245    pub fn error_workflow_stream(
11246        &self,
11247        stream_name: impl Into<String>,
11248        error_reason: impl Into<String>,
11249        retention_seconds: Option<u64>,
11250    ) -> Result<()> {
11251        let error_reason = error_reason.into();
11252        if error_reason.is_empty() {
11253            return Err(Error::Codec(
11254                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11255            ));
11256        }
11257        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11258    }
11259
11260    fn finish_workflow_stream(
11261        &self,
11262        stream_name: String,
11263        error_reason: Option<String>,
11264        retention_seconds: Option<u64>,
11265    ) -> Result<()> {
11266        if stream_name.is_empty() {
11267            return Err(Error::Codec(
11268                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11269            ));
11270        }
11271        if retention_seconds == Some(0) {
11272            return Err(Error::Codec(
11273                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11274            ));
11275        }
11276        let mut state = self
11277            .state
11278            .lock()
11279            .map_err(|_| Error::WorkflowStatePoisoned)?;
11280        let command_ordinal = state.workflow_stream_command_counter;
11281        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11282            state.workflow_stream_command_counter += 1;
11283            return match recorded {
11284                RecordedCommand::SideEffect { .. } => {
11285                    state.command_cursor += 1;
11286                    Ok(())
11287                }
11288                other => Err(command_mismatch(&other, "workflow stream close")),
11289            };
11290        }
11291        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11292        state.workflow_stream_command_counter += 1;
11293        let mut directive = json!({
11294            "operation": if error_reason.is_some() { "error" } else { "close" },
11295            "stream_name": stream_name,
11296            "command_identity": identity,
11297            "command_ordinal": command_ordinal,
11298        });
11299        if let Some(error_reason) = error_reason {
11300            directive["error_reason"] = json!(error_reason);
11301        }
11302        if let Some(retention_seconds) = retention_seconds {
11303            directive["retention_seconds"] = json!(retention_seconds);
11304        }
11305        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11306        state.commands.push(json!({
11307            "type": "record_side_effect",
11308            "result": result,
11309            "workflow_stream": directive,
11310        }));
11311        Ok(())
11312    }
11313
11314    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11315        let identity = state.workflow_command_identity.as_str();
11316        if identity.is_empty() {
11317            return Err(Error::MissingWorkflowCommandIdentity);
11318        }
11319        Ok(identity)
11320    }
11321
11322    /// Validate, emit, or replay a typed workflow search-attribute update.
11323    ///
11324    /// The command is non-blocking within a workflow decision, but its
11325    /// `SearchAttributesUpserted` event occupies the same deterministic command
11326    /// stream as activities, timers, conditions, and other durable operations.
11327    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11328        update.validate()?;
11329        let (attributes, attribute_types) = update.into_wire_parts();
11330        let mut state = self
11331            .state
11332            .lock()
11333            .map_err(|_| Error::WorkflowStatePoisoned)?;
11334
11335        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11336            return match recorded {
11337                RecordedCommand::SearchAttributes {
11338                    sequence,
11339                    attributes: recorded_attributes,
11340                    attribute_types: recorded_attribute_types,
11341                } => {
11342                    if recorded_attributes != attributes {
11343                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11344                            "search_attribute_value_mismatch",
11345                            Some(sequence),
11346                            Some(recorded_attributes.to_string()),
11347                            Some(attributes.to_string()),
11348                            "search-attribute values differ from the recorded durable command",
11349                        )));
11350                    }
11351                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11352                        if recorded_types != attribute_types {
11353                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11354                                "search_attribute_type_mismatch",
11355                                Some(sequence),
11356                                Some(json!(recorded_types).to_string()),
11357                                Some(json!(attribute_types).to_string()),
11358                                "search-attribute declared types differ from the recorded durable command",
11359                            )));
11360                        }
11361                    }
11362                    state.command_cursor += 1;
11363                    Ok(())
11364                }
11365                other => Err(command_mismatch(&other, "search-attribute update")),
11366            };
11367        }
11368
11369        let mut command = serde_json::Map::from_iter([
11370            ("type".to_string(), json!("upsert_search_attributes")),
11371            ("attributes".to_string(), attributes),
11372        ]);
11373        if !attribute_types.is_empty() {
11374            command.insert("attribute_types".to_string(), json!(attribute_types));
11375        }
11376        state.commands.push(Value::Object(command));
11377        Ok(())
11378    }
11379
11380    /// Record a UUIDv4 once and return the same UUID on every replay.
11381    pub fn uuid_v4(&self) -> Result<Uuid> {
11382        self.side_effect(Uuid::new_v4)
11383    }
11384
11385    /// Select the newest supported version for a change, or replay the version
11386    /// already committed for that stable change ID.
11387    ///
11388    /// An unmarked old history that reached its next durable operation, or
11389    /// already completed, selects `-1` when that version is supported. This
11390    /// leaves the original operation available and writes no additional marker.
11391    /// Consistent markers written by older workers retain their original ordered
11392    /// positions. Repeated calls consume a matching marker at the current cursor.
11393    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11394    pub fn get_version(
11395        &self,
11396        change_id: impl Into<String>,
11397        min_supported: i32,
11398        max_supported: i32,
11399    ) -> Result<i32> {
11400        let change_id = change_id.into();
11401        if change_id.trim().is_empty() {
11402            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11403                "version_change_id_invalid",
11404                None,
11405                Some("non-empty change ID".to_string()),
11406                Some(change_id),
11407                "version markers require a stable non-empty change ID",
11408            )));
11409        }
11410        if min_supported > max_supported {
11411            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11412                "version_range_invalid",
11413                None,
11414                Some("min_supported <= max_supported".to_string()),
11415                Some(format!("{min_supported}..={max_supported}")),
11416                "version marker supported range is invalid",
11417            )));
11418        }
11419
11420        let mut state = self
11421            .state
11422            .lock()
11423            .map_err(|_| Error::WorkflowStatePoisoned)?;
11424        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
11425            if let Some(RecordedCommand::VersionMarker {
11426                sequence: alias_sequence,
11427                change_id: alias_change_id,
11428                version: alias_version,
11429            }) = state.recorded_commands.get(state.command_cursor)
11430            {
11431                if alias_change_id == &change_id {
11432                    if *alias_version != version {
11433                        return Err(invalid_recorded_history(
11434                            "version_marker_conflict",
11435                            *alias_sequence,
11436                            &format!("selected version {version} for change ID {change_id:?}"),
11437                            &format!("recorded version {alias_version}"),
11438                            "recorded marker conflicts with the decision already selected during replay",
11439                        ));
11440                    }
11441                    ensure_version_supported(
11442                        &change_id,
11443                        version,
11444                        min_supported,
11445                        max_supported,
11446                        *alias_sequence,
11447                    )?;
11448                    // Older workers could record the same decision again. Keep
11449                    // each physical boundary without skipping intervening work.
11450                    state.command_cursor += 1;
11451                    return Ok(version);
11452                }
11453            }
11454            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
11455            return Ok(version);
11456        }
11457
11458        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11459            return match recorded {
11460                RecordedCommand::VersionMarker {
11461                    sequence,
11462                    change_id: recorded_change_id,
11463                    version,
11464                    ..
11465                } => {
11466                    if recorded_change_id != change_id {
11467                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11468                            "version_change_id_mismatch",
11469                            Some(sequence),
11470                            Some(recorded_change_id),
11471                            Some(change_id),
11472                            "recorded version marker change ID differs from current workflow code",
11473                        )));
11474                    }
11475                    ensure_version_supported(
11476                        &change_id,
11477                        version,
11478                        min_supported,
11479                        max_supported,
11480                        sequence,
11481                    )?;
11482                    state.command_cursor += 1;
11483                    state.version_markers.insert(change_id, (version, sequence));
11484                    Ok(version)
11485                }
11486                other => {
11487                    let version = -1;
11488                    let sequence = other.sequence();
11489                    ensure_version_supported(
11490                        &change_id,
11491                        version,
11492                        min_supported,
11493                        max_supported,
11494                        sequence,
11495                    )?;
11496                    // The existing operation proves this patch site was reached
11497                    // before its marker existed. Keep its original cursor.
11498                    state.version_markers.insert(change_id, (version, sequence));
11499                    Ok(version)
11500                }
11501            };
11502        }
11503
11504        if state
11505            .history_events
11506            .iter()
11507            .any(|event| event.event_type == "WorkflowCompleted")
11508        {
11509            let version = -1;
11510            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
11511            state.version_markers.insert(change_id, (version, 0));
11512            return Ok(version);
11513        }
11514
11515        let version = max_supported;
11516        state.commands.push(json!({
11517            "type": "record_version_marker",
11518            "change_id": change_id,
11519            "version": version,
11520            "min_supported": min_supported,
11521            "max_supported": max_supported,
11522        }));
11523        // Sequence numbers are assigned by the server. Zero identifies a marker
11524        // selected in this uncommitted decision batch for duplicate-call checks.
11525        state.version_markers.insert(change_id, (version, 0));
11526        Ok(version)
11527    }
11528
11529    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
11530    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
11531        Ok(self.get_version(change_id, -1, 1)? == 1)
11532    }
11533
11534    /// Keep a patch marker in history after the legacy branch has been removed.
11535    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
11536        self.get_version(change_id, -1, 1).map(|_| ())
11537    }
11538
11539    /// Merge non-indexed workflow memo metadata through durable history.
11540    ///
11541    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
11542    /// public Avro payload envelope consumed by Server and Cloud runtimes.
11543    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
11544        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
11545        let mut state = self
11546            .state
11547            .lock()
11548            .map_err(|_| Error::WorkflowStatePoisoned)?;
11549
11550        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11551            return match recorded {
11552                RecordedCommand::Memo {
11553                    sequence,
11554                    entries: recorded_entries,
11555                } => {
11556                    if recorded_entries != entries {
11557                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11558                            "memo_update_mismatch",
11559                            Some(sequence),
11560                            Some(format!("{recorded_entries:?}")),
11561                            Some(format!("{entries:?}")),
11562                            "recorded memo entries differ from the current workflow update",
11563                        )));
11564                    }
11565                    state.command_cursor += 1;
11566                    Ok(())
11567                }
11568                other => Err(command_mismatch(&other, "memo upsert")),
11569            };
11570        }
11571
11572        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
11573        state.commands.push(json!({
11574            "type": "upsert_memo",
11575            "entries": entries_envelope,
11576        }));
11577        Ok(())
11578    }
11579
11580    /// Start a named durable child on an explicit queue and await its result.
11581    ///
11582    /// The command is recorded in the parent's sequence-ordered durable command
11583    /// stream. Replay keeps a scheduled child pending without emitting another
11584    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
11585    /// values preserve the history payload codec and include both sides of the
11586    /// durable relationship; failures are returned as
11587    /// [`Error::ChildWorkflowFailed`].
11588    ///
11589    /// ```no_run
11590    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
11591    /// # fn configure(client: Client) {
11592    /// let mut worker = Worker::new(client, "parent-workers");
11593    /// worker.register_workflow("order-parent", |ctx, _input| async move {
11594    ///     let child = ctx
11595    ///         .start_child_workflow(
11596    ///             "fulfil-order",
11597    ///             ChildWorkflowOptions::new("fulfilment-workers")
11598    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
11599    ///             json!([{"order_id": "order-42"}]),
11600    ///         )
11601    ///         .await?;
11602    ///     Ok(child.result)
11603    /// });
11604    /// # }
11605    /// ```
11606    pub fn start_child_workflow<T: Serialize>(
11607        &self,
11608        workflow_type: impl Into<String>,
11609        options: ChildWorkflowOptions,
11610        args: T,
11611    ) -> ChildWorkflowCall {
11612        ChildWorkflowCall {
11613            ctx: self.clone(),
11614            workflow_type: workflow_type.into(),
11615            options,
11616            args: Some(AvroValue::from_serialize(&args)),
11617            scheduled: false,
11618            matched_pending: false,
11619            parallel_group_path: Vec::new(),
11620        }
11621    }
11622
11623    pub async fn start_child_workflow_avro_value<T: Serialize>(
11624        &self,
11625        workflow_type: impl Into<String>,
11626        options: ChildWorkflowOptions,
11627        args: T,
11628    ) -> Result<ChildWorkflowAvroResult> {
11629        let mut call = self.start_child_workflow(workflow_type, options, args);
11630        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11631    }
11632
11633    fn take_commands(&self) -> Result<Vec<Value>> {
11634        let mut state = self
11635            .state
11636            .lock()
11637            .map_err(|_| Error::WorkflowStatePoisoned)?;
11638        Ok(std::mem::take(&mut state.commands))
11639    }
11640
11641    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11642        let mut state = self
11643            .state
11644            .lock()
11645            .map_err(|_| Error::WorkflowStatePoisoned)?;
11646
11647        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11648            return Err(command_mismatch(&recorded, "continue as new"));
11649        }
11650        if state.recorded_continue_as_new_sequence.is_some() {
11651            state.continue_as_new_consumed = true;
11652            return Ok(None);
11653        }
11654
11655        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11656        let mut command = serde_json::Map::from_iter([
11657            ("type".to_string(), json!("continue_as_new")),
11658            ("arguments".to_string(), arguments),
11659            ("queue".to_string(), json!(state.task_queue.clone())),
11660        ]);
11661        if let Some(workflow_type) = request.options.workflow_type {
11662            command.insert("workflow_type".to_string(), json!(workflow_type));
11663        }
11664        if let Some(task_queue) = request.options.task_queue {
11665            command.insert("queue".to_string(), json!(task_queue));
11666        }
11667        Ok(Some(Value::Object(command)))
11668    }
11669
11670    fn matched_recorded_pending(&self) -> Result<bool> {
11671        let state = self
11672            .state
11673            .lock()
11674            .map_err(|_| Error::WorkflowStatePoisoned)?;
11675        Ok(state.matched_recorded_pending)
11676    }
11677
11678    fn ensure_history_consumed(&self) -> Result<()> {
11679        let state = self
11680            .state
11681            .lock()
11682            .map_err(|_| Error::WorkflowStatePoisoned)?;
11683        if let Some(replay) = &state.scope_delivery {
11684            if let Some((&sequence, _)) = replay
11685                .canonical
11686                .deliveries
11687                .iter()
11688                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11689            {
11690                return Err(invalid_recorded_history(
11691                    "cancellation_scope_delivery_unconsumed",
11692                    sequence,
11693                    "original scoped delivery",
11694                    "workflow completion",
11695                    "workflow completed without consuming its committed scope delivery",
11696                ));
11697            }
11698        }
11699        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11700            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11701                "recorded_commands_unconsumed",
11702                Some(command.sequence()),
11703                Some(command.shape().to_string()),
11704                Some("workflow completion".to_string()),
11705                "workflow completed before consuming all recorded durable commands",
11706            )));
11707        }
11708        if let Some(delivery) = state
11709            .cancellation_history
11710            .delivery
11711            .as_ref()
11712            .filter(|_| !state.cancellation_consumed)
11713        {
11714            return Err(invalid_recorded_history(
11715                "cooperative_cancellation_unconsumed",
11716                delivery.sequence,
11717                "committed cancellation call",
11718                "workflow completion",
11719                "workflow completed without reaching its committed cancellation boundary",
11720            ));
11721        }
11722        if let Some(sequence) = state
11723            .recorded_continue_as_new_sequence
11724            .filter(|_| !state.continue_as_new_consumed)
11725        {
11726            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11727                "recorded_continue_as_new_unconsumed",
11728                Some(sequence),
11729                Some("continue as new".to_string()),
11730                Some("workflow completion".to_string()),
11731                "workflow completed without consuming its recorded continue-as-new transition",
11732            )));
11733        }
11734        Ok(())
11735    }
11736}
11737
11738fn contiguous_message_stream_count(
11739    pending: &[MessageStreamMessage],
11740    cursor: u64,
11741    max_items: usize,
11742) -> usize {
11743    pending
11744        .iter()
11745        .take(max_items)
11746        .enumerate()
11747        .take_while(|(offset, message)| {
11748            u64::try_from(*offset)
11749                .ok()
11750                .and_then(|offset| cursor.checked_add(offset + 1))
11751                == Some(message.position)
11752        })
11753        .count()
11754}
11755
11756fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11757    matches!(
11758        event.event_type.as_str(),
11759        "ActivityScheduled"
11760            | "TimerScheduled"
11761            | "ChildWorkflowScheduled"
11762            | "SignalWaitOpened"
11763            | "ConditionWaitOpened"
11764            | "SearchAttributesUpserted"
11765            | "SideEffectRecorded"
11766            | "VersionMarkerRecorded"
11767            | "MemoUpserted"
11768            | "WorkflowContinuedAsNew"
11769    )
11770}
11771
11772#[derive(Debug)]
11773struct WorkflowState {
11774    workflow_id: Option<String>,
11775    run_id: Option<String>,
11776    task_queue: String,
11777    payload_codec: String,
11778    history_events: Arc<Vec<HistoryEvent>>,
11779    history_budget: WorkflowHistoryBudget,
11780    cancel_requested: bool,
11781    cancellation_history: CancellationHistory,
11782    cancellation_consumed: bool,
11783    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11784    cancellation_shield_depth: u64,
11785    cancellation_delivery_enabled: bool,
11786    cancellation_delivery_intent: Option<CancellationDelivery>,
11787    cancellation_delivery_command_count: usize,
11788    allow_cancellation_scope_authoring: bool,
11789    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11790    cancellation_scope_memberships: BTreeMap<u64, String>,
11791    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11792    resume_signal: Option<ResumeSignal>,
11793    recorded_commands: Vec<RecordedCommand>,
11794    selection_markers: Vec<SelectionMarker>,
11795    selection_marker_cursor: usize,
11796    cancelled_selection_members: Vec<SelectionCancellation>,
11797    recorded_continue_as_new_sequence: Option<u64>,
11798    continue_as_new_consumed: bool,
11799    command_cursor: usize,
11800    condition_wait_occurrence_counter: u64,
11801    matched_recorded_pending: bool,
11802    version_markers: HashMap<String, (i32, u64)>,
11803    workflow_command_identity: String,
11804    workflow_stream_command_counter: u64,
11805    commands: Vec<Value>,
11806    local_activity_requests: Vec<local_activity::Request>,
11807    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11808    message_stream_cursors: HashMap<String, u64>,
11809    message_stream_waits: HashMap<String, u64>,
11810}
11811
11812impl WorkflowState {
11813    #[cfg(test)]
11814    fn new(
11815        history: Vec<HistoryEvent>,
11816        task_queue: String,
11817        payload_codec: String,
11818        resume_signal: Option<ResumeSignal>,
11819    ) -> Result<Self> {
11820        Self::new_with_identity(
11821            history,
11822            None,
11823            None,
11824            task_queue,
11825            payload_codec,
11826            resume_signal,
11827        )
11828    }
11829
11830    fn new_with_identity(
11831        history: Vec<HistoryEvent>,
11832        workflow_id: Option<String>,
11833        run_id: Option<String>,
11834        task_queue: String,
11835        payload_codec: String,
11836        resume_signal: Option<ResumeSignal>,
11837    ) -> Result<Self> {
11838        Self::new_with_identity_and_scopes(
11839            history,
11840            workflow_id,
11841            run_id,
11842            task_queue,
11843            payload_codec,
11844            resume_signal,
11845            false,
11846        )
11847    }
11848
11849    fn new_with_identity_and_scopes(
11850        history: Vec<HistoryEvent>,
11851        workflow_id: Option<String>,
11852        run_id: Option<String>,
11853        task_queue: String,
11854        payload_codec: String,
11855        resume_signal: Option<ResumeSignal>,
11856        allow_cancellation_scope_authoring: bool,
11857    ) -> Result<Self> {
11858        Self::new_with_identity_and_scope_delivery(
11859            history,
11860            workflow_id,
11861            run_id,
11862            task_queue,
11863            payload_codec,
11864            resume_signal,
11865            allow_cancellation_scope_authoring,
11866            false,
11867        )
11868    }
11869
11870    fn new_with_identity_and_scope_delivery(
11871        history: Vec<HistoryEvent>,
11872        workflow_id: Option<String>,
11873        run_id: Option<String>,
11874        task_queue: String,
11875        payload_codec: String,
11876        resume_signal: Option<ResumeSignal>,
11877        allow_cancellation_scope_authoring: bool,
11878        allow_cancellation_scope_delivery: bool,
11879    ) -> Result<Self> {
11880        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11881            &history,
11882            allow_cancellation_scope_authoring,
11883            allow_cancellation_scope_delivery,
11884        )?;
11885        let scopes = if allow_cancellation_scope_authoring {
11886            cancellation_scope::CancellationScopeHistory::read(
11887                &history,
11888                run_id.as_deref().unwrap_or_default(),
11889            )?
11890        } else {
11891            cancellation_scope::CancellationScopeHistory::default()
11892        };
11893        let cancellation_history = CancellationHistory::from_events(
11894            &history,
11895            run_id.as_deref().unwrap_or_default(),
11896            None,
11897        )?;
11898        if allow_cancellation_scope_authoring
11899            && cancellation_history.request.is_some()
11900            && !allow_cancellation_scope_delivery
11901        {
11902            return Err(Error::CancellationScopeExecutionUnavailable);
11903        }
11904        let scope_delivery = if allow_cancellation_scope_delivery {
11905            Some(cancellation_scope_replay::ScopeReplay::read(
11906                &history,
11907                &scopes,
11908                run_id.as_deref().unwrap_or_default(),
11909                workflow_id.as_deref().unwrap_or_default(),
11910            )?)
11911        } else {
11912            None
11913        };
11914        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11915            &history,
11916            &payload_codec,
11917            WorkflowIdentity {
11918                workflow_id: workflow_id.clone(),
11919                run_id: run_id.clone(),
11920            },
11921        )?)?;
11922        for (sequence, opening) in &scopes.openings {
11923            if recorded_commands
11924                .iter()
11925                .any(|command| command.sequence() == *sequence)
11926            {
11927                return Err(invalid_recorded_history(
11928                    "invalid_cancellation_scope_history",
11929                    *sequence,
11930                    "distinct authored scope opening",
11931                    "operation collision",
11932                    "scope opening collides with a command",
11933                ));
11934            }
11935            recorded_commands.push(RecordedCommand::CancellationScope {
11936                sequence: *sequence,
11937                scope_id: opening.scope_id.clone(),
11938                parent_scope_id: opening.parent_scope_id.clone(),
11939                shield_parent: opening.shield_parent,
11940            });
11941        }
11942        recorded_commands.sort_by_key(RecordedCommand::sequence);
11943        if let Some(replay) = &scope_delivery {
11944            replay.bind_commands(&mut recorded_commands)?;
11945        }
11946        let selection_markers = recorded_selection_markers(&history)?;
11947        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11948        let recorded_continue_as_new = history
11949            .iter()
11950            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11951            .collect::<Vec<_>>();
11952        if recorded_continue_as_new.len() > 1 {
11953            return Err(invalid_recorded_history(
11954                "duplicate_continue_as_new_transition",
11955                recorded_continue_as_new
11956                    .last()
11957                    .and_then(|event| durable_event_sequence(event))
11958                    .unwrap_or(0),
11959                "one WorkflowContinuedAsNew event",
11960                &format!(
11961                    "{} WorkflowContinuedAsNew events",
11962                    recorded_continue_as_new.len()
11963                ),
11964                "workflow history records one continue-as-new transition more than once",
11965            ));
11966        }
11967        let recorded_continue_as_new_sequence = recorded_continue_as_new
11968            .first()
11969            .map(|event| {
11970                durable_event_sequence(event).ok_or_else(|| {
11971                    Error::NonDeterministicReplay(ReplayFailure::new(
11972                        "continue_as_new_sequence_missing",
11973                        None,
11974                        Some("recorded transition sequence".to_string()),
11975                        Some("missing sequence".to_string()),
11976                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11977                    ))
11978                })
11979            })
11980            .transpose()?;
11981        let mut message_stream_cursors = HashMap::new();
11982        for event in &history {
11983            if !matches!(
11984                event.event_type.as_str(),
11985                "SignalReceived" | "SignalApplied"
11986            ) || event.payload.get("signal_name").and_then(Value::as_str)
11987                != Some(MESSAGE_STREAM_SIGNAL)
11988            {
11989                continue;
11990            }
11991            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11992            if arguments.len() != 1 {
11993                continue;
11994            }
11995            let envelope = arguments[0].clone().into_json()?;
11996            let Some(envelope) = envelope.as_object() else {
11997                continue;
11998            };
11999            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
12000            {
12001                continue;
12002            }
12003            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12004                continue;
12005            };
12006            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12007            else {
12008                continue;
12009            };
12010            let cursor = message_stream_cursors
12011                .entry(stream_name.to_string())
12012                .or_insert(0);
12013            *cursor = (*cursor).max(through_position);
12014        }
12015        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
12016        let cancel_requested = history.iter().any(|event| {
12017            matches!(
12018                event.event_type.as_str(),
12019                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
12020            )
12021        });
12022        let cancellation_clock = cancellation_history
12023            .request
12024            .as_ref()
12025            .and_then(|request| request.context.as_ref())
12026            .map(|_| {
12027                cancellation_replay_clock::ReplayClock::new(
12028                    &history,
12029                    &recorded_commands,
12030                    cancellation_history.delivery_index,
12031                )
12032            })
12033            .or_else(|| {
12034                scope_delivery.as_ref().map(|_| {
12035                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12036                })
12037            });
12038        Ok(Self {
12039            workflow_command_identity: String::new(),
12040            workflow_stream_command_counter: 0,
12041            workflow_id,
12042            run_id,
12043            task_queue,
12044            payload_codec,
12045            history_events: Arc::new(history),
12046            history_budget: WorkflowHistoryBudget {
12047                event_count,
12048                ..WorkflowHistoryBudget::default()
12049            },
12050            cancel_requested,
12051            cancellation_history,
12052            cancellation_consumed: false,
12053            cancellation_clock,
12054            cancellation_shield_depth: 0,
12055            cancellation_delivery_enabled: false,
12056            cancellation_delivery_intent: None,
12057            cancellation_delivery_command_count: 0,
12058            allow_cancellation_scope_authoring,
12059            cancellation_scope_opening: None,
12060            cancellation_scope_memberships: scopes.memberships,
12061            scope_delivery,
12062            resume_signal,
12063            recorded_commands,
12064            selection_markers,
12065            selection_marker_cursor: 0,
12066            cancelled_selection_members,
12067            recorded_continue_as_new_sequence,
12068            continue_as_new_consumed: false,
12069            command_cursor: 0,
12070            condition_wait_occurrence_counter: 0,
12071            matched_recorded_pending: false,
12072            version_markers: HashMap::new(),
12073            commands: Vec::new(),
12074            local_activity_requests: Vec::new(),
12075            message_stream_messages: HashMap::new(),
12076            message_stream_cursors,
12077            message_stream_waits: HashMap::new(),
12078        })
12079    }
12080}
12081
12082enum MessageStreamDelivery {
12083    Message(MessageStreamMessage),
12084    Cursor {
12085        stream_name: String,
12086        through_position: u64,
12087    },
12088}
12089
12090fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12091    if arguments.len() != 1 {
12092        return Ok(None);
12093    }
12094    let envelope = arguments
12095        .into_iter()
12096        .next()
12097        .expect("one argument was checked");
12098    let Some(envelope) = envelope.as_object() else {
12099        return Ok(None);
12100    };
12101    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12102        return Ok(None);
12103    };
12104    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12105        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12106        else {
12107            return Ok(None);
12108        };
12109        return Ok(Some(MessageStreamDelivery::Cursor {
12110            stream_name: stream_name.to_string(),
12111            through_position,
12112        }));
12113    }
12114    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12115        return Ok(None);
12116    }
12117    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12118        return Ok(None);
12119    };
12120    let Some(position) = envelope
12121        .get("position")
12122        .and_then(Value::as_u64)
12123        .filter(|value| *value > 0)
12124    else {
12125        return Ok(None);
12126    };
12127    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12128        return Ok(None);
12129    };
12130    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12131    else {
12132        return Ok(None);
12133    };
12134    let decoded = decode_avro_value(&payload_envelope)?;
12135    let AvroValue::Array(values) = decoded else {
12136        return Ok(None);
12137    };
12138    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12139        stream_name: stream_name.to_string(),
12140        message_id: message_id.to_string(),
12141        position,
12142        arguments: values,
12143    })))
12144}
12145
12146#[derive(Clone, Debug)]
12147enum RecordedCommand {
12148    ServiceOperation {
12149        sequence: u64,
12150        call: nexus::RecordedServiceCall,
12151    },
12152    CancellationScope {
12153        sequence: u64,
12154        scope_id: String,
12155        parent_scope_id: String,
12156        shield_parent: bool,
12157    },
12158    CancellationGroup {
12159        sequence: u64,
12160        span: u64,
12161        original: Vec<RecordedCommand>,
12162    },
12163    CancellationBoundary {
12164        sequence: u64,
12165        call_kind: CancellationCallKind,
12166        original: Option<Box<RecordedCommand>>,
12167    },
12168    Activity {
12169        sequence: u64,
12170        activity_type: Option<String>,
12171        cancellation_policy: String,
12172        options: Option<RecordedActivityOptions>,
12173        outcome: Option<ActivityOutcome>,
12174        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12175    },
12176    Timer {
12177        sequence: u64,
12178        delay_seconds: u64,
12179        fired: bool,
12180        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12181    },
12182    ChildWorkflow {
12183        sequence: u64,
12184        workflow_type: Option<String>,
12185        policies: RecordedChildPolicies,
12186        outcome: Option<ChildWorkflowOutcome>,
12187        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12188    },
12189    SignalWait {
12190        sequence: u64,
12191        signal_name: String,
12192        value: Option<Vec<AvroValue>>,
12193        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12194    },
12195    ConditionWait {
12196        sequence: u64,
12197        occurrence_id: String,
12198        condition_key: Option<String>,
12199        predicate_identity: String,
12200        timeout_seconds: Option<u64>,
12201        result: Option<ConditionWaitResult>,
12202        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12203    },
12204    SearchAttributes {
12205        sequence: u64,
12206        attributes: Value,
12207        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12208    },
12209    SideEffect {
12210        sequence: u64,
12211        value: AvroValue,
12212    },
12213    VersionMarker {
12214        sequence: u64,
12215        change_id: String,
12216        version: i32,
12217    },
12218    Memo {
12219        sequence: u64,
12220        entries: AvroValue,
12221    },
12222}
12223
12224#[derive(Clone, Debug, PartialEq, Eq)]
12225struct SelectionMarker {
12226    selection_group_id: String,
12227    selection_group_base_sequence: u64,
12228    selection_group_size: usize,
12229    member_key: SelectionKey,
12230    member_index: usize,
12231    member_base_sequence: u64,
12232    member_size: usize,
12233    operation_kind: String,
12234    operation_identity: String,
12235    outcome: String,
12236    resolution_event_id: String,
12237    resolution_event_type: String,
12238}
12239
12240#[derive(Clone, Debug, PartialEq, Eq)]
12241struct SelectionCancellation {
12242    selection_group_id: String,
12243    member_key: SelectionKey,
12244    member_index: usize,
12245    member_base_sequence: u64,
12246    member_size: usize,
12247    operation_kind: String,
12248    operation_identity: String,
12249}
12250
12251fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12252    let mut markers: Vec<SelectionMarker> = Vec::new();
12253    for event in events
12254        .iter()
12255        .filter(|event| event.event_type == "SelectionResolved")
12256    {
12257        let payload = &event.payload;
12258        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12259        let group_size = required_selection_usize(payload, "selection_group_size")?;
12260        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12261        let member_size = required_selection_usize(payload, "member_size")?;
12262        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12263        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12264            invalid_recorded_history(
12265                "selection_marker_invalid",
12266                base_sequence,
12267                "non-empty selection_group_id",
12268                &payload.to_string(),
12269                "selection winner history is missing its durable group identity",
12270            )
12271        })?;
12272        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12273        if group_id != expected_group_id {
12274            return Err(invalid_recorded_history(
12275                "selection_marker_invalid",
12276                base_sequence,
12277                &expected_group_id,
12278                &group_id,
12279                "selection winner history contains an incompatible group identity",
12280            ));
12281        }
12282        let group_end = base_sequence
12283            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12284            .unwrap_or(u64::MAX);
12285        let member_end = member_base_sequence
12286            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12287            .unwrap_or(u64::MAX);
12288        if member_index >= group_size
12289            || member_base_sequence < base_sequence
12290            || member_end > group_end
12291        {
12292            return Err(invalid_recorded_history(
12293                "selection_marker_invalid",
12294                base_sequence,
12295                "winner member within selection group bounds",
12296                &payload.to_string(),
12297                "selection winner history contains an invalid member range",
12298            ));
12299        }
12300        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12301            invalid_recorded_history(
12302                "selection_marker_invalid",
12303                base_sequence,
12304                "selection operation kind",
12305                &payload.to_string(),
12306                "selection winner history is missing its operation kind",
12307            )
12308        })?;
12309        if !matches!(
12310            operation_kind.as_str(),
12311            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12312        ) {
12313            return Err(invalid_recorded_history(
12314                "selection_marker_invalid",
12315                base_sequence,
12316                "activity, child, timer, signal, condition, or group",
12317                &operation_kind,
12318                "selection winner history contains an unsupported operation kind",
12319            ));
12320        }
12321        let operation_identity =
12322            payload_string(payload, "operation_identity").ok_or_else(|| {
12323                invalid_recorded_history(
12324                    "selection_marker_invalid",
12325                    base_sequence,
12326                    "non-empty operation identity",
12327                    &payload.to_string(),
12328                    "selection winner history is missing its durable operation identity",
12329                )
12330            })?;
12331        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12332            invalid_recorded_history(
12333                "selection_marker_invalid",
12334                base_sequence,
12335                "completed or failed selection outcome",
12336                &payload.to_string(),
12337                "selection winner history is missing its outcome",
12338            )
12339        })?;
12340        if !matches!(outcome.as_str(), "completed" | "failed") {
12341            return Err(invalid_recorded_history(
12342                "selection_marker_invalid",
12343                base_sequence,
12344                "completed or failed selection outcome",
12345                &outcome,
12346                "selection winner history contains an unsupported outcome",
12347            ));
12348        }
12349        let marker = SelectionMarker {
12350            selection_group_id: group_id,
12351            selection_group_base_sequence: base_sequence,
12352            selection_group_size: group_size,
12353            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
12354            member_index,
12355            member_base_sequence,
12356            member_size,
12357            operation_kind,
12358            operation_identity,
12359            outcome,
12360            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
12361                || {
12362                    invalid_recorded_history(
12363                        "selection_marker_invalid",
12364                        base_sequence,
12365                        "durable resolution_event_id",
12366                        &payload.to_string(),
12367                        "selection winner history is missing its terminal event identity",
12368                    )
12369                },
12370            )?,
12371            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
12372                || {
12373                    invalid_recorded_history(
12374                        "selection_marker_invalid",
12375                        base_sequence,
12376                        "durable resolution_event_type",
12377                        &payload.to_string(),
12378                        "selection winner history is missing its terminal event type",
12379                    )
12380                },
12381            )?,
12382        };
12383        if let Some(existing) = markers
12384            .iter()
12385            .find(|existing| existing.selection_group_id == marker.selection_group_id)
12386        {
12387            if existing != &marker {
12388                return Err(invalid_recorded_history(
12389                    "selection_marker_conflict",
12390                    base_sequence,
12391                    &format!("one winner for {}", marker.selection_group_id),
12392                    &payload.to_string(),
12393                    "selection history records conflicting winners for one durable group",
12394                ));
12395            }
12396            continue;
12397        }
12398        markers.push(marker);
12399    }
12400    Ok(markers)
12401}
12402
12403fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
12404    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
12405    for event in events
12406        .iter()
12407        .filter(|event| event.event_type == "SelectionOperationCancelled")
12408    {
12409        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
12410            invalid_recorded_history(
12411                "selection_cancellation_invalid",
12412                0,
12413                "non-empty selection_group_id",
12414                &event.payload.to_string(),
12415                "selection cancellation history is missing its group identity",
12416            )
12417        })?;
12418        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
12419        let marker = SelectionCancellation {
12420            selection_group_id: group_id,
12421            member_key: selection_key_from_value(
12422                event.payload.get("member_key"),
12423                member_base_sequence,
12424            )?,
12425            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
12426            member_base_sequence,
12427            member_size: required_selection_usize(&event.payload, "member_size")?,
12428            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
12429                invalid_recorded_history(
12430                    "selection_cancellation_invalid",
12431                    member_base_sequence,
12432                    "selection operation kind",
12433                    &event.payload.to_string(),
12434                    "selection cancellation is missing its operation kind",
12435                )
12436            })?,
12437            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
12438                || {
12439                    invalid_recorded_history(
12440                        "selection_cancellation_invalid",
12441                        member_base_sequence,
12442                        "selection operation identity",
12443                        &event.payload.to_string(),
12444                        "selection cancellation is missing its operation identity",
12445                    )
12446                },
12447            )?,
12448        };
12449        if let Some(existing) = cancelled.iter().find(|recorded| {
12450            recorded.selection_group_id == marker.selection_group_id
12451                && recorded.member_base_sequence == marker.member_base_sequence
12452        }) {
12453            if existing != &marker {
12454                return Err(invalid_recorded_history(
12455                    "selection_cancellation_conflict",
12456                    member_base_sequence,
12457                    "one stable SelectionOperationCancelled marker",
12458                    &event.payload.to_string(),
12459                    "selection cancellation history contains conflicting member metadata",
12460                ));
12461            }
12462        } else {
12463            cancelled.push(marker);
12464        }
12465    }
12466    Ok(cancelled)
12467}
12468
12469fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
12470    payload
12471        .get(field)
12472        .and_then(value_as_u64)
12473        .filter(|value| *value > 0)
12474        .ok_or_else(|| {
12475            invalid_recorded_history(
12476                "selection_marker_invalid",
12477                0,
12478                &format!("positive integer {field}"),
12479                &payload.to_string(),
12480                "selection history contains invalid durable identity metadata",
12481            )
12482        })
12483}
12484
12485fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
12486    required_selection_usize_allow_zero(payload, field).and_then(|value| {
12487        if value > 0 {
12488            Ok(value)
12489        } else {
12490            Err(invalid_recorded_history(
12491                "selection_marker_invalid",
12492                0,
12493                &format!("positive integer {field}"),
12494                &payload.to_string(),
12495                "selection history contains invalid durable identity metadata",
12496            ))
12497        }
12498    })
12499}
12500
12501fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
12502    payload
12503        .get(field)
12504        .and_then(value_as_u64)
12505        .and_then(|value| usize::try_from(value).ok())
12506        .ok_or_else(|| {
12507            invalid_recorded_history(
12508                "selection_marker_invalid",
12509                0,
12510                &format!("non-negative integer {field}"),
12511                &payload.to_string(),
12512                "selection history contains invalid durable identity metadata",
12513            )
12514        })
12515}
12516
12517#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12518struct RecordedActivityOptions {
12519    task_queue: RecordedSnapshotValue<Option<String>>,
12520    execution_mode: RecordedSnapshotValue<Option<String>>,
12521    retry_policy: ActivityRetrySnapshot,
12522    worker_session: Option<Value>,
12523}
12524
12525#[derive(Clone, Debug)]
12526struct RecordedChildPolicies {
12527    parent_close_policy: String,
12528    cancellation_policy: String,
12529}
12530
12531fn recorded_activity_cancellation_policy(
12532    events: &[&HistoryEvent],
12533    sequence: u64,
12534) -> Result<String> {
12535    let mut policy: Option<String> = None;
12536    for event in events.iter().filter(|event| {
12537        matches!(
12538            event.event_type.as_str(),
12539            "ActivityScheduled"
12540                | "ActivityStarted"
12541                | "ActivityCompleted"
12542                | "ActivityFailed"
12543                | "ActivityTimedOut"
12544                | "ActivityCancelled"
12545        )
12546    }) {
12547        for source in [Some(&event.payload), event.payload.get("activity")]
12548            .into_iter()
12549            .flatten()
12550        {
12551            let Some(value) = source.get("cancellation_policy") else {
12552                continue;
12553            };
12554            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
12555                value.as_str()
12556            else {
12557                return Err(invalid_recorded_history(
12558                    "invalid_activity_cancellation_policy_history",
12559                    sequence,
12560                    "supported Activity cancellation policy",
12561                    &value.to_string(),
12562                    "Activity history contains an invalid cancellation policy",
12563                ));
12564            };
12565            if let Some(previous) = policy.as_deref() {
12566                if previous != incoming {
12567                    return Err(invalid_recorded_history(
12568                        "activity_cancellation_policy_history_conflict",
12569                        sequence,
12570                        previous,
12571                        incoming,
12572                        "Activity cancellation policy changed between history events",
12573                    ));
12574                }
12575            }
12576            policy = Some(incoming.to_string());
12577        }
12578        policy.get_or_insert_with(|| "try_cancel".to_string());
12579    }
12580    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
12581}
12582
12583fn recorded_child_policy_value<'a>(
12584    payload: &'a Value,
12585    field: &str,
12586    sequence: u64,
12587) -> Result<Option<&'a str>> {
12588    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
12589        return Ok(None);
12590    };
12591    let valid = match (field, value.as_str()) {
12592        (
12593            "parent_close_policy",
12594            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
12595        ) => true,
12596        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
12597            true
12598        }
12599        _ => false,
12600    };
12601    if !valid {
12602        return Err(invalid_recorded_history(
12603            "invalid_child_workflow_policy_history",
12604            sequence,
12605            "supported child workflow policy",
12606            &value.to_string(),
12607            "child workflow history contains an invalid policy",
12608        ));
12609    }
12610    Ok(value.as_str())
12611}
12612
12613fn recorded_child_policies(
12614    events: &[&HistoryEvent],
12615    scheduled: &HistoryEvent,
12616    sequence: u64,
12617) -> Result<RecordedChildPolicies> {
12618    let parent_close_policy =
12619        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
12620            .unwrap_or("abandon")
12621            .to_string();
12622    let cancellation_policy =
12623        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
12624            .unwrap_or("abandon")
12625            .to_string();
12626    for event in events {
12627        for (field, expected) in [
12628            ("parent_close_policy", parent_close_policy.as_str()),
12629            ("cancellation_policy", cancellation_policy.as_str()),
12630        ] {
12631            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
12632                if actual != expected {
12633                    return Err(invalid_recorded_history(
12634                        "child_workflow_policy_history_conflict",
12635                        sequence,
12636                        expected,
12637                        actual,
12638                        "child workflow policy changed between history events",
12639                    ));
12640                }
12641            }
12642        }
12643    }
12644    Ok(RecordedChildPolicies {
12645        parent_close_policy,
12646        cancellation_policy,
12647    })
12648}
12649
12650fn ensure_child_policies_match(
12651    sequence: u64,
12652    recorded: &RecordedChildPolicies,
12653    current: &ChildWorkflowOptions,
12654) -> Result<()> {
12655    for (field, expected, actual) in [
12656        (
12657            "parent_close_policy",
12658            recorded.parent_close_policy.as_str(),
12659            current.parent_close_policy.as_str(),
12660        ),
12661        (
12662            "cancellation_policy",
12663            recorded.cancellation_policy.as_str(),
12664            current.cancellation_policy.as_str(),
12665        ),
12666    ] {
12667        if expected != actual {
12668            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12669                "child_workflow_policy_changed",
12670                Some(sequence),
12671                Some(expected.to_string()),
12672                Some(actual.to_string()),
12673                format!("child workflow {field} changed during replay"),
12674            )));
12675        }
12676    }
12677    Ok(())
12678}
12679
12680#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12681enum RecordedSnapshotValue<T> {
12682    /// Older history did not persist this field, so it cannot constrain replay.
12683    Unknown,
12684    Known(T),
12685}
12686
12687impl<T: PartialEq> RecordedSnapshotValue<T> {
12688    fn matches_current(&self, current: &Self) -> bool {
12689        match self {
12690            Self::Unknown => true,
12691            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12692        }
12693    }
12694}
12695
12696#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12697struct ActivityRetrySnapshot {
12698    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12699    max_attempts: RecordedSnapshotValue<Option<u64>>,
12700    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12701    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12702    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12703    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12704    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12705    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12706}
12707
12708impl ActivityRetrySnapshot {
12709    fn matches_current(&self, current: &Self) -> bool {
12710        self.snapshot_version
12711            .matches_current(&current.snapshot_version)
12712            && self.max_attempts.matches_current(&current.max_attempts)
12713            && self
12714                .backoff_seconds
12715                .matches_current(&current.backoff_seconds)
12716            && self
12717                .start_to_close_timeout
12718                .matches_current(&current.start_to_close_timeout)
12719            && self
12720                .schedule_to_start_timeout
12721                .matches_current(&current.schedule_to_start_timeout)
12722            && self
12723                .schedule_to_close_timeout
12724                .matches_current(&current.schedule_to_close_timeout)
12725            && self
12726                .heartbeat_timeout
12727                .matches_current(&current.heartbeat_timeout)
12728            && self
12729                .non_retryable_error_types
12730                .matches_current(&current.non_retryable_error_types)
12731    }
12732}
12733
12734fn recorded_optional_u64(
12735    object: Option<&serde_json::Map<String, Value>>,
12736    field: &str,
12737) -> RecordedSnapshotValue<Option<u64>> {
12738    match object.and_then(|object| object.get(field)) {
12739        None => RecordedSnapshotValue::Unknown,
12740        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12741        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12742    }
12743}
12744
12745fn recorded_optional_string(
12746    object: &serde_json::Map<String, Value>,
12747    field: &str,
12748) -> RecordedSnapshotValue<Option<String>> {
12749    match object.get(field) {
12750        None => RecordedSnapshotValue::Unknown,
12751        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12752        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12753    }
12754}
12755
12756fn recorded_activity_execution_mode(
12757    events: &[&HistoryEvent],
12758    sequence: u64,
12759) -> Result<RecordedSnapshotValue<Option<String>>> {
12760    let mut recorded = RecordedSnapshotValue::Unknown;
12761    for event in events {
12762        for object in [
12763            event.payload.as_object(),
12764            event.payload.get("activity").and_then(Value::as_object),
12765        ]
12766        .into_iter()
12767        .flatten()
12768        {
12769            let mode = match object.get("execution_mode") {
12770                None => None,
12771                Some(Value::Null) => Some(None),
12772                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12773                Some(_) => {
12774                    return Err(invalid_recorded_history(
12775                        "activity_execution_mode_invalid",
12776                        sequence,
12777                        "null or a non-empty execution mode",
12778                        "invalid execution_mode",
12779                        "activity history contains an invalid execution mode",
12780                    ))
12781                }
12782            };
12783            let legacy_mode = match object.get("local_activity") {
12784                None => None,
12785                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12786                Some(_) => {
12787                    return Err(invalid_recorded_history(
12788                        "activity_execution_mode_invalid",
12789                        sequence,
12790                        "boolean local_activity",
12791                        "invalid local_activity",
12792                        "activity history contains an invalid local-activity marker",
12793                    ))
12794                }
12795            };
12796            for mode in [mode, legacy_mode].into_iter().flatten() {
12797                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12798                {
12799                    return Err(invalid_recorded_history(
12800                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12801                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12802                    ));
12803                }
12804                recorded = RecordedSnapshotValue::Known(mode);
12805            }
12806        }
12807    }
12808    Ok(recorded)
12809}
12810
12811fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12812    let policy = policy.and_then(Value::as_object);
12813    let backoff_seconds = policy
12814        .and_then(|policy| policy.get("backoff_seconds"))
12815        .and_then(Value::as_array)
12816        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12817        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12818    let mut non_retryable_error_types = Vec::new();
12819    for error_type in policy
12820        .and_then(|policy| policy.get("non_retryable_error_types"))
12821        .and_then(Value::as_array)
12822        .into_iter()
12823        .flatten()
12824        .filter_map(Value::as_str)
12825        .map(str::trim)
12826        .filter(|error_type| !error_type.is_empty())
12827    {
12828        if !non_retryable_error_types
12829            .iter()
12830            .any(|recorded| recorded == error_type)
12831        {
12832            non_retryable_error_types.push(error_type.to_string());
12833        }
12834    }
12835
12836    ActivityRetrySnapshot {
12837        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12838        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12839        backoff_seconds,
12840        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12841        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12842        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12843        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12844        non_retryable_error_types: if policy
12845            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12846        {
12847            RecordedSnapshotValue::Known(non_retryable_error_types)
12848        } else {
12849            RecordedSnapshotValue::Unknown
12850        },
12851    }
12852}
12853
12854fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12855    let policy = options.retry_policy.as_ref();
12856    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12857        Some(Value::Null) => None,
12858        Some(value) => value_as_u64(value),
12859        None => Some(1),
12860    };
12861    let backoff_seconds = policy
12862        .and_then(|policy| policy.get("backoff_seconds"))
12863        .and_then(Value::as_array)
12864        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12865        .unwrap_or_default();
12866    let non_retryable_error_types = policy
12867        .and_then(|policy| policy.get("non_retryable_error_types"))
12868        .and_then(Value::as_array)
12869        .into_iter()
12870        .flatten()
12871        .filter_map(Value::as_str)
12872        .map(str::to_string)
12873        .collect();
12874
12875    ActivityRetrySnapshot {
12876        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12877        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12878        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12879        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12880        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12881        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12882        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12883        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12884    }
12885}
12886
12887fn activity_options_description(options: &RecordedActivityOptions) -> String {
12888    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12889}
12890
12891impl RecordedCommand {
12892    fn sequence(&self) -> u64 {
12893        match self {
12894            Self::CancellationGroup { sequence, .. }
12895            | Self::CancellationScope { sequence, .. }
12896            | Self::CancellationBoundary { sequence, .. }
12897            | Self::Activity { sequence, .. }
12898            | Self::Timer { sequence, .. }
12899            | Self::ChildWorkflow { sequence, .. }
12900            | Self::SignalWait { sequence, .. }
12901            | Self::ConditionWait { sequence, .. }
12902            | Self::SearchAttributes { sequence, .. }
12903            | Self::SideEffect { sequence, .. }
12904            | Self::VersionMarker { sequence, .. }
12905            | Self::Memo { sequence, .. } => *sequence,
12906            Self::ServiceOperation { sequence, .. } => *sequence,
12907        }
12908    }
12909
12910    fn shape(&self) -> &'static str {
12911        match self {
12912            Self::CancellationScope { .. } => "cancellation scope",
12913            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12914                "cooperative cancellation"
12915            }
12916            Self::Activity { .. } => "activity",
12917            Self::Timer { .. } => "timer",
12918            Self::ChildWorkflow { .. } => "child workflow",
12919            Self::SignalWait { .. } => "signal wait",
12920            Self::ConditionWait { .. } => "condition wait",
12921            Self::SearchAttributes { .. } => "search-attribute update",
12922            Self::SideEffect { .. } => "side effect",
12923            Self::VersionMarker { .. } => "version marker",
12924            Self::Memo { .. } => "memo upsert",
12925            Self::ServiceOperation { .. } => "service operation",
12926        }
12927    }
12928}
12929
12930fn ensure_version_supported(
12931    change_id: &str,
12932    version: i32,
12933    min_supported: i32,
12934    max_supported: i32,
12935    sequence: u64,
12936) -> Result<()> {
12937    if (min_supported..=max_supported).contains(&version) {
12938        return Ok(());
12939    }
12940    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12941        "version_marker_incompatible_range",
12942        (sequence != 0).then_some(sequence),
12943        Some(format!("{min_supported}..={max_supported}")),
12944        Some(format!("{change_id}:{version}")),
12945        "recorded workflow version is outside the range supported by current code",
12946    )))
12947}
12948
12949#[derive(Clone, Debug)]
12950struct ResumeSignal {
12951    signal_name: String,
12952    arguments: Vec<AvroValue>,
12953}
12954
12955const MAX_PARALLEL_OPERATIONS: usize = 1000;
12956
12957fn parallel_group_prefix(kind: &str) -> &'static str {
12958    match kind {
12959        "activity" => "parallel-activities",
12960        "child" => "parallel-children",
12961        "timer" => "parallel-timers",
12962        _ => "parallel-calls",
12963    }
12964}
12965
12966fn parallel_group_entry(
12967    base_sequence: u64,
12968    size: usize,
12969    index: usize,
12970    kind: &str,
12971) -> ParallelGroupMetadata {
12972    ParallelGroupMetadata {
12973        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12974        parallel_group_kind: kind.to_string(),
12975        parallel_group_base_sequence: base_sequence,
12976        parallel_group_size: size,
12977        parallel_group_index: index,
12978        parallel_group_mode: None,
12979        selection_member_key: None,
12980        selection_member_index: None,
12981        selection_member_base_sequence: None,
12982        selection_member_size: None,
12983        selection_member_kind: None,
12984    }
12985}
12986
12987struct SelectionMemberMetadata {
12988    key: SelectionKey,
12989    index: usize,
12990    base_sequence: u64,
12991    size: usize,
12992    kind: String,
12993}
12994
12995fn selection_group_entry(
12996    base_sequence: u64,
12997    size: usize,
12998    index: usize,
12999    kind: &str,
13000    member: &SelectionMemberMetadata,
13001) -> ParallelGroupMetadata {
13002    ParallelGroupMetadata {
13003        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
13004        parallel_group_kind: kind.to_string(),
13005        parallel_group_base_sequence: base_sequence,
13006        parallel_group_size: size,
13007        parallel_group_index: index,
13008        parallel_group_mode: Some("select".to_string()),
13009        selection_member_key: Some(member.key.clone()),
13010        selection_member_index: Some(member.index),
13011        selection_member_base_sequence: Some(member.base_sequence),
13012        selection_member_size: Some(member.size),
13013        selection_member_kind: Some(member.kind.clone()),
13014    }
13015}
13016
13017fn apply_parallel_group_path(
13018    command: &mut serde_json::Map<String, Value>,
13019    path: &[ParallelGroupMetadata],
13020) {
13021    let Some(inner) = path.last() else {
13022        return;
13023    };
13024    command.insert(
13025        "parallel_group_id".to_string(),
13026        json!(inner.parallel_group_id),
13027    );
13028    command.insert(
13029        "parallel_group_kind".to_string(),
13030        json!(inner.parallel_group_kind),
13031    );
13032    command.insert(
13033        "parallel_group_base_sequence".to_string(),
13034        json!(inner.parallel_group_base_sequence),
13035    );
13036    command.insert(
13037        "parallel_group_size".to_string(),
13038        json!(inner.parallel_group_size),
13039    );
13040    command.insert(
13041        "parallel_group_index".to_string(),
13042        json!(inner.parallel_group_index),
13043    );
13044    if let Some(mode) = &inner.parallel_group_mode {
13045        command.insert("parallel_group_mode".to_string(), json!(mode));
13046    }
13047    if let Some(key) = &inner.selection_member_key {
13048        command.insert("selection_member_key".to_string(), json!(key));
13049    }
13050    if let Some(index) = inner.selection_member_index {
13051        command.insert("selection_member_index".to_string(), json!(index));
13052    }
13053    if let Some(base_sequence) = inner.selection_member_base_sequence {
13054        command.insert(
13055            "selection_member_base_sequence".to_string(),
13056            json!(base_sequence),
13057        );
13058    }
13059    if let Some(size) = inner.selection_member_size {
13060        command.insert("selection_member_size".to_string(), json!(size));
13061    }
13062    if let Some(kind) = &inner.selection_member_kind {
13063        command.insert("selection_member_kind".to_string(), json!(kind));
13064    }
13065    command.insert("parallel_group_path".to_string(), json!(path));
13066}
13067
13068fn ensure_parallel_path_matches(
13069    sequence: u64,
13070    recorded: Option<&[ParallelGroupMetadata]>,
13071    expected: &[ParallelGroupMetadata],
13072) -> Result<()> {
13073    match (recorded, expected.is_empty()) {
13074        (None, true) => Ok(()),
13075        (Some(recorded), false) if recorded == expected => Ok(()),
13076        (None, false) => Err(invalid_recorded_history(
13077            "parallel_group_metadata_missing",
13078            sequence,
13079            &serde_json::to_string(expected).unwrap_or_default(),
13080            "<missing>",
13081            "recorded parallel member is missing its durable group path",
13082        )),
13083        (Some(recorded), true) => Err(invalid_recorded_history(
13084            "parallel_group_shape_mismatch",
13085            sequence,
13086            "sequential command",
13087            &serde_json::to_string(recorded).unwrap_or_default(),
13088            "recorded command belonged to a parallel group but current code schedules it sequentially",
13089        )),
13090        (Some(recorded), false) => Err(invalid_recorded_history(
13091            "parallel_group_shape_mismatch",
13092            sequence,
13093            &serde_json::to_string(recorded).unwrap_or_default(),
13094            &serde_json::to_string(expected).unwrap_or_default(),
13095            "recorded parallel-group identity or path changed during replay",
13096        )),
13097    }
13098}
13099
13100#[derive(Clone, Debug)]
13101enum ParallelShape {
13102    Leaf,
13103    Group(Vec<ParallelShape>),
13104}
13105
13106struct ParallelDescriptor {
13107    operation: ParallelOperation,
13108    offset: usize,
13109    member_path: Vec<usize>,
13110    group_path: Vec<ParallelGroupMetadata>,
13111}
13112
13113fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13114    operations
13115        .iter()
13116        .map(|operation| match operation {
13117            ParallelOperation::Group(children) => parallel_leaf_count(children),
13118            _ => 1,
13119        })
13120        .sum()
13121}
13122
13123fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13124    match operation {
13125        ParallelOperation::Activity { .. } => Some("activity"),
13126        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13127        ParallelOperation::Timer(_) => Some("timer"),
13128        ParallelOperation::Signal(_) => Some("signal"),
13129        ParallelOperation::Condition { .. } => Some("condition"),
13130        ParallelOperation::Group(children) => parallel_group_kind(children),
13131    }
13132}
13133
13134fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13135    let mut kind = None;
13136    for operation in operations {
13137        let Some(operation_kind) = parallel_operation_kind(operation) else {
13138            continue;
13139        };
13140        match kind {
13141            None => kind = Some(operation_kind),
13142            Some(current) if current == operation_kind => {}
13143            Some(_) => return Some("mixed"),
13144        }
13145    }
13146    kind
13147}
13148
13149fn validate_parallel_operations(
13150    operations: &[ParallelOperation],
13151    member_path: &mut Vec<usize>,
13152    root: bool,
13153) -> Result<()> {
13154    let leaves = parallel_leaf_count(operations);
13155    if leaves > MAX_PARALLEL_OPERATIONS {
13156        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13157            reason: "fan_out_limit_exceeded",
13158            member_path: member_path.clone(),
13159            message: format!(
13160                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13161            ),
13162        }));
13163    }
13164    if !root && operations.is_empty() {
13165        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13166            reason: "nested_group_empty",
13167            member_path: member_path.clone(),
13168            message: "a nested group must contain at least one durable leaf".to_string(),
13169        }));
13170    }
13171
13172    for (index, operation) in operations.iter().enumerate() {
13173        member_path.push(index);
13174        match operation {
13175            ParallelOperation::Activity {
13176                options, arguments, ..
13177            } => {
13178                options
13179                    .validate()
13180                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13181                if let Err(error) = arguments {
13182                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13183                        reason: "arguments_invalid",
13184                        member_path: member_path.clone(),
13185                        message: error.to_string(),
13186                    }));
13187                }
13188            }
13189            ParallelOperation::ChildWorkflow {
13190                options, arguments, ..
13191            } => {
13192                validate_parallel_child_options(options)?;
13193                if let Err(error) = arguments {
13194                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13195                        reason: "arguments_invalid",
13196                        member_path: member_path.clone(),
13197                        message: error.to_string(),
13198                    }));
13199                }
13200            }
13201            ParallelOperation::Timer(duration)
13202                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13203            {
13204                return Err(Error::TimerDurationOverflow);
13205            }
13206            ParallelOperation::Timer(_) => {}
13207            ParallelOperation::Signal(signal_name) => {
13208                validate_user_signal_name(signal_name)?;
13209                if signal_name.trim().is_empty() {
13210                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13211                        reason: "signal_name_empty",
13212                        member_path: member_path.clone(),
13213                        message: "signal wait name must not be empty".to_string(),
13214                    }));
13215                }
13216            }
13217            ParallelOperation::Condition { options, .. } => {
13218                options.validate()?;
13219            }
13220            ParallelOperation::Group(children) => {
13221                validate_parallel_operations(children, member_path, false)?;
13222            }
13223        }
13224        member_path.pop();
13225    }
13226    Ok(())
13227}
13228
13229fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13230    if options.task_queue.trim().is_empty() {
13231        return Err(Error::InvalidChildWorkflowOptions(
13232            "task_queue must not be empty".to_string(),
13233        ));
13234    }
13235    for (name, value) in [
13236        (
13237            "execution_timeout_seconds",
13238            options.execution_timeout_seconds,
13239        ),
13240        ("run_timeout_seconds", options.run_timeout_seconds),
13241    ] {
13242        if value == Some(0) {
13243            return Err(Error::InvalidChildWorkflowOptions(format!(
13244                "{name} must be at least 1"
13245            )));
13246        }
13247    }
13248    if options
13249        .retry_policy
13250        .as_ref()
13251        .is_some_and(|policy| policy.max_attempts == Some(0))
13252    {
13253        return Err(Error::InvalidChildWorkflowOptions(
13254            "retry_policy.max_attempts must be at least 1".to_string(),
13255        ));
13256    }
13257    Ok(())
13258}
13259
13260fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13261    ParallelShape::Group(
13262        operations
13263            .iter()
13264            .map(|operation| match operation {
13265                ParallelOperation::Group(children) => parallel_shape(children),
13266                _ => ParallelShape::Leaf,
13267            })
13268            .collect(),
13269    )
13270}
13271
13272fn parallel_descriptors(
13273    operations: Vec<ParallelOperation>,
13274    base_sequence: u64,
13275) -> Result<Vec<ParallelDescriptor>> {
13276    let size = parallel_leaf_count(&operations);
13277    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13278    let mut descriptors = Vec::with_capacity(size);
13279    let mut cursor = 0;
13280
13281    for (index, operation) in operations.into_iter().enumerate() {
13282        match operation {
13283            ParallelOperation::Group(children) => {
13284                let child_base = base_sequence
13285                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13286                    .ok_or(Error::TimerDurationOverflow)?;
13287                for mut descriptor in parallel_descriptors(children, child_base)? {
13288                    let outer_index = cursor + descriptor.offset;
13289                    descriptor.group_path.insert(
13290                        0,
13291                        parallel_group_entry(base_sequence, size, outer_index, kind),
13292                    );
13293                    descriptor.member_path.insert(0, index);
13294                    descriptor.offset = outer_index;
13295                    descriptors.push(descriptor);
13296                }
13297                cursor = descriptors.len();
13298            }
13299            operation => {
13300                descriptors.push(ParallelDescriptor {
13301                    operation,
13302                    offset: cursor,
13303                    member_path: vec![index],
13304                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13305                });
13306                cursor += 1;
13307            }
13308        }
13309    }
13310    Ok(descriptors)
13311}
13312
13313enum ParallelLeafCall {
13314    Activity(ActivityCall),
13315    ChildWorkflow(ChildWorkflowCall),
13316    Timer(TimerCall),
13317    Signal(SignalCall),
13318    Condition(ConditionWaitCall),
13319}
13320
13321fn parallel_leaf_call(
13322    ctx: &WorkflowContext,
13323    operation: ParallelOperation,
13324    parallel_group_path: Vec<ParallelGroupMetadata>,
13325) -> ParallelLeafCall {
13326    match operation {
13327        ParallelOperation::Activity {
13328            activity_type,
13329            options,
13330            arguments,
13331        } => ParallelLeafCall::Activity(ActivityCall {
13332            ctx: ctx.clone(),
13333            activity_type,
13334            options,
13335            worker_session: None,
13336            args: Some(arguments),
13337            scheduled: false,
13338            local: false,
13339            local_result: None,
13340            parallel_group_path,
13341        }),
13342        ParallelOperation::ChildWorkflow {
13343            workflow_type,
13344            options,
13345            arguments,
13346        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13347            ctx: ctx.clone(),
13348            workflow_type,
13349            options,
13350            args: Some(arguments),
13351            scheduled: false,
13352            matched_pending: false,
13353            parallel_group_path,
13354        }),
13355        ParallelOperation::Timer(duration) => {
13356            let delay_seconds = duration
13357                .as_secs()
13358                .checked_add(u64::from(duration.subsec_nanos() > 0));
13359            ParallelLeafCall::Timer(TimerCall {
13360                ctx: ctx.clone(),
13361                delay_seconds,
13362                scheduled: false,
13363                matched_pending: false,
13364                parallel_group_path,
13365            })
13366        }
13367        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
13368            ctx: ctx.clone(),
13369            signal_name,
13370            runtime_reserved_allowed: false,
13371            opened_wait: false,
13372            matched_pending: false,
13373            parallel_group_path,
13374        }),
13375        ParallelOperation::Condition { options, predicate } => {
13376            ParallelLeafCall::Condition(ConditionWaitCall {
13377                ctx: ctx.clone(),
13378                options,
13379                predicate,
13380                occurrence_id: None,
13381                opened_wait: false,
13382                parallel_group_path,
13383            })
13384        }
13385        ParallelOperation::Group(_) => {
13386            unreachable!("parallel descriptors contain only durable leaves")
13387        }
13388    }
13389}
13390
13391impl ParallelLeafCall {
13392    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
13393        match self {
13394            Self::Activity(call) => Pin::new(call)
13395                .poll_avro_value(cx)
13396                .map_ok(ParallelAvroResult::Activity),
13397            Self::ChildWorkflow(call) => Pin::new(call)
13398                .poll_avro_value(cx)
13399                .map_ok(ParallelAvroResult::ChildWorkflow),
13400            Self::Timer(call) => Pin::new(call)
13401                .poll(cx)
13402                .map_ok(|()| ParallelAvroResult::Timer),
13403            Self::Signal(call) => Pin::new(call)
13404                .poll_avro_value(cx)
13405                .map_ok(ParallelAvroResult::Signal),
13406            Self::Condition(call) => Pin::new(call)
13407                .poll(cx)
13408                .map_ok(ParallelAvroResult::Condition),
13409        }
13410    }
13411}
13412
13413struct ParallelLeaf {
13414    call: ParallelLeafCall,
13415    sequence: u64,
13416    member_path: Vec<usize>,
13417    group_path: Vec<ParallelGroupMetadata>,
13418    result: Option<ParallelAvroResult>,
13419}
13420
13421/// Future returned by [`WorkflowContext::parallel`].
13422pub struct ParallelCall {
13423    ctx: WorkflowContext,
13424    operations: Option<Vec<ParallelOperation>>,
13425    shape: Option<ParallelShape>,
13426    leaves: Vec<ParallelLeaf>,
13427    pending_scope_delivery: bool,
13428    worker_session: Option<WorkerSessionOptions>,
13429}
13430
13431impl ParallelCall {
13432    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
13433        Self {
13434            ctx,
13435            operations: Some(operations),
13436            shape: None,
13437            leaves: Vec::new(),
13438            pending_scope_delivery: false,
13439            worker_session: None,
13440        }
13441    }
13442
13443    fn initialize(&mut self) -> Result<()> {
13444        if let Some(session) = &self.worker_session {
13445            session.to_wire()?;
13446        }
13447        let operations = self.operations.take().unwrap_or_default();
13448        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
13449        self.shape = Some(parallel_shape(&operations));
13450        if operations.is_empty() {
13451            return Ok(());
13452        }
13453
13454        let base_sequence = {
13455            let state = self
13456                .ctx
13457                .state
13458                .lock()
13459                .map_err(|_| Error::WorkflowStatePoisoned)?;
13460            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13461                recorded.sequence()
13462            } else {
13463                let last = state
13464                    .recorded_commands
13465                    .last()
13466                    .map(RecordedCommand::sequence)
13467                    .unwrap_or(0);
13468                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13469                    .and_then(|sequence| sequence.checked_add(1))
13470                    .ok_or_else(|| {
13471                        Error::InvalidParallelGroup(ParallelGroupError {
13472                            reason: "sequence_overflow",
13473                            member_path: Vec::new(),
13474                            message: "parallel group sequence identity overflowed u64".to_string(),
13475                        })
13476                    })?
13477            }
13478        };
13479
13480        let descriptors = parallel_descriptors(operations, base_sequence)?;
13481        {
13482            let mut state = self
13483                .ctx
13484                .state
13485                .lock()
13486                .map_err(|_| Error::WorkflowStatePoisoned)?;
13487            let cursor = state.command_cursor;
13488            self.ctx.validate_scope_membership(&mut state, cursor)?;
13489            if state.prepare_parallel_scope_cancellation(&descriptors)? {
13490                self.pending_scope_delivery = true;
13491                return Ok(());
13492            }
13493            state.expand_cancellation_group(&descriptors)?;
13494            state.prepare_group_cancellation(&descriptors)?;
13495        }
13496        self.leaves = descriptors
13497            .into_iter()
13498            .map(|descriptor| {
13499                let mut call = parallel_leaf_call(
13500                    &self.ctx,
13501                    descriptor.operation,
13502                    descriptor.group_path.clone(),
13503                );
13504                if let (Some(session), ParallelLeafCall::Activity(activity)) =
13505                    (&self.worker_session, &mut call)
13506                {
13507                    activity.worker_session = Some(session.clone());
13508                }
13509                ParallelLeaf {
13510                    call,
13511                    sequence: base_sequence + descriptor.offset as u64,
13512                    member_path: descriptor.member_path,
13513                    group_path: descriptor.group_path,
13514                    result: None,
13515                }
13516            })
13517            .collect();
13518        Ok(())
13519    }
13520
13521    fn poll_avro_value(
13522        mut self: Pin<&mut Self>,
13523        cx: &mut TaskContext<'_>,
13524    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
13525        if self.operations.is_some() {
13526            if let Err(error) = self.initialize() {
13527                return Poll::Ready(Err(error));
13528            }
13529        }
13530        if self.pending_scope_delivery {
13531            return Poll::Pending;
13532        }
13533        if self.leaves.is_empty() {
13534            return Poll::Ready(Ok(Vec::new()));
13535        }
13536
13537        let mut failures = Vec::new();
13538        let mut pending = false;
13539        for (index, leaf) in self.leaves.iter_mut().enumerate() {
13540            if leaf.result.is_some() {
13541                continue;
13542            }
13543            match leaf.call.poll_avro_value(cx) {
13544                Poll::Ready(Ok(result)) => leaf.result = Some(result),
13545                Poll::Ready(Err(error)) => failures.push((index, error)),
13546                Poll::Pending => pending = true,
13547            }
13548        }
13549
13550        if !failures.is_empty() {
13551            if let Some(position) = failures
13552                .iter()
13553                .position(|(_, error)| workflow_task_integrity_error(error))
13554            {
13555                return Poll::Ready(Err(failures.remove(position).1));
13556            }
13557            if self
13558                .ctx
13559                .state
13560                .lock()
13561                .map_err(|_| Error::WorkflowStatePoisoned)?
13562                .cancellation_delivery_intent
13563                .is_some()
13564            {
13565                return Poll::Pending;
13566            }
13567            if let Some(position) = failures
13568                .iter()
13569                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
13570            {
13571                return Poll::Ready(Err(failures.remove(position).1));
13572            }
13573            failures.sort_by_key(|(index, _)| *index);
13574            let (failed_index, cause) = failures.remove(0);
13575            let failed = &self.leaves[failed_index];
13576            let completed = self
13577                .leaves
13578                .iter()
13579                .filter_map(|leaf| {
13580                    leaf.result
13581                        .clone()
13582                        .and_then(|result| result.into_json_result().ok())
13583                        .map(|result| ParallelCompletion {
13584                            member_path: leaf.member_path.clone(),
13585                            result,
13586                        })
13587                })
13588                .collect();
13589            let group_id = failed
13590                .group_path
13591                .first()
13592                .map(|entry| entry.parallel_group_id.clone())
13593                .unwrap_or_default();
13594            let sequences = self
13595                .leaves
13596                .iter()
13597                .map(|leaf| leaf.sequence)
13598                .collect::<Vec<_>>();
13599            self.ctx
13600                .state
13601                .lock()
13602                .map_err(|_| Error::WorkflowStatePoisoned)?
13603                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
13604            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
13605                group_id,
13606                member_path: failed.member_path.clone(),
13607                group_path: failed.group_path.clone(),
13608                completed,
13609                cause: Box::new(cause),
13610            })));
13611        }
13612        if pending
13613            || self
13614                .ctx
13615                .state
13616                .lock()
13617                .map_err(|_| Error::WorkflowStatePoisoned)?
13618                .cancellation_delivery_intent
13619                .is_some()
13620        {
13621            return Poll::Pending;
13622        }
13623
13624        let mut flat_results = self
13625            .leaves
13626            .iter_mut()
13627            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
13628            .collect::<Vec<_>>()
13629            .into_iter();
13630        let results = parallel_results_for_shape(
13631            self.shape.as_ref().expect("initialized parallel shape"),
13632            &mut flat_results,
13633        );
13634        let sequences = self
13635            .leaves
13636            .iter()
13637            .map(|leaf| leaf.sequence)
13638            .collect::<Vec<_>>();
13639        self.ctx
13640            .state
13641            .lock()
13642            .map_err(|_| Error::WorkflowStatePoisoned)?
13643            .advance_cancellation_sequences(&sequences, None);
13644        Poll::Ready(Ok(match results {
13645            ParallelAvroResult::Group(results) => results,
13646            ParallelAvroResult::Activity(_)
13647            | ParallelAvroResult::ChildWorkflow(_)
13648            | ParallelAvroResult::Timer
13649            | ParallelAvroResult::Signal(_)
13650            | ParallelAvroResult::Condition(_) => {
13651                unreachable!("root parallel shape is a group")
13652            }
13653        }))
13654    }
13655}
13656
13657fn parallel_results_for_shape(
13658    shape: &ParallelShape,
13659    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13660) -> ParallelAvroResult {
13661    match shape {
13662        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13663        ParallelShape::Group(children) => ParallelAvroResult::Group(
13664            children
13665                .iter()
13666                .map(|child| parallel_results_for_shape(child, flat_results))
13667                .collect(),
13668        ),
13669    }
13670}
13671
13672impl Future for ParallelCall {
13673    type Output = Result<Vec<ParallelResult>>;
13674
13675    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13676        self.poll_avro_value(cx)
13677            .map_ok(|results| {
13678                results
13679                    .into_iter()
13680                    .map(ParallelAvroResult::into_json_result)
13681                    .collect::<Result<Vec<_>>>()
13682            })
13683            .map_ok(|result| result)
13684            .flatten_result()
13685    }
13686}
13687
13688#[derive(Clone, Debug)]
13689struct SelectionMemberPlan {
13690    key: SelectionKey,
13691    index: usize,
13692    base_sequence: u64,
13693    size: usize,
13694    kind: String,
13695    shape: ParallelShape,
13696    leaf_start: usize,
13697}
13698
13699fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13700    match operation {
13701        ParallelOperation::Activity { .. } => "activity",
13702        ParallelOperation::ChildWorkflow { .. } => "child",
13703        ParallelOperation::Timer(_) => "timer",
13704        ParallelOperation::Signal(_) => "signal",
13705        ParallelOperation::Condition { .. } => "condition",
13706        ParallelOperation::Group(_) => "group",
13707    }
13708}
13709
13710fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13711    match operation {
13712        ParallelOperation::Group(children) => parallel_shape(children),
13713        _ => ParallelShape::Leaf,
13714    }
13715}
13716
13717fn selection_descriptors(
13718    operations: Vec<(SelectionKey, ParallelOperation)>,
13719    base_sequence: u64,
13720) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13721    if operations.is_empty() {
13722        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13723            reason: "selection_empty",
13724            member_path: Vec::new(),
13725            message: "durable selection requires at least one operation".to_string(),
13726        }));
13727    }
13728    let operation_refs = operations
13729        .iter()
13730        .map(|(_, operation)| operation)
13731        .collect::<Vec<_>>();
13732    let total_size = operation_refs
13733        .iter()
13734        .map(|operation| match operation {
13735            ParallelOperation::Group(children) => parallel_leaf_count(children),
13736            _ => 1,
13737        })
13738        .sum::<usize>();
13739    if total_size > MAX_PARALLEL_OPERATIONS {
13740        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13741            reason: "fan_out_limit_exceeded",
13742            member_path: Vec::new(),
13743            message: format!(
13744                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13745            ),
13746        }));
13747    }
13748    let group_kind = {
13749        let mut kind = None;
13750        for operation in &operation_refs {
13751            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13752            match kind {
13753                None => kind = Some(operation_kind),
13754                Some(current) if current == operation_kind => {}
13755                Some(_) => {
13756                    kind = Some("mixed");
13757                    break;
13758                }
13759            }
13760        }
13761        kind.unwrap_or("mixed")
13762    };
13763
13764    let mut descriptors = Vec::with_capacity(total_size);
13765    let mut members = Vec::with_capacity(operations.len());
13766    let mut cursor = 0usize;
13767    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13768    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13769        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13770            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13771                reason: "selection_key_invalid",
13772                member_path: vec![member_index],
13773                message: "selection member keys must be non-empty strings or non-negative integers"
13774                    .to_string(),
13775            }));
13776        }
13777        if seen_keys.contains(&key) {
13778            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13779                reason: "selection_key_duplicate",
13780                member_path: vec![member_index],
13781                message: format!("selection member key {key:?} is duplicated"),
13782            }));
13783        }
13784        seen_keys.push(key.clone());
13785        let member_size = match &operation {
13786            ParallelOperation::Group(children) => parallel_leaf_count(children),
13787            _ => 1,
13788        };
13789        if member_size == 0 {
13790            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13791                reason: "selection_member_empty",
13792                member_path: vec![member_index],
13793                message: "a selection member must contain at least one durable leaf".to_string(),
13794            }));
13795        }
13796        let member_base = base_sequence
13797            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13798            .ok_or(Error::TimerDurationOverflow)?;
13799        let member_kind = selection_operation_kind(&operation).to_string();
13800        let member_shape = selection_operation_shape(&operation);
13801        let leaf_start = descriptors.len();
13802        match operation {
13803            ParallelOperation::Group(children) => {
13804                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13805                for mut descriptor in parallel_descriptors(children, member_base)? {
13806                    let flat_index = cursor + descriptor.offset;
13807                    descriptor.group_path.insert(
13808                        0,
13809                        selection_group_entry(
13810                            base_sequence,
13811                            total_size,
13812                            flat_index,
13813                            group_kind,
13814                            &SelectionMemberMetadata {
13815                                key: key.clone(),
13816                                index: member_index,
13817                                base_sequence: member_base,
13818                                size: member_size,
13819                                kind: member_kind.clone(),
13820                            },
13821                        ),
13822                    );
13823                    descriptor.member_path.insert(0, member_index);
13824                    descriptor.offset = flat_index;
13825                    descriptors.push(descriptor);
13826                }
13827            }
13828            operation => {
13829                validate_parallel_operations(
13830                    std::slice::from_ref(&operation),
13831                    &mut Vec::new(),
13832                    true,
13833                )?;
13834                descriptors.push(ParallelDescriptor {
13835                    operation,
13836                    offset: cursor,
13837                    member_path: vec![member_index],
13838                    group_path: vec![selection_group_entry(
13839                        base_sequence,
13840                        total_size,
13841                        cursor,
13842                        group_kind,
13843                        &SelectionMemberMetadata {
13844                            key: key.clone(),
13845                            index: member_index,
13846                            base_sequence: member_base,
13847                            size: member_size,
13848                            kind: member_kind.clone(),
13849                        },
13850                    )],
13851                });
13852            }
13853        }
13854        members.push(SelectionMemberPlan {
13855            key,
13856            index: member_index,
13857            base_sequence: member_base,
13858            size: member_size,
13859            kind: member_kind,
13860            shape: member_shape,
13861            leaf_start,
13862        });
13863        cursor += member_size;
13864    }
13865    Ok((descriptors, members))
13866}
13867
13868struct SelectionLeaf {
13869    call: ParallelLeafCall,
13870    outcome: Option<Result<ParallelAvroResult>>,
13871}
13872
13873/// Stable reference to one member of a durable selection group.
13874#[derive(Clone)]
13875pub struct DurableOperationHandle {
13876    ctx: WorkflowContext,
13877    pub key: SelectionKey,
13878    pub index: usize,
13879    pub kind: String,
13880    pub identity: String,
13881    pub base_sequence: u64,
13882    pub size: usize,
13883    pub selection_group_id: String,
13884    shape: ParallelShape,
13885}
13886
13887impl std::fmt::Debug for DurableOperationHandle {
13888    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13889        formatter
13890            .debug_struct("DurableOperationHandle")
13891            .field("key", &self.key)
13892            .field("index", &self.index)
13893            .field("kind", &self.kind)
13894            .field("identity", &self.identity)
13895            .field("base_sequence", &self.base_sequence)
13896            .field("size", &self.size)
13897            .field("selection_group_id", &self.selection_group_id)
13898            .finish()
13899    }
13900}
13901
13902impl DurableOperationHandle {
13903    /// Await this member after another member has already won the selection.
13904    pub fn await_result(&self) -> DurableOperationAwaitCall {
13905        DurableOperationAwaitCall {
13906            handle: self.clone(),
13907        }
13908    }
13909
13910    /// Request cancellation without affecting siblings. The future resolves
13911    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13912    /// beat a concurrently committed terminal result.
13913    pub fn cancel(&self) -> CancelDurableOperationCall {
13914        CancelDurableOperationCall {
13915            handle: self.clone(),
13916            emitted: false,
13917        }
13918    }
13919}
13920
13921/// The one winner committed for a durable selection group.
13922#[derive(Debug)]
13923pub struct SelectionResult {
13924    pub key: SelectionKey,
13925    pub index: usize,
13926    pub kind: String,
13927    pub identity: String,
13928    pub value: Option<ParallelResult>,
13929    pub failure: Option<Error>,
13930    pub winner: DurableOperationHandle,
13931    pub handles: Vec<DurableOperationHandle>,
13932}
13933
13934impl SelectionResult {
13935    pub fn succeeded(&self) -> bool {
13936        self.failure.is_none()
13937    }
13938
13939    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13940        self.handles.iter().find(|handle| &handle.key == key)
13941    }
13942
13943    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13944        self.handles
13945            .iter()
13946            .filter(|handle| handle.index != self.index)
13947            .collect()
13948    }
13949
13950    pub fn into_result(self) -> Result<ParallelResult> {
13951        match (self.value, self.failure) {
13952            (Some(value), None) => Ok(value),
13953            (_, Some(error)) => Err(error),
13954            _ => Err(Error::WorkerLoop(
13955                "selection result contained neither a value nor a failure".to_string(),
13956            )),
13957        }
13958    }
13959}
13960
13961/// Future returned by [`WorkflowContext::select`].
13962pub struct SelectCall {
13963    ctx: WorkflowContext,
13964    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13965    members: Vec<SelectionMemberPlan>,
13966    leaves: Vec<SelectionLeaf>,
13967    group_id: Option<String>,
13968}
13969
13970impl SelectCall {
13971    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13972        Self {
13973            ctx,
13974            operations: Some(operations),
13975            members: Vec::new(),
13976            leaves: Vec::new(),
13977            group_id: None,
13978        }
13979    }
13980
13981    fn initialize(&mut self) -> Result<()> {
13982        let operations = self.operations.take().unwrap_or_default();
13983        let base_sequence = {
13984            let state = self
13985                .ctx
13986                .state
13987                .lock()
13988                .map_err(|_| Error::WorkflowStatePoisoned)?;
13989            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13990                state.recorded_commands.get(state.command_cursor)
13991            {
13992                *sequence
13993            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13994            {
13995                marker.selection_group_base_sequence
13996            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13997                recorded.sequence()
13998            } else {
13999                let last = state
14000                    .recorded_commands
14001                    .last()
14002                    .map(RecordedCommand::sequence)
14003                    .unwrap_or(0);
14004                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
14005                    .and_then(|sequence| sequence.checked_add(1))
14006                    .ok_or(Error::TimerDurationOverflow)?
14007            }
14008        };
14009        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
14010        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
14011        {
14012            let mut state = self
14013                .ctx
14014                .state
14015                .lock()
14016                .map_err(|_| Error::WorkflowStatePoisoned)?;
14017            state.expand_cancellation_group(&descriptors)?;
14018            state.prepare_group_cancellation(&descriptors)?;
14019        }
14020        self.leaves = descriptors
14021            .into_iter()
14022            .map(|descriptor| SelectionLeaf {
14023                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
14024                outcome: None,
14025            })
14026            .collect();
14027        self.members = members;
14028        self.group_id = Some(group_id);
14029        Ok(())
14030    }
14031}
14032
14033impl Future for SelectCall {
14034    type Output = Result<SelectionResult>;
14035
14036    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14037        if self.operations.is_some() {
14038            if let Err(error) = self.initialize() {
14039                return Poll::Ready(Err(error));
14040            }
14041        }
14042
14043        for leaf in &mut self.leaves {
14044            if leaf.outcome.is_some() {
14045                continue;
14046            }
14047            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14048                if outcome
14049                    .as_ref()
14050                    .err()
14051                    .is_some_and(workflow_task_integrity_error)
14052                {
14053                    return Poll::Ready(outcome.map(|_| unreachable!()));
14054                }
14055                leaf.outcome = Some(outcome);
14056            }
14057        }
14058
14059        if self
14060            .ctx
14061            .state
14062            .lock()
14063            .map_err(|_| Error::WorkflowStatePoisoned)?
14064            .cancellation_delivery_intent
14065            .is_some()
14066        {
14067            return Poll::Pending;
14068        }
14069
14070        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14071            matches!(
14072                leaf.outcome,
14073                Some(Err(Error::CooperativeCancellationRequested(_)))
14074            )
14075        }) {
14076            return Poll::Ready(
14077                leaf.outcome
14078                    .take()
14079                    .expect("matched cancellation")
14080                    .map(|_| unreachable!()),
14081            );
14082        }
14083
14084        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14085        let selection_member_range = self
14086            .members
14087            .first()
14088            .map(|member| member.base_sequence)
14089            .zip(self.leaves.len().try_into().ok())
14090            .map(|(base_sequence, size): (u64, u64)| {
14091                base_sequence..base_sequence.saturating_add(size)
14092            });
14093        let marker = {
14094            let mut state = match self.ctx.state.lock() {
14095                Ok(state) => state,
14096                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14097            };
14098            let marker = state
14099                .selection_markers
14100                .get(state.selection_marker_cursor)
14101                .cloned();
14102            if marker.is_none()
14103                && all_members_terminal
14104                && selection_member_range.as_ref().is_some_and(|member_range| {
14105                    state
14106                        .recorded_commands
14107                        .iter()
14108                        .any(|command| member_range.contains(&command.sequence()))
14109                })
14110            {
14111                // Terminal member history can be committed before the server's
14112                // SelectionResolved marker becomes visible to this task. That
14113                // marker is the durable barrier the selection is still waiting
14114                // on, so an otherwise commandless replay remains legitimately
14115                // pending instead of failing as an untracked yield.
14116                state.matched_recorded_pending = true;
14117            }
14118            marker
14119        };
14120        let Some(marker) = marker else {
14121            return Poll::Pending;
14122        };
14123        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14124            || marker.selection_group_size != self.leaves.len()
14125            || self.members.first().map(|member| member.base_sequence)
14126                != Some(marker.selection_group_base_sequence)
14127        {
14128            return Poll::Ready(Err(invalid_recorded_history(
14129                "selection_group_shape_mismatch",
14130                marker.selection_group_base_sequence,
14131                self.group_id
14132                    .as_deref()
14133                    .unwrap_or("initialized selection group"),
14134                &marker.selection_group_id,
14135                "recorded selection group differs from current workflow code",
14136            )));
14137        }
14138        let Some(member_position) = self.members.iter().position(|member| {
14139            member.key == marker.member_key
14140                && member.index == marker.member_index
14141                && member.base_sequence == marker.member_base_sequence
14142                && member.size == marker.member_size
14143                && member.kind == marker.operation_kind
14144        }) else {
14145            return Poll::Ready(Err(invalid_recorded_history(
14146                "selection_member_shape_mismatch",
14147                marker.member_base_sequence,
14148                "winner member matching current workflow code",
14149                &format!("{:?}", marker.member_key),
14150                "recorded selection winner differs from the authored member identity",
14151            )));
14152        };
14153        let member = self.members[member_position].clone();
14154        let (handles, resolution_sequence) = {
14155            let mut state = match self.ctx.state.lock() {
14156                Ok(state) => state,
14157                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14158            };
14159            let identities = self
14160                .members
14161                .iter()
14162                .map(|candidate| {
14163                    selection_operation_identity(
14164                        &state,
14165                        &candidate.kind,
14166                        candidate.base_sequence,
14167                        candidate.size,
14168                    )
14169                })
14170                .collect::<Vec<_>>();
14171            if let Some((position, missing)) = identities
14172                .iter()
14173                .enumerate()
14174                .find(|(_, identity)| identity.is_empty())
14175                .map(|(position, identity)| (position, identity.clone()))
14176            {
14177                let candidate = &self.members[position];
14178                return Poll::Ready(Err(invalid_recorded_history(
14179                    "selection_operation_identity_missing",
14180                    candidate.base_sequence,
14181                    &format!(
14182                        "durable {} resource identity from scheduled/open history",
14183                        candidate.kind
14184                    ),
14185                    &missing,
14186                    "selection member history is missing its canonical durable identity",
14187                )));
14188            }
14189            let expected_winner_identity = &identities[member_position];
14190            let resolution_sequence = match validated_selection_resolution_sequence(
14191                &state,
14192                &marker,
14193                &member,
14194                expected_winner_identity,
14195            ) {
14196                Ok(sequence) => sequence,
14197                Err(error) => return Poll::Ready(Err(error)),
14198            };
14199            let handles = self
14200                .members
14201                .iter()
14202                .zip(identities)
14203                .map(|(member, identity)| DurableOperationHandle {
14204                    ctx: self.ctx.clone(),
14205                    key: member.key.clone(),
14206                    index: member.index,
14207                    kind: member.kind.clone(),
14208                    identity,
14209                    base_sequence: member.base_sequence,
14210                    size: member.size,
14211                    selection_group_id: marker.selection_group_id.clone(),
14212                    shape: member.shape.clone(),
14213                })
14214                .collect::<Vec<_>>();
14215            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14216                return Poll::Ready(Err(error));
14217            }
14218            state.selection_marker_cursor += 1;
14219            (handles, resolution_sequence)
14220        };
14221
14222        let mut winner_failure = None;
14223        let mut flat_results = Vec::with_capacity(member.size);
14224        if marker.outcome == "failed" {
14225            let resolution_offset = match resolution_sequence
14226                .checked_sub(member.base_sequence)
14227                .and_then(|offset| usize::try_from(offset).ok())
14228            {
14229                Some(offset) if offset < member.size => offset,
14230                _ => {
14231                    return Poll::Ready(Err(invalid_recorded_history(
14232                        "selection_resolution_event_mismatch",
14233                        member.base_sequence,
14234                        "failure event within selected member bounds",
14235                        &resolution_sequence.to_string(),
14236                        "selection failure event is outside the authored member",
14237                    )))
14238                }
14239            };
14240            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14241            match leaf.outcome.take() {
14242                Some(Err(error)) => winner_failure = Some(error),
14243                _ => {
14244                    return Poll::Ready(Err(invalid_recorded_history(
14245                        "selection_winner_outcome_mismatch",
14246                        member.base_sequence,
14247                        "exact failed terminal history referenced by SelectionResolved",
14248                        "missing or successful resolution event",
14249                        "selection winner marker disagrees with terminal operation history",
14250                    )))
14251                }
14252            }
14253        } else {
14254            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14255                match leaf.outcome.take() {
14256                    Some(Ok(result)) => flat_results.push(result),
14257                    Some(Err(_)) => {
14258                        return Poll::Ready(Err(invalid_recorded_history(
14259                            "selection_winner_outcome_mismatch",
14260                            member.base_sequence,
14261                            "fully completed nested selection member",
14262                            "failed durable leaf",
14263                            "completed selection winner contains a failed leaf",
14264                        )))
14265                    }
14266                    None => {
14267                        return Poll::Ready(Err(invalid_recorded_history(
14268                            "selection_winner_unresolved",
14269                            member.base_sequence,
14270                            "terminal history for every completed winner leaf",
14271                            "pending member history",
14272                            "completed SelectionResolved member has an unfinished durable barrier",
14273                        )))
14274                    }
14275                }
14276            }
14277        }
14278        let value = if winner_failure.is_none() {
14279            let mut flat_results = flat_results.into_iter();
14280            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14281            match value.into_json_result() {
14282                Ok(value) => Some(value),
14283                Err(error) => return Poll::Ready(Err(error)),
14284            }
14285        } else {
14286            None
14287        };
14288        let winner = handles[member_position].clone();
14289        self.ctx
14290            .state
14291            .lock()
14292            .map_err(|_| Error::WorkflowStatePoisoned)?
14293            .advance_cancellation_selection(&marker.selection_group_id);
14294        Poll::Ready(Ok(SelectionResult {
14295            key: winner.key.clone(),
14296            index: winner.index,
14297            kind: winner.kind.clone(),
14298            identity: winner.identity.clone(),
14299            value,
14300            failure: winner_failure,
14301            winner,
14302            handles,
14303        }))
14304    }
14305}
14306
14307fn selection_operation_identity(
14308    state: &WorkflowState,
14309    kind: &str,
14310    base_sequence: u64,
14311    size: usize,
14312) -> String {
14313    if kind == "group" {
14314        return format!("group:{base_sequence}:{size}");
14315    }
14316    let fields: &[&str] = match kind {
14317        "activity" => &["activity_execution_id"],
14318        "child" => &["child_workflow_run_id"],
14319        "timer" => &["timer_id"],
14320        "signal" => &["signal_wait_id"],
14321        "condition" => &["condition_wait_id"],
14322        _ => &[],
14323    };
14324    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14325        for event in state
14326            .history_events
14327            .iter()
14328            .filter(|event| durable_event_sequence(event) == Some(sequence))
14329        {
14330            for field in fields {
14331                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14332                    if !identity.is_empty() {
14333                        return identity.to_string();
14334                    }
14335                }
14336            }
14337        }
14338    }
14339    String::new()
14340}
14341
14342fn validated_selection_resolution_sequence(
14343    state: &WorkflowState,
14344    marker: &SelectionMarker,
14345    member: &SelectionMemberPlan,
14346    expected_identity: &str,
14347) -> Result<u64> {
14348    if expected_identity.is_empty() {
14349        return Err(invalid_recorded_history(
14350            "selection_operation_identity_missing",
14351            member.base_sequence,
14352            &format!(
14353                "durable {} resource identity from scheduled/open history",
14354                member.kind
14355            ),
14356            "missing operation identity",
14357            "selection member history is missing its canonical durable identity",
14358        ));
14359    }
14360    if marker.operation_identity != expected_identity {
14361        return Err(invalid_recorded_history(
14362            "selection_operation_identity_mismatch",
14363            member.base_sequence,
14364            expected_identity,
14365            &marker.operation_identity,
14366            "selection winner identity does not match durable scheduled/open history",
14367        ));
14368    }
14369
14370    let failure_types = [
14371        "ActivityFailed",
14372        "ActivityCancelled",
14373        "ActivityTimedOut",
14374        "ChildRunFailed",
14375        "ChildRunCancelled",
14376        "ChildRunTerminated",
14377    ];
14378    let success_types = [
14379        "ActivityCompleted",
14380        "ChildRunCompleted",
14381        "TimerFired",
14382        "SignalApplied",
14383        "ConditionWaitSatisfied",
14384        "ConditionWaitTimedOut",
14385    ];
14386    let terminal_types: &[&str] = if marker.outcome == "failed" {
14387        &failure_types
14388    } else {
14389        &success_types
14390    };
14391    let mut candidates = Vec::new();
14392    let member_commands = (member.base_sequence
14393        ..member.base_sequence.saturating_add(member.size as u64))
14394        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
14395        .map(|command| (command.sequence(), command))
14396        .collect::<BTreeMap<_, _>>();
14397    let mut resolved_conditions = BTreeSet::new();
14398    for event in state.history_events.iter() {
14399        let Some(sequence) = durable_event_sequence(event) else {
14400            continue;
14401        };
14402        let Some(command) = member_commands.get(&sequence) else {
14403            continue;
14404        };
14405        if !terminal_types.contains(&event.event_type.as_str()) {
14406            continue;
14407        }
14408        if matches!(command, RecordedCommand::ConditionWait { .. }) {
14409            if !matches!(
14410                event.event_type.as_str(),
14411                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
14412            ) && !(event.event_type == "TimerFired"
14413                && event.payload.get("timer_kind").and_then(Value::as_str)
14414                    == Some("condition_timeout"))
14415            {
14416                continue;
14417            }
14418            if !resolved_conditions.insert(sequence) {
14419                continue;
14420            }
14421        }
14422        let event_id = event
14423            .raw
14424            .get("id")
14425            .or_else(|| event.raw.get("event_id"))
14426            .and_then(Value::as_str)
14427            .filter(|value| !value.is_empty())
14428            .ok_or_else(|| {
14429                invalid_recorded_history(
14430                    "selection_resolution_event_id_missing",
14431                    member.base_sequence,
14432                    "terminal selection history with a durable event id",
14433                    &event.payload.to_string(),
14434                    "selection terminal history cannot be bound to its winner marker",
14435                )
14436            })?;
14437        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
14438    }
14439    let resolution = if marker.outcome == "failed" {
14440        candidates.first()
14441    } else {
14442        candidates.last()
14443    };
14444    let Some((event_id, event_type, sequence)) = resolution else {
14445        return Err(invalid_recorded_history(
14446            "selection_resolution_event_missing",
14447            member.base_sequence,
14448            "terminal history for the selected member",
14449            &format!("{:?}", marker.member_key),
14450            "selection winner marker has no matching durable terminal event",
14451        ));
14452    };
14453    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
14454        return Err(invalid_recorded_history(
14455            "selection_resolution_event_mismatch",
14456            member.base_sequence,
14457            &format!("{event_type}:{event_id}"),
14458            &format!(
14459                "{}:{}",
14460                marker.resolution_event_type, marker.resolution_event_id
14461            ),
14462            "selection winner marker does not reference the event that made its member terminal",
14463        ));
14464    }
14465    Ok(*sequence)
14466}
14467
14468fn selection_member_recorded_command(
14469    state: &WorkflowState,
14470    authored_sequence: u64,
14471) -> Option<&RecordedCommand> {
14472    let original = state
14473        .recorded_commands
14474        .iter()
14475        .find(|command| command.sequence() == authored_sequence)?;
14476    let RecordedCommand::ConditionWait {
14477        occurrence_id,
14478        parallel_group_path: Some(_),
14479        ..
14480    } = original
14481    else {
14482        return Some(original);
14483    };
14484    // Decoding proves each physical reopen has the same authored identity and
14485    // group path after a satisfied predecessor. Only its latest wait can make
14486    // this logical member terminal.
14487    state
14488        .recorded_commands
14489        .iter()
14490        .filter(|command| {
14491            matches!(command, RecordedCommand::ConditionWait {
14492                occurrence_id: candidate, ..
14493            } if candidate == occurrence_id)
14494        })
14495        .max_by_key(|command| command.sequence())
14496}
14497
14498fn recorded_selection_member_outcome(
14499    state: &WorkflowState,
14500    handle: &DurableOperationHandle,
14501) -> Result<Option<ParallelResult>> {
14502    for event in state.history_events.iter() {
14503        let Some(sequence) = durable_event_sequence(event) else {
14504            continue;
14505        };
14506        if sequence < handle.base_sequence
14507            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
14508            || !matches!(
14509                event.event_type.as_str(),
14510                "ActivityFailed"
14511                    | "ActivityCancelled"
14512                    | "ActivityTimedOut"
14513                    | "ChildRunFailed"
14514                    | "ChildRunCancelled"
14515                    | "ChildRunTerminated"
14516            )
14517        {
14518            continue;
14519        }
14520        let Some(command) = state
14521            .recorded_commands
14522            .iter()
14523            .find(|command| command.sequence() == sequence)
14524        else {
14525            continue;
14526        };
14527        match command {
14528            RecordedCommand::Activity {
14529                outcome: Some(Err(failure)),
14530                ..
14531            } => return Err(Error::ActivityFailed(failure.clone())),
14532            RecordedCommand::ChildWorkflow {
14533                outcome: Some(Err(failure)),
14534                ..
14535            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
14536            _ => {}
14537        }
14538    }
14539
14540    let mut results = Vec::with_capacity(handle.size);
14541    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14542        let Some(command) = selection_member_recorded_command(state, sequence) else {
14543            return Ok(None);
14544        };
14545        let result = match command {
14546            RecordedCommand::Activity { outcome, .. } => match outcome {
14547                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
14548                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
14549                None => return Ok(None),
14550            },
14551            RecordedCommand::Timer { fired, .. } => {
14552                if !fired {
14553                    return Ok(None);
14554                }
14555                ParallelAvroResult::Timer
14556            }
14557            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
14558                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
14559                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
14560                None => return Ok(None),
14561            },
14562            RecordedCommand::SignalWait { value, .. } => match value {
14563                Some(value) => ParallelAvroResult::Signal(value.clone()),
14564                None => return Ok(None),
14565            },
14566            RecordedCommand::ConditionWait { result, .. } => match result {
14567                Some(result) => ParallelAvroResult::Condition(*result),
14568                None => return Ok(None),
14569            },
14570            other => {
14571                return Err(command_mismatch(
14572                    other,
14573                    format!("selected {} member", handle.kind),
14574                ))
14575            }
14576        };
14577        results.push(result);
14578    }
14579    let mut results = results.into_iter();
14580    parallel_results_for_shape(&handle.shape, &mut results)
14581        .into_json_result()
14582        .map(Some)
14583}
14584
14585fn recorded_selection_member_is_terminal(
14586    state: &WorkflowState,
14587    handle: &DurableOperationHandle,
14588) -> bool {
14589    let mut completed = 0usize;
14590    let mut all_completed = true;
14591    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14592        let Some(command) = selection_member_recorded_command(state, sequence) else {
14593            all_completed = false;
14594            continue;
14595        };
14596        let terminal = match command {
14597            RecordedCommand::Activity {
14598                outcome: Some(Err(_)),
14599                ..
14600            }
14601            | RecordedCommand::ChildWorkflow {
14602                outcome: Some(Err(_)),
14603                ..
14604            } => return true,
14605            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
14606            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
14607            RecordedCommand::Timer { fired, .. } => *fired,
14608            RecordedCommand::SignalWait { value, .. } => value.is_some(),
14609            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
14610            RecordedCommand::SearchAttributes { .. }
14611            | RecordedCommand::CancellationScope { .. }
14612            | RecordedCommand::SideEffect { .. }
14613            | RecordedCommand::VersionMarker { .. }
14614            | RecordedCommand::Memo { .. }
14615            | RecordedCommand::CancellationBoundary { .. }
14616            | RecordedCommand::CancellationGroup { .. } => false,
14617            RecordedCommand::ServiceOperation { .. } => false,
14618        };
14619        if !terminal {
14620            all_completed = false;
14621            continue;
14622        }
14623        completed += 1;
14624    }
14625    all_completed && completed == handle.size
14626}
14627
14628fn selection_cancellation_for_handle(
14629    state: &WorkflowState,
14630    handle: &DurableOperationHandle,
14631) -> Result<bool> {
14632    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
14633        recorded.selection_group_id == handle.selection_group_id
14634            && recorded.member_base_sequence == handle.base_sequence
14635    }) else {
14636        return Ok(false);
14637    };
14638    validate_selection_cancellation_marker(marker, handle)?;
14639    Ok(true)
14640}
14641
14642fn validate_selection_cancellations_for_handles(
14643    state: &WorkflowState,
14644    handles: &[DurableOperationHandle],
14645) -> Result<()> {
14646    let Some(group_id) = handles
14647        .first()
14648        .map(|handle| handle.selection_group_id.as_str())
14649    else {
14650        return Ok(());
14651    };
14652    for marker in state
14653        .cancelled_selection_members
14654        .iter()
14655        .filter(|marker| marker.selection_group_id == group_id)
14656    {
14657        let Some(handle) = handles
14658            .iter()
14659            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14660        else {
14661            return Err(invalid_recorded_history(
14662                "selection_cancellation_member_mismatch",
14663                marker.member_base_sequence,
14664                "SelectionOperationCancelled matching an authored selection handle",
14665                &format!("{marker:?}"),
14666                "selection cancellation member base does not name an authored member",
14667            ));
14668        };
14669        validate_selection_cancellation_marker(marker, handle)?;
14670    }
14671    Ok(())
14672}
14673
14674fn validate_selection_cancellation_marker(
14675    marker: &SelectionCancellation,
14676    handle: &DurableOperationHandle,
14677) -> Result<()> {
14678    if marker.selection_group_id != handle.selection_group_id
14679        || marker.member_key != handle.key
14680        || marker.member_index != handle.index
14681        || marker.member_base_sequence != handle.base_sequence
14682        || marker.member_size != handle.size
14683        || marker.operation_kind != handle.kind
14684        || marker.operation_identity != handle.identity
14685    {
14686        return Err(invalid_recorded_history(
14687            "selection_cancellation_member_mismatch",
14688            handle.base_sequence,
14689            "SelectionOperationCancelled matching the authored selection handle",
14690            &format!("{marker:?}"),
14691            "selection cancellation history targets different authored member metadata",
14692        ));
14693    }
14694    Ok(())
14695}
14696
14697/// Future returned by [`DurableOperationHandle::await_result`].
14698pub struct DurableOperationAwaitCall {
14699    handle: DurableOperationHandle,
14700}
14701
14702impl Future for DurableOperationAwaitCall {
14703    type Output = Result<ParallelResult>;
14704
14705    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14706        let mut state = match self.handle.ctx.state.lock() {
14707            Ok(state) => state,
14708            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14709        };
14710        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14711            return Poll::Ready(Err(error));
14712        }
14713        match state.prepare_selection_handle_cancellation(&self.handle) {
14714            Ok(true) => return Poll::Pending,
14715            Ok(false) => {}
14716            Err(error) => return Poll::Ready(Err(error)),
14717        }
14718        match selection_cancellation_for_handle(&state, &self.handle) {
14719            Err(error) => return Poll::Ready(Err(error)),
14720            Ok(false) => {}
14721            Ok(true) => {
14722                state.advance_cancellation_receipt(
14723                    &self.handle.selection_group_id,
14724                    self.handle.base_sequence,
14725                );
14726                return Poll::Ready(Err(Error::DurableOperationCancelled(
14727                    DurableOperationCancelled {
14728                        selection_group_id: self.handle.selection_group_id.clone(),
14729                        member_key: self.handle.key.clone(),
14730                        member_index: self.handle.index,
14731                        operation_kind: self.handle.kind.clone(),
14732                        operation_identity: self.handle.identity.clone(),
14733                    },
14734                )));
14735            }
14736        }
14737        match recorded_selection_member_outcome(&state, &self.handle) {
14738            Ok(Some(result)) => {
14739                state.advance_cancellation_handle(&self.handle, false);
14740                Poll::Ready(Ok(result))
14741            }
14742            Ok(None) => Poll::Pending,
14743            Err(error) => {
14744                if !workflow_task_integrity_error(&error) {
14745                    state.advance_cancellation_handle(&self.handle, true);
14746                }
14747                Poll::Ready(Err(error))
14748            }
14749        }
14750    }
14751}
14752
14753fn validate_selection_delivery_handle(
14754    state: &WorkflowState,
14755    handle: &DurableOperationHandle,
14756) -> Result<()> {
14757    let path = state
14758        .recorded_commands
14759        .iter()
14760        .find(|command| command.sequence() == handle.base_sequence)
14761        .and_then(|command| match command {
14762            RecordedCommand::Activity {
14763                parallel_group_path,
14764                ..
14765            }
14766            | RecordedCommand::ChildWorkflow {
14767                parallel_group_path,
14768                ..
14769            }
14770            | RecordedCommand::Timer {
14771                parallel_group_path,
14772                ..
14773            }
14774            | RecordedCommand::SignalWait {
14775                parallel_group_path,
14776                ..
14777            }
14778            | RecordedCommand::ConditionWait {
14779                parallel_group_path,
14780                ..
14781            } => parallel_group_path.as_ref(),
14782            _ => None,
14783        })
14784        .and_then(|path| path.first());
14785    let matches = path.is_some_and(|entry| {
14786        entry.parallel_group_mode.as_deref() == Some("select")
14787            && entry.parallel_group_id == handle.selection_group_id
14788            && entry.selection_member_key.as_ref() == Some(&handle.key)
14789            && entry.selection_member_index == Some(handle.index)
14790            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14791            && entry.selection_member_size == Some(handle.size)
14792            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14793    });
14794    if !matches
14795        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14796            != handle.identity
14797    {
14798        return Err(invalid_recorded_history(
14799            "cooperative_cancellation_call_mismatch",
14800            handle.base_sequence,
14801            "selection handle matching its authored durable identity",
14802            &format!("{handle:?}"),
14803            "selection handle identity or member metadata changed before cancellation replay",
14804        ));
14805    }
14806    Ok(())
14807}
14808
14809/// Future returned by [`DurableOperationHandle::cancel`].
14810pub struct CancelDurableOperationCall {
14811    handle: DurableOperationHandle,
14812    emitted: bool,
14813}
14814
14815impl Future for CancelDurableOperationCall {
14816    type Output = Result<()>;
14817
14818    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14819        let ctx = self.handle.ctx.clone();
14820        let mut state = match ctx.state.lock() {
14821            Ok(state) => state,
14822            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14823        };
14824        match selection_cancellation_for_handle(&state, &self.handle) {
14825            Err(error) => return Poll::Ready(Err(error)),
14826            Ok(true) => {
14827                state.advance_cancellation_receipt(
14828                    &self.handle.selection_group_id,
14829                    self.handle.base_sequence,
14830                );
14831                return Poll::Ready(Ok(()));
14832            }
14833            Ok(false) => {}
14834        }
14835        if recorded_selection_member_is_terminal(&state, &self.handle) {
14836            return Poll::Ready(Ok(()));
14837        }
14838        if !self.emitted {
14839            state.commands.push(json!({
14840                "type": "cancel_selection_operation",
14841                "selection_group_id": self.handle.selection_group_id,
14842                "member_key": self.handle.key,
14843                "member_index": self.handle.index,
14844                "member_base_sequence": self.handle.base_sequence,
14845                "member_size": self.handle.size,
14846                "operation_kind": self.handle.kind,
14847                "operation_identity": self.handle.identity,
14848            }));
14849            self.emitted = true;
14850        }
14851        // Unit completes the request, not the member's outcome. Following
14852        // workflow commands commit atomically with this cancellation request.
14853        // Waiting here would need another workflow task that cancellation
14854        // alone does not create. await_result still requires recorded history.
14855        Poll::Ready(Ok(()))
14856    }
14857}
14858
14859trait PollNestedResultExt<T> {
14860    fn flatten_result(self) -> Poll<Result<T>>;
14861}
14862
14863impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14864    fn flatten_result(self) -> Poll<Result<T>> {
14865        match self {
14866            Poll::Ready(Ok(result)) => Poll::Ready(result),
14867            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14868            Poll::Pending => Poll::Pending,
14869        }
14870    }
14871}
14872
14873struct SagaCompensation {
14874    activity_type: String,
14875    options: ActivityOptions,
14876    arguments: AvroValue,
14877    registration_order: usize,
14878}
14879
14880/// Workflow-local deterministic saga compensation helper.
14881///
14882/// Register each compensation only after its forward step succeeds. Passing
14883/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14884/// reverse registration order after any failure, including cooperative
14885/// cancellation. Each compensation is an ordinary durable activity, so replay,
14886/// duplicate delivery, and worker restart use existing history semantics.
14887pub struct Saga {
14888    ctx: WorkflowContext,
14889    compensations: Vec<SagaCompensation>,
14890}
14891
14892impl Saga {
14893    fn new(ctx: WorkflowContext) -> Self {
14894        Self {
14895            ctx,
14896            compensations: Vec::new(),
14897        }
14898    }
14899
14900    pub fn add_compensation<T: Serialize>(
14901        &mut self,
14902        activity_type: impl Into<String>,
14903        args: T,
14904    ) -> Result<&mut Self> {
14905        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14906    }
14907
14908    pub fn add_compensation_with_options<T: Serialize>(
14909        &mut self,
14910        activity_type: impl Into<String>,
14911        options: ActivityOptions,
14912        args: T,
14913    ) -> Result<&mut Self> {
14914        let activity_type = activity_type.into();
14915        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14916            return Err(Error::Codec(
14917                "saga compensation activity type must be non-empty without surrounding whitespace"
14918                    .to_string(),
14919            ));
14920        }
14921        options.validate().map_err(Error::InvalidActivityOptions)?;
14922        let arguments = AvroValue::from_serialize(&args)?;
14923        let registration_order = self.compensations.len() + 1;
14924        self.compensations.push(SagaCompensation {
14925            activity_type,
14926            options,
14927            arguments,
14928            registration_order,
14929        });
14930        Ok(self)
14931    }
14932
14933    /// Compensate `initiating_failure` and return the failure that must remain.
14934    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14935        let _shield = match self.ctx.cancellation_shield() {
14936            Ok(shield) => shield,
14937            Err(error) => return error,
14938        };
14939        while let Some(compensation) = self.compensations.pop() {
14940            if let Err(compensation_failure) = self
14941                .ctx
14942                .activity_with_options(
14943                    compensation.activity_type.clone(),
14944                    compensation.options,
14945                    compensation.arguments,
14946                )
14947                .await
14948            {
14949                if workflow_task_integrity_error(&compensation_failure) {
14950                    return compensation_failure;
14951                }
14952                return Error::SagaCompensationFailed(SagaCompensationFailure {
14953                    initiating_failure: Box::new(initiating_failure),
14954                    compensation_failure: Box::new(compensation_failure),
14955                    compensation_activity_type: compensation.activity_type,
14956                    compensation_registration_order: compensation.registration_order,
14957                });
14958            }
14959        }
14960        initiating_failure
14961    }
14962
14963    /// Return a successful forward value or compensate and preserve its failure.
14964    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14965        match outcome {
14966            Ok(value) => Ok(value),
14967            Err(error) => Err(self.compensate(error).await),
14968        }
14969    }
14970}
14971
14972pub struct ActivityCall {
14973    ctx: WorkflowContext,
14974    activity_type: String,
14975    options: ActivityOptions,
14976    worker_session: Option<WorkerSessionOptions>,
14977    args: Option<Result<AvroValue>>,
14978    scheduled: bool,
14979    local: bool,
14980    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14981    parallel_group_path: Vec<ParallelGroupMetadata>,
14982}
14983
14984impl ActivityCall {
14985    fn poll_avro_value(
14986        mut self: Pin<&mut Self>,
14987        _cx: &mut TaskContext<'_>,
14988    ) -> Poll<Result<AvroValue>> {
14989        let ctx = self.ctx.clone();
14990        let mut state = match ctx.state.lock() {
14991            Ok(state) => state,
14992            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14993        };
14994
14995        if let Some(result) = &self.local_result {
14996            return match result.lock() {
14997                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14998                    Poll::Ready(result.map_err(Error::ActivityFailed))
14999                }),
15000                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15001            };
15002        }
15003        if self.scheduled {
15004            return Poll::Pending;
15005        }
15006
15007        let options = match self.options.validate() {
15008            Ok(options) => options,
15009            Err(error) => {
15010                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
15011            }
15012        };
15013        if self.local {
15014            if self.worker_session.is_some() {
15015                return Poll::Ready(Err(Error::WorkerLoop(
15016                    "local activities cannot use worker-session routing".into(),
15017                )));
15018            }
15019            if let Err(error) = local_activity::validate(&options) {
15020                return Poll::Ready(Err(error));
15021            }
15022        }
15023        let session = match self
15024            .worker_session
15025            .as_ref()
15026            .map(WorkerSessionOptions::to_wire)
15027            .transpose()
15028        {
15029            Ok(value) => value,
15030            Err(error) => return Poll::Ready(Err(error)),
15031        };
15032        let session_queue = session
15033            .as_ref()
15034            .and_then(|session| session["queue"].as_str());
15035        let task_queue = options
15036            .task_queue
15037            .clone()
15038            .or_else(|| session_queue.map(str::to_owned))
15039            .unwrap_or_else(|| state.task_queue.clone());
15040        if session_queue.is_some_and(|queue| queue != task_queue) {
15041            return Poll::Ready(Err(Error::WorkerLoop(
15042                "worker-session queue must match the activity task queue".into(),
15043            )));
15044        }
15045        let current_recorded_options = RecordedActivityOptions {
15046            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15047            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15048            retry_policy: current_activity_retry_snapshot(&options),
15049            worker_session: session,
15050        };
15051
15052        let cursor = state.command_cursor;
15053        let call_kind = if self.local {
15054            CancellationCallKind::LocalActivity
15055        } else {
15056            CancellationCallKind::Activity
15057        };
15058        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15059            return Poll::Ready(Err(error));
15060        }
15061        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15062            Ok(recorded) => recorded,
15063            Err(error) => return Poll::Ready(Err(error)),
15064        };
15065        if let Some(recorded) = recorded {
15066            let sequence = recorded.sequence();
15067            match recorded {
15068                RecordedCommand::Activity {
15069                    activity_type,
15070                    cancellation_policy,
15071                    options: recorded_options,
15072                    outcome,
15073                    parallel_group_path,
15074                    ..
15075                } => {
15076                    let current_policy = options
15077                        .cancellation_policy
15078                        .unwrap_or(CancellationPolicy::TryCancel)
15079                        .as_str();
15080                    if cancellation_policy != current_policy {
15081                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15082                            ReplayFailure::new(
15083                                "activity_cancellation_policy_changed",
15084                                Some(sequence),
15085                                Some(cancellation_policy),
15086                                Some(current_policy.to_string()),
15087                                "Activity cancellation policy changed during replay",
15088                            ),
15089                        )));
15090                    }
15091                    if let Err(error) = ensure_parallel_path_matches(
15092                        sequence,
15093                        parallel_group_path.as_deref(),
15094                        &self.parallel_group_path,
15095                    ) {
15096                        return Poll::Ready(Err(error));
15097                    }
15098                    if let Some(recorded_type) = activity_type {
15099                        if recorded_type != self.activity_type {
15100                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15101                                ReplayFailure::new(
15102                                    "recorded_command_detail_mismatch",
15103                                    Some(sequence),
15104                                    Some(format!("activity:{recorded_type}")),
15105                                    Some(format!("activity:{}", self.activity_type)),
15106                                    "recorded activity type differs from the current workflow command",
15107                                ),
15108                            )));
15109                        }
15110                    }
15111                    if let Some(recorded_options) = recorded_options {
15112                        if recorded_options.worker_session
15113                            != current_recorded_options.worker_session
15114                        {
15115                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15116                                "activity_worker_session_mismatch", Some(sequence),
15117                                Some(activity_options_description(&recorded_options)),
15118                                Some(activity_options_description(&current_recorded_options)),
15119                                "recorded worker-session routing differs from the current activity",
15120                            ))));
15121                        }
15122                        if !recorded_options
15123                            .task_queue
15124                            .matches_current(&current_recorded_options.task_queue)
15125                        {
15126                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15127                                ReplayFailure::new(
15128                                    "activity_task_queue_mismatch",
15129                                    Some(sequence),
15130                                    Some(activity_options_description(&recorded_options)),
15131                                    Some(activity_options_description(&current_recorded_options)),
15132                                    "recorded activity task queue differs from the current workflow command",
15133                                ),
15134                            )));
15135                        }
15136                        if (self.local
15137                            && matches!(
15138                                recorded_options.execution_mode,
15139                                RecordedSnapshotValue::Unknown
15140                            ))
15141                            || !recorded_options
15142                                .execution_mode
15143                                .matches_current(&current_recorded_options.execution_mode)
15144                        {
15145                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15146                                ReplayFailure::new(
15147                                    "activity_execution_mode_mismatch",
15148                                    Some(sequence),
15149                                    Some(activity_options_description(&recorded_options)),
15150                                    Some(activity_options_description(&current_recorded_options)),
15151                                    "recorded activity execution mode differs from the current workflow command",
15152                                ),
15153                            )));
15154                        }
15155                        if !recorded_options
15156                            .retry_policy
15157                            .matches_current(&current_recorded_options.retry_policy)
15158                        {
15159                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15160                                ReplayFailure::new(
15161                                    "activity_retry_policy_mismatch",
15162                                    Some(sequence),
15163                                    Some(activity_options_description(&recorded_options)),
15164                                    Some(activity_options_description(&current_recorded_options)),
15165                                    "recorded activity retry policy differs from the current workflow command",
15166                                ),
15167                            )));
15168                        }
15169                    }
15170                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15171                        return Poll::Ready(Err(error));
15172                    }
15173                    match state.prepare_scalar_cancellation(
15174                        cursor,
15175                        call_kind,
15176                        &self.parallel_group_path,
15177                    ) {
15178                        Ok(true) => {
15179                            self.scheduled = true;
15180                            return Poll::Pending;
15181                        }
15182                        Ok(false) => {}
15183                        Err(error) => return Poll::Ready(Err(error)),
15184                    }
15185                    state.command_cursor += 1;
15186                    if let Some(outcome) = outcome {
15187                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15188                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15189                    }
15190                    state.matched_recorded_pending = true;
15191                    self.scheduled = true;
15192                    return Poll::Pending;
15193                }
15194                other => {
15195                    return Poll::Ready(Err(command_mismatch(
15196                        &other,
15197                        format!("activity:{}", self.activity_type),
15198                    )));
15199                }
15200            }
15201        }
15202
15203        if !self.scheduled {
15204            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15205                Ok(args) => args,
15206                Err(error) => return Poll::Ready(Err(error)),
15207            };
15208            let arguments = normalize_avro_arguments(args);
15209            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15210                Ok(envelope) => envelope,
15211                Err(error) => return Poll::Ready(Err(error)),
15212            };
15213
15214            let mut command = serde_json::Map::from_iter([
15215                (
15216                    "type".to_string(),
15217                    json!(if self.local {
15218                        "record_local_activity"
15219                    } else {
15220                        "schedule_activity"
15221                    }),
15222                ),
15223                (
15224                    "activity_type".to_string(),
15225                    json!(self.activity_type.clone()),
15226                ),
15227                ("queue".to_string(), json!(task_queue)),
15228                ("arguments".to_string(), envelope),
15229            ]);
15230            for (field, value) in [
15231                ("start_to_close_timeout", options.start_to_close_timeout),
15232                (
15233                    "schedule_to_start_timeout",
15234                    options.schedule_to_start_timeout,
15235                ),
15236                (
15237                    "schedule_to_close_timeout",
15238                    options.schedule_to_close_timeout,
15239                ),
15240                ("heartbeat_timeout", options.heartbeat_timeout),
15241            ] {
15242                if let Some(value) = value {
15243                    command.insert(field.to_string(), json!(value));
15244                }
15245            }
15246            if let Some(retry_policy) = &options.retry_policy {
15247                command.insert("retry_policy".to_string(), retry_policy.clone());
15248            }
15249            if let Some(policy) = options.cancellation_policy {
15250                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15251            }
15252            if let Some(session) = current_recorded_options.worker_session {
15253                command.insert("worker_session".into(), session);
15254            }
15255            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15256            ctx.apply_scope_membership(&mut command);
15257            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15258                Ok(true) => {
15259                    self.scheduled = true;
15260                    return Poll::Pending;
15261                }
15262                Ok(false) => {}
15263                Err(error) => return Poll::Ready(Err(error)),
15264            }
15265            if self.local {
15266                command.remove("queue");
15267                command.insert("execution_mode".into(), json!("local"));
15268                let result = Arc::new(Mutex::new(None));
15269                let command_index = state.commands.len();
15270                state.local_activity_requests.push(local_activity::Request {
15271                    command_index,
15272                    options,
15273                    arguments,
15274                    result: result.clone(),
15275                });
15276                self.local_result = Some(result);
15277            }
15278            state.commands.push(Value::Object(command));
15279            self.scheduled = true;
15280        }
15281
15282        Poll::Pending
15283    }
15284}
15285
15286impl Future for ActivityCall {
15287    type Output = Result<Value>;
15288
15289    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15290        match self.poll_avro_value(cx) {
15291            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15292            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15293            Poll::Pending => Poll::Pending,
15294        }
15295    }
15296}
15297
15298/// Future returned by [`WorkflowContext::sleep`].
15299pub struct TimerCall {
15300    ctx: WorkflowContext,
15301    delay_seconds: Option<u64>,
15302    scheduled: bool,
15303    matched_pending: bool,
15304    parallel_group_path: Vec<ParallelGroupMetadata>,
15305}
15306
15307impl Future for TimerCall {
15308    type Output = Result<()>;
15309
15310    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15311        if self.matched_pending {
15312            return Poll::Pending;
15313        }
15314
15315        let ctx = self.ctx.clone();
15316        let Some(requested_delay) = self.delay_seconds else {
15317            return Poll::Ready(Err(Error::TimerDurationOverflow));
15318        };
15319        let mut state = match ctx.state.lock() {
15320            Ok(state) => state,
15321            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15322        };
15323
15324        let cursor = state.command_cursor;
15325        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15326            return Poll::Ready(Err(error));
15327        }
15328        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15329        {
15330            Ok(recorded) => recorded,
15331            Err(error) => return Poll::Ready(Err(error)),
15332        };
15333        if let Some(recorded) = recorded {
15334            match recorded {
15335                RecordedCommand::Timer {
15336                    sequence,
15337                    delay_seconds,
15338                    fired,
15339                    parallel_group_path,
15340                    ..
15341                } => {
15342                    if let Err(error) =
15343                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15344                    {
15345                        return Poll::Ready(Err(error));
15346                    }
15347                    if let Err(error) = ensure_parallel_path_matches(
15348                        sequence,
15349                        parallel_group_path.as_deref(),
15350                        &self.parallel_group_path,
15351                    ) {
15352                        return Poll::Ready(Err(error));
15353                    }
15354                    if delay_seconds != requested_delay {
15355                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15356                            ReplayFailure::new(
15357                                "timer_delay_mismatch",
15358                                Some(sequence),
15359                                Some(format!("timer:{delay_seconds}s")),
15360                                Some(format!("timer:{requested_delay}s")),
15361                                "recorded timer delay differs from the current workflow command",
15362                            ),
15363                        )));
15364                    }
15365                    if let Err(error) =
15366                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
15367                    {
15368                        return Poll::Ready(Err(error));
15369                    }
15370                    match state.prepare_scalar_cancellation(
15371                        cursor,
15372                        CancellationCallKind::Timer,
15373                        &self.parallel_group_path,
15374                    ) {
15375                        Ok(true) => {
15376                            self.scheduled = true;
15377                            self.matched_pending = true;
15378                            return Poll::Pending;
15379                        }
15380                        Ok(false) => {}
15381                        Err(error) => return Poll::Ready(Err(error)),
15382                    }
15383                    state.command_cursor += 1;
15384                    if fired {
15385                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15386                        return Poll::Ready(Ok(()));
15387                    }
15388                    state.matched_recorded_pending = true;
15389                    self.scheduled = true;
15390                    self.matched_pending = true;
15391                    return Poll::Pending;
15392                }
15393                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
15394            }
15395        }
15396
15397        if !self.scheduled {
15398            let mut command = serde_json::Map::from_iter([
15399                ("type".to_string(), json!("start_timer")),
15400                ("delay_seconds".to_string(), json!(requested_delay)),
15401            ]);
15402            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
15403                Ok(Some(proof)) => {
15404                    command.insert("cancellation_cleanup".into(), proof);
15405                }
15406                Ok(None) => {}
15407                Err(error) => return Poll::Ready(Err(error)),
15408            }
15409            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15410            ctx.apply_scope_membership(&mut command);
15411            match state.prepare_scalar_cancellation(
15412                cursor,
15413                CancellationCallKind::Timer,
15414                &self.parallel_group_path,
15415            ) {
15416                Ok(true) => {
15417                    self.scheduled = true;
15418                    self.matched_pending = true;
15419                    return Poll::Pending;
15420                }
15421                Ok(false) => {}
15422                Err(error) => return Poll::Ready(Err(error)),
15423            }
15424            state.commands.push(Value::Object(command));
15425            self.scheduled = true;
15426        }
15427
15428        Poll::Pending
15429    }
15430}
15431
15432/// Future returned by [`WorkflowContext::wait_condition`].
15433pub struct ConditionWaitCall {
15434    ctx: WorkflowContext,
15435    options: ConditionWaitOptions,
15436    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
15437    occurrence_id: Option<String>,
15438    opened_wait: bool,
15439    parallel_group_path: Vec<ParallelGroupMetadata>,
15440}
15441
15442impl Future for ConditionWaitCall {
15443    type Output = Result<ConditionWaitResult>;
15444
15445    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15446        if self.opened_wait {
15447            return Poll::Pending;
15448        }
15449
15450        let options = match self.options.validate() {
15451            Ok(options) => options,
15452            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
15453        };
15454        let ctx = self.ctx.clone();
15455        let occurrence_id = match self.occurrence_id.as_ref() {
15456            Some(occurrence_id) => occurrence_id.clone(),
15457            None => {
15458                let mut state = match ctx.state.lock() {
15459                    Ok(state) => state,
15460                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15461                };
15462                let ordinal = state.condition_wait_occurrence_counter;
15463                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
15464                    Some(next) => next,
15465                    None => {
15466                        return Poll::Ready(Err(Error::WorkerLoop(
15467                            "condition wait occurrence counter overflowed".to_string(),
15468                        )))
15469                    }
15470                };
15471                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
15472                drop(state);
15473                self.occurrence_id = Some(occurrence_id.clone());
15474                occurrence_id
15475            }
15476        };
15477
15478        let recorded_result = {
15479            let mut state = match ctx.state.lock() {
15480                Ok(state) => state,
15481                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15482            };
15483            let initial_cursor = state.command_cursor;
15484            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
15485                return Poll::Ready(Err(error));
15486            }
15487            let recorded = match state
15488                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
15489            {
15490                Ok(recorded) => recorded,
15491                Err(error) => return Poll::Ready(Err(error)),
15492            };
15493            let Some(recorded) = recorded else {
15494                drop(state);
15495                return self.poll_new_condition(options);
15496            };
15497            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
15498                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
15499            }
15500
15501            let mut cursor = state.command_cursor;
15502            let mut result = None;
15503            let mut pending_delivery = false;
15504            loop {
15505                if cursor > initial_cursor
15506                    && matches!(
15507                        state.recorded_commands.get(cursor),
15508                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
15509                    )
15510                {
15511                    break;
15512                }
15513                let recorded = match state
15514                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
15515                {
15516                    Ok(recorded) => recorded,
15517                    Err(error) => return Poll::Ready(Err(error)),
15518                };
15519                let Some(RecordedCommand::ConditionWait {
15520                    sequence,
15521                    occurrence_id: ref recorded_occurrence_id,
15522                    ref condition_key,
15523                    ref predicate_identity,
15524                    timeout_seconds,
15525                    result: recorded_result,
15526                    ref parallel_group_path,
15527                    ..
15528                }) = recorded
15529                else {
15530                    break;
15531                };
15532
15533                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
15534                    break;
15535                }
15536                if let Err(error) = ensure_parallel_path_matches(
15537                    sequence,
15538                    parallel_group_path.as_deref(),
15539                    &self.parallel_group_path,
15540                ) {
15541                    return Poll::Ready(Err(error));
15542                }
15543                if let Err(error) = validate_recorded_condition_wait(
15544                    sequence,
15545                    recorded_occurrence_id,
15546                    condition_key.as_deref(),
15547                    predicate_identity,
15548                    timeout_seconds,
15549                    &occurrence_id,
15550                    &options,
15551                ) {
15552                    return Poll::Ready(Err(error));
15553                }
15554                if result == Some(ConditionWaitResult::TimedOut) {
15555                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15556                        "condition_wait_reopened_after_timeout",
15557                        Some(sequence),
15558                        Some("timed-out condition is terminal".to_string()),
15559                        Some("another physical wait-open".to_string()),
15560                        "condition history reopened one logical wait after its durable timeout",
15561                    ))));
15562                }
15563                if let Err(error) =
15564                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
15565                {
15566                    return Poll::Ready(Err(error));
15567                }
15568                match state.prepare_scalar_cancellation(
15569                    cursor,
15570                    CancellationCallKind::Condition,
15571                    &self.parallel_group_path,
15572                ) {
15573                    Ok(pending) => pending_delivery |= pending,
15574                    Err(error) => return Poll::Ready(Err(error)),
15575                }
15576                result = recorded_result;
15577                if result.is_some() {
15578                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15579                }
15580                cursor += 1;
15581            }
15582            state.command_cursor = cursor;
15583            if pending_delivery {
15584                self.opened_wait = true;
15585                return Poll::Pending;
15586            }
15587            result
15588        };
15589
15590        if let Some(result) = recorded_result {
15591            return Poll::Ready(Ok(result));
15592        }
15593
15594        self.poll_open_condition(options, true)
15595    }
15596}
15597
15598impl ConditionWaitCall {
15599    fn poll_new_condition(
15600        self: Pin<&mut Self>,
15601        options: ValidatedConditionWaitOptions,
15602    ) -> Poll<Result<ConditionWaitResult>> {
15603        self.poll_open_condition(options, false)
15604    }
15605
15606    fn poll_open_condition(
15607        mut self: Pin<&mut Self>,
15608        options: ValidatedConditionWaitOptions,
15609        recorded_wait: bool,
15610    ) -> Poll<Result<ConditionWaitResult>> {
15611        {
15612            let ctx = self.ctx.clone();
15613            let mut state = match ctx.state.lock() {
15614                Ok(state) => state,
15615                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15616            };
15617            let cursor = state.command_cursor;
15618            match state.prepare_scalar_cancellation(
15619                cursor,
15620                CancellationCallKind::Condition,
15621                &self.parallel_group_path,
15622            ) {
15623                Ok(true) => {
15624                    self.opened_wait = true;
15625                    return Poll::Pending;
15626                }
15627                Ok(false) => {}
15628                Err(error) => return Poll::Ready(Err(error)),
15629            }
15630        }
15631        let selection_member = self
15632            .parallel_group_path
15633            .first()
15634            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
15635        match (self.predicate)() {
15636            Ok(true) if !selection_member || recorded_wait => {
15637                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
15638            }
15639            Ok(_) => {}
15640            Err(error) => return Poll::Ready(Err(error)),
15641        }
15642        if options.timeout_seconds == Some(0) && !selection_member {
15643            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15644        }
15645
15646        let ctx = self.ctx.clone();
15647        let mut state = match ctx.state.lock() {
15648            Ok(state) => state,
15649            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15650        };
15651        let mut command = serde_json::Map::from_iter([
15652            ("type".to_string(), json!("open_condition_wait")),
15653            (
15654                "condition_wait_occurrence_id".to_string(),
15655                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15656            ),
15657            ("condition_key".to_string(), json!(options.condition_key)),
15658            (
15659                "condition_definition_fingerprint".to_string(),
15660                json!(options.predicate_identity),
15661            ),
15662        ]);
15663        if let Some(timeout_seconds) = options.timeout_seconds {
15664            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15665        }
15666        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15667        ctx.apply_scope_membership(&mut command);
15668        state.commands.push(Value::Object(command));
15669        drop(state);
15670        self.opened_wait = true;
15671        Poll::Pending
15672    }
15673}
15674
15675fn validate_recorded_condition_wait(
15676    sequence: u64,
15677    recorded_occurrence_id: &str,
15678    recorded_key: Option<&str>,
15679    recorded_predicate_identity: &str,
15680    recorded_timeout_seconds: Option<u64>,
15681    current_occurrence_id: &str,
15682    current: &ValidatedConditionWaitOptions,
15683) -> Result<()> {
15684    if recorded_occurrence_id != current_occurrence_id {
15685        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15686            "condition_wait_occurrence_mismatch",
15687            Some(sequence),
15688            Some(recorded_occurrence_id.to_string()),
15689            Some(current_occurrence_id.to_string()),
15690            "recorded condition occurrence differs from the current authored wait position",
15691        )));
15692    }
15693    if recorded_key != Some(current.condition_key.as_str()) {
15694        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15695            "condition_wait_key_mismatch",
15696            Some(sequence),
15697            recorded_key.map(str::to_string),
15698            Some(current.condition_key.clone()),
15699            "recorded condition identity differs from the current workflow wait",
15700        )));
15701    }
15702    if recorded_predicate_identity != current.predicate_identity {
15703        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15704            "condition_wait_predicate_mismatch",
15705            Some(sequence),
15706            Some(recorded_predicate_identity.to_string()),
15707            Some(current.predicate_identity.clone()),
15708            "recorded condition predicate behavior differs from current workflow code",
15709        )));
15710    }
15711    if recorded_timeout_seconds != current.timeout_seconds {
15712        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15713            "condition_wait_timeout_mismatch",
15714            Some(sequence),
15715            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15716            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15717            "recorded condition timeout differs from the current workflow wait",
15718        )));
15719    }
15720    Ok(())
15721}
15722
15723/// Future returned by [`WorkflowContext::start_child_workflow`].
15724pub struct ChildWorkflowCall {
15725    ctx: WorkflowContext,
15726    workflow_type: String,
15727    options: ChildWorkflowOptions,
15728    args: Option<Result<AvroValue>>,
15729    scheduled: bool,
15730    matched_pending: bool,
15731    parallel_group_path: Vec<ParallelGroupMetadata>,
15732}
15733
15734impl ChildWorkflowCall {
15735    fn poll_avro_value(
15736        mut self: Pin<&mut Self>,
15737        _cx: &mut TaskContext<'_>,
15738    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15739        if self.matched_pending {
15740            return Poll::Pending;
15741        }
15742
15743        let ctx = self.ctx.clone();
15744        let mut state = match ctx.state.lock() {
15745            Ok(state) => state,
15746            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15747        };
15748
15749        let cursor = state.command_cursor;
15750        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15751            return Poll::Ready(Err(error));
15752        }
15753        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15754        {
15755            Ok(recorded) => recorded,
15756            Err(error) => return Poll::Ready(Err(error)),
15757        };
15758        if let Some(recorded) = recorded {
15759            let sequence = recorded.sequence();
15760            match recorded {
15761                RecordedCommand::ChildWorkflow {
15762                    workflow_type,
15763                    policies,
15764                    outcome,
15765                    parallel_group_path,
15766                    ..
15767                } => {
15768                    if let Err(error) = ensure_parallel_path_matches(
15769                        sequence,
15770                        parallel_group_path.as_deref(),
15771                        &self.parallel_group_path,
15772                    ) {
15773                        return Poll::Ready(Err(error));
15774                    }
15775                    if let Some(recorded_type) = workflow_type {
15776                        if recorded_type != self.workflow_type {
15777                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15778                                ReplayFailure::new(
15779                                    "recorded_command_detail_mismatch",
15780                                    Some(sequence),
15781                                    Some(format!("child workflow:{recorded_type}")),
15782                                    Some(format!("child workflow:{}", self.workflow_type)),
15783                                    "recorded child workflow type differs from the current workflow command",
15784                                ),
15785                            )));
15786                        }
15787                    }
15788                    if let Err(error) =
15789                        ensure_child_policies_match(sequence, &policies, &self.options)
15790                    {
15791                        return Poll::Ready(Err(error));
15792                    }
15793                    if let Err(error) =
15794                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15795                    {
15796                        return Poll::Ready(Err(error));
15797                    }
15798                    match state.prepare_scalar_cancellation(
15799                        cursor,
15800                        CancellationCallKind::Child,
15801                        &self.parallel_group_path,
15802                    ) {
15803                        Ok(true) => {
15804                            self.scheduled = true;
15805                            self.matched_pending = true;
15806                            return Poll::Pending;
15807                        }
15808                        Ok(false) => {}
15809                        Err(error) => return Poll::Ready(Err(error)),
15810                    }
15811                    state.command_cursor += 1;
15812                    if let Some(outcome) = outcome {
15813                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15814                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15815                    }
15816                    state.matched_recorded_pending = true;
15817                    self.scheduled = true;
15818                    self.matched_pending = true;
15819                    return Poll::Pending;
15820                }
15821                other => {
15822                    return Poll::Ready(Err(command_mismatch(
15823                        &other,
15824                        format!("child workflow:{}", self.workflow_type),
15825                    )));
15826                }
15827            }
15828        }
15829
15830        if !self.scheduled {
15831            if self.options.task_queue.trim().is_empty() {
15832                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15833                    "task_queue must not be empty".to_string(),
15834                )));
15835            }
15836            for (name, value) in [
15837                (
15838                    "execution_timeout_seconds",
15839                    self.options.execution_timeout_seconds,
15840                ),
15841                ("run_timeout_seconds", self.options.run_timeout_seconds),
15842            ] {
15843                if value == Some(0) {
15844                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15845                        "{name} must be at least 1"
15846                    ))));
15847                }
15848            }
15849
15850            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15851                Ok(args) => args,
15852                Err(error) => return Poll::Ready(Err(error)),
15853            };
15854            let arguments = match encode_typed_envelope(
15855                &normalize_avro_arguments(args),
15856                &state.payload_codec,
15857            ) {
15858                Ok(arguments) => arguments,
15859                Err(error) => return Poll::Ready(Err(error)),
15860            };
15861            let mut command = json!({
15862                "type": "start_child_workflow",
15863                "workflow_type": self.workflow_type,
15864                "queue": self.options.task_queue,
15865                "parent_close_policy": self.options.parent_close_policy.as_str(),
15866                "arguments": arguments,
15867            });
15868            let object = command
15869                .as_object_mut()
15870                .expect("child workflow command is always an object");
15871            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15872                object.insert(
15873                    "cancellation_policy".to_string(),
15874                    json!(self.options.cancellation_policy.as_str()),
15875                );
15876            }
15877            if let Some(policy) = &self.options.retry_policy {
15878                let mut retry_policy = serde_json::Map::new();
15879                if let Some(max_attempts) = policy.max_attempts {
15880                    if max_attempts == 0 {
15881                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15882                            "retry_policy.max_attempts must be at least 1".to_string(),
15883                        )));
15884                    }
15885                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15886                }
15887                if !policy.backoff_seconds.is_empty() {
15888                    retry_policy
15889                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15890                }
15891                if !policy.non_retryable_error_types.is_empty() {
15892                    retry_policy.insert(
15893                        "non_retryable_error_types".to_string(),
15894                        json!(policy.non_retryable_error_types),
15895                    );
15896                }
15897                if retry_policy.is_empty() {
15898                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15899                        "retry_policy must configure at least one field".to_string(),
15900                    )));
15901                }
15902                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15903            }
15904            if let Some(seconds) = self.options.execution_timeout_seconds {
15905                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15906            }
15907            if let Some(seconds) = self.options.run_timeout_seconds {
15908                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15909            }
15910            apply_parallel_group_path(object, &self.parallel_group_path);
15911            ctx.apply_scope_membership(object);
15912            match state.prepare_scalar_cancellation(
15913                cursor,
15914                CancellationCallKind::Child,
15915                &self.parallel_group_path,
15916            ) {
15917                Ok(true) => {
15918                    self.scheduled = true;
15919                    self.matched_pending = true;
15920                    return Poll::Pending;
15921                }
15922                Ok(false) => {}
15923                Err(error) => return Poll::Ready(Err(error)),
15924            }
15925            state.commands.push(command);
15926            self.scheduled = true;
15927        }
15928
15929        Poll::Pending
15930    }
15931}
15932
15933impl Future for ChildWorkflowCall {
15934    type Output = Result<ChildWorkflowResult>;
15935
15936    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15937        match self.poll_avro_value(cx) {
15938            Poll::Ready(Ok(result)) => match result.result.into_json() {
15939                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15940                    parent: result.parent,
15941                    child: result.child,
15942                    child_workflow_type: result.child_workflow_type,
15943                    result: projected,
15944                })),
15945                Err(error) => Poll::Ready(Err(error)),
15946            },
15947            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15948            Poll::Pending => Poll::Pending,
15949        }
15950    }
15951}
15952
15953fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15954    Error::NonDeterministicReplay(ReplayFailure::new(
15955        "recorded_command_mismatch",
15956        Some(recorded.sequence()),
15957        Some(recorded.shape().to_string()),
15958        Some(actual.into()),
15959        "current workflow command does not match the recorded durable command sequence",
15960    ))
15961}
15962
15963pub struct SignalCall {
15964    ctx: WorkflowContext,
15965    signal_name: String,
15966    runtime_reserved_allowed: bool,
15967    opened_wait: bool,
15968    matched_pending: bool,
15969    parallel_group_path: Vec<ParallelGroupMetadata>,
15970}
15971
15972impl SignalCall {
15973    fn poll_avro_value(
15974        mut self: Pin<&mut Self>,
15975        _cx: &mut TaskContext<'_>,
15976    ) -> Poll<Result<Vec<AvroValue>>> {
15977        if self.matched_pending {
15978            return Poll::Pending;
15979        }
15980        if !self.runtime_reserved_allowed {
15981            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15982                return Poll::Ready(Err(error));
15983            }
15984        }
15985
15986        let ctx = self.ctx.clone();
15987        let mut state = match ctx.state.lock() {
15988            Ok(state) => state,
15989            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15990        };
15991
15992        let cursor = state.command_cursor;
15993        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15994            return Poll::Ready(Err(error));
15995        }
15996        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15997        {
15998            Ok(recorded) => recorded,
15999            Err(error) => return Poll::Ready(Err(error)),
16000        };
16001        if let Some(recorded) = recorded {
16002            match recorded {
16003                RecordedCommand::SignalWait {
16004                    sequence,
16005                    signal_name,
16006                    value,
16007                    parallel_group_path,
16008                } => {
16009                    if let Err(error) = ensure_parallel_path_matches(
16010                        sequence,
16011                        parallel_group_path.as_deref(),
16012                        &self.parallel_group_path,
16013                    ) {
16014                        return Poll::Ready(Err(error));
16015                    }
16016                    if signal_name != self.signal_name {
16017                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16018                            ReplayFailure::new(
16019                                "recorded_command_detail_mismatch",
16020                                Some(sequence),
16021                                Some(format!("signal wait:{signal_name}")),
16022                                Some(format!("signal wait:{}", self.signal_name)),
16023                                "recorded signal name differs from the current workflow command",
16024                            ),
16025                        )));
16026                    }
16027
16028                    if let Err(error) =
16029                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16030                    {
16031                        return Poll::Ready(Err(error));
16032                    }
16033                    match state.prepare_scalar_cancellation(
16034                        cursor,
16035                        CancellationCallKind::Signal,
16036                        &self.parallel_group_path,
16037                    ) {
16038                        Ok(true) => {
16039                            self.opened_wait = true;
16040                            self.matched_pending = true;
16041                            return Poll::Pending;
16042                        }
16043                        Ok(false) => {}
16044                        Err(error) => return Poll::Ready(Err(error)),
16045                    }
16046                    state.command_cursor += 1;
16047                    if let Some(value) = value {
16048                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
16049                        return Poll::Ready(Ok(value));
16050                    }
16051                    if state
16052                        .resume_signal
16053                        .as_ref()
16054                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16055                    {
16056                        let signal = state
16057                            .resume_signal
16058                            .take()
16059                            .expect("matching resume signal is present");
16060                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
16061                        return Poll::Ready(Ok(signal.arguments));
16062                    }
16063
16064                    state.matched_recorded_pending = true;
16065                    self.opened_wait = true;
16066                    self.matched_pending = true;
16067                    return Poll::Pending;
16068                }
16069                other => {
16070                    return Poll::Ready(Err(command_mismatch(
16071                        &other,
16072                        format!("signal wait:{}", self.signal_name),
16073                    )));
16074                }
16075            }
16076        }
16077
16078        match state.prepare_scalar_cancellation(
16079            cursor,
16080            CancellationCallKind::Signal,
16081            &self.parallel_group_path,
16082        ) {
16083            Ok(true) => {
16084                self.opened_wait = true;
16085                self.matched_pending = true;
16086                return Poll::Pending;
16087            }
16088            Ok(false) => {}
16089            Err(error) => return Poll::Ready(Err(error)),
16090        }
16091
16092        if state
16093            .resume_signal
16094            .as_ref()
16095            .is_some_and(|signal| signal.signal_name == self.signal_name)
16096        {
16097            let signal = state
16098                .resume_signal
16099                .take()
16100                .expect("matching resume signal is present");
16101            state.unavailable_cancellation_boundary(&self.parallel_group_path);
16102            return Poll::Ready(Ok(signal.arguments));
16103        }
16104
16105        if !self.opened_wait {
16106            let mut command = serde_json::Map::from_iter([
16107                ("type".to_string(), json!("open_signal_wait")),
16108                ("signal_name".to_string(), json!(self.signal_name)),
16109            ]);
16110            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16111            ctx.apply_scope_membership(&mut command);
16112            state.commands.push(Value::Object(command));
16113            self.opened_wait = true;
16114        }
16115
16116        Poll::Pending
16117    }
16118}
16119
16120impl Future for SignalCall {
16121    type Output = Result<Vec<Value>>;
16122
16123    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16124        match self.poll_avro_value(cx) {
16125            Poll::Ready(Ok(values)) => Poll::Ready(
16126                values
16127                    .into_iter()
16128                    .map(AvroValue::into_json)
16129                    .collect::<Result<Vec<_>>>(),
16130            ),
16131            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16132            Poll::Pending => Poll::Pending,
16133        }
16134    }
16135}
16136
16137#[derive(Clone, Debug)]
16138pub struct ActivityContext {
16139    client: Client,
16140    pub task_id: String,
16141    pub activity_attempt_id: String,
16142    pub lease_owner: String,
16143    pub activity_type: String,
16144    pub attempt_number: u64,
16145    pub task_queue: String,
16146    pub worker_id: String,
16147    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16148    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16149    worker_session: Option<WorkerSession>,
16150}
16151
16152impl ActivityContext {
16153    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16154        if let Some(heartbeats) = &self.local_heartbeats {
16155            return heartbeats
16156                .lock()
16157                .map_err(|_| Error::WorkflowStatePoisoned)?
16158                .record(details);
16159        }
16160        if let Some(guard) = &self.claim_guard {
16161            return guard.heartbeat(self, details).await;
16162        }
16163        if let Some(session) = &self.worker_session {
16164            if !session.active() {
16165                return Err(Error::ActivityExecutionAbandoned(
16166                    "worker-session lease or TTL is no longer active".into(),
16167                ));
16168            }
16169            let result = self
16170                .client
16171                .heartbeat_activity_task_value(
16172                    &self.task_id,
16173                    &self.activity_attempt_id,
16174                    &self.lease_owner,
16175                    details,
16176                )
16177                .await;
16178            return worker_session::settle_activity_heartbeat(
16179                session,
16180                result,
16181                &self.task_id,
16182                &self.activity_attempt_id,
16183                &self.lease_owner,
16184            );
16185        }
16186        self.client
16187            .heartbeat_activity_task(
16188                &self.task_id,
16189                &self.activity_attempt_id,
16190                &self.lease_owner,
16191                details,
16192            )
16193            .await
16194    }
16195}
16196
16197fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
16198    validate_payload_codec(codec)?;
16199    match value {
16200        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
16201            value, codec,
16202        )?)),
16203        None => Ok(AvroValue::Array(Vec::new())),
16204    }
16205}
16206
16207fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
16208    let Some(signal_name) = task
16209        .signal_name
16210        .as_deref()
16211        .filter(|value| !value.is_empty())
16212    else {
16213        return Ok(None);
16214    };
16215    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
16216    let AvroValue::Array(arguments) = decoded else {
16217        unreachable!("normalize_avro_arguments always returns an array");
16218    };
16219
16220    Ok(Some(ResumeSignal {
16221        signal_name: signal_name.to_string(),
16222        arguments,
16223    }))
16224}
16225
16226fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
16227    validate_payload_codec(&task.payload_codec)?;
16228    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
16229    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
16230    for event in &task.history_events {
16231        validate_history_event_payloads(event, &task.payload_codec)?;
16232    }
16233    Ok(())
16234}
16235
16236fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
16237    validate_payload_codec(&task.payload_codec)?;
16238    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
16239}
16240
16241fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
16242    validate_payload_codec(&task.payload_codec)?;
16243    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
16244    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
16245    for event in &task.history_events {
16246        validate_history_event_payloads(event, &task.payload_codec)?;
16247    }
16248
16249    let Some(export) = task.history_export.as_ref() else {
16250        return Ok(());
16251    };
16252    let export_codec = match export.get("payloads") {
16253        Some(payloads) => declared_payload_codec(payloads, "codec")?,
16254        None => None,
16255    }
16256    .unwrap_or(&task.payload_codec);
16257    validate_payload_codec(export_codec)?;
16258
16259    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
16260        for event in events {
16261            let event_type = event
16262                .get("event_type")
16263                .or_else(|| event.get("type"))
16264                .and_then(Value::as_str)
16265                .unwrap_or_default();
16266            if let Some(payload) = event.get("payload") {
16267                validate_history_payloads(event_type, payload, export_codec)?;
16268            }
16269        }
16270    }
16271    for signal in export
16272        .get("signals")
16273        .and_then(Value::as_array)
16274        .into_iter()
16275        .flatten()
16276    {
16277        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
16278        validate_payload_codec(codec)?;
16279        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
16280    }
16281    for activity in export
16282        .get("activities")
16283        .and_then(Value::as_array)
16284        .into_iter()
16285        .flatten()
16286    {
16287        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
16288        validate_payload_codec(codec)?;
16289        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
16290        validate_optional_inbound_payload(activity.get("result"), codec)?;
16291    }
16292    Ok(())
16293}
16294
16295fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
16296    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
16297}
16298
16299fn validate_history_payloads(
16300    event_type: &str,
16301    payload: &Value,
16302    fallback_codec: &str,
16303) -> Result<()> {
16304    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
16305    validate_payload_codec(codec)?;
16306    for field in history_payload_fields(event_type) {
16307        validate_optional_inbound_payload(payload.get(*field), codec)?;
16308    }
16309    Ok(())
16310}
16311
16312const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
16313
16314fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
16315    match event_type {
16316        "ActivityCompleted" => &["result"],
16317        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
16318        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
16319        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
16320        "ChildRunCompleted" => &["result", "output"],
16321        "WorkflowCompleted" => &["output"],
16322        "ServiceCallStarted"
16323        | "ServiceCallCompleted"
16324        | "ServiceCallFailed"
16325        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
16326        _ => &[],
16327    }
16328}
16329
16330fn signal_history_payload(payload: &Value) -> Option<&Value> {
16331    SIGNAL_HISTORY_PAYLOAD_FIELDS
16332        .iter()
16333        .find_map(|field| payload.get(*field))
16334}
16335
16336fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
16337    match value.get(field) {
16338        None => Ok(None),
16339        Some(Value::String(codec)) => Ok(Some(codec)),
16340        Some(_) => Err(invalid_payload_envelope()),
16341    }
16342}
16343
16344fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
16345    validate_payload_codec(codec)?;
16346    if let Some(value) = value.filter(|value| !value.is_null()) {
16347        decode_wire_avro_value(value, codec)?;
16348    }
16349    Ok(())
16350}
16351
16352fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
16353    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
16354        invalid_recorded_history(
16355            "parallel_group_metadata_invalid",
16356            sequence,
16357            "non-empty parallel_group_id",
16358            &payload.to_string(),
16359            "parallel-group history is missing its stable identity",
16360        )
16361    })?;
16362    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
16363        invalid_recorded_history(
16364            "parallel_group_metadata_invalid",
16365            sequence,
16366            "activity, child, timer, signal, condition, or mixed group kind",
16367            &payload.to_string(),
16368            "parallel-group history is missing its group kind",
16369        )
16370    })?;
16371    if !matches!(
16372        kind.as_str(),
16373        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
16374    ) {
16375        return Err(invalid_recorded_history(
16376            "parallel_group_metadata_invalid",
16377            sequence,
16378            "activity, child, timer, signal, condition, or mixed group kind",
16379            &kind,
16380            "parallel-group history contains an unsupported group kind",
16381        ));
16382    }
16383    let base_sequence = payload
16384        .get("parallel_group_base_sequence")
16385        .and_then(value_as_u64)
16386        .filter(|value| *value > 0)
16387        .ok_or_else(|| {
16388            invalid_recorded_history(
16389                "parallel_group_metadata_invalid",
16390                sequence,
16391                "positive parallel_group_base_sequence",
16392                &payload.to_string(),
16393                "parallel-group history contains an invalid base sequence",
16394            )
16395        })?;
16396    let size = payload
16397        .get("parallel_group_size")
16398        .and_then(value_as_u64)
16399        .and_then(|value| usize::try_from(value).ok())
16400        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
16401        .ok_or_else(|| {
16402            invalid_recorded_history(
16403                "parallel_group_metadata_invalid",
16404                sequence,
16405                "bounded positive parallel_group_size",
16406                &payload.to_string(),
16407                "parallel-group history contains an invalid group size",
16408            )
16409        })?;
16410    let index = payload
16411        .get("parallel_group_index")
16412        .and_then(value_as_u64)
16413        .and_then(|value| usize::try_from(value).ok())
16414        .filter(|value| *value < size)
16415        .ok_or_else(|| {
16416            invalid_recorded_history(
16417                "parallel_group_metadata_invalid",
16418                sequence,
16419                "parallel_group_index within group bounds",
16420                &payload.to_string(),
16421                "parallel-group history contains an invalid member index",
16422            )
16423        })?;
16424    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
16425        return Err(invalid_recorded_history(
16426            "parallel_group_metadata_invalid",
16427            sequence,
16428            "base sequence plus member index equals workflow sequence",
16429            &payload.to_string(),
16430            "parallel-group path does not preserve durable workflow position",
16431        ));
16432    }
16433    let mode = payload
16434        .get("parallel_group_mode")
16435        .and_then(Value::as_str)
16436        .unwrap_or("all");
16437    if !matches!(mode, "all" | "select") {
16438        return Err(invalid_recorded_history(
16439            "parallel_group_metadata_invalid",
16440            sequence,
16441            "parallel group mode all or select",
16442            mode,
16443            "parallel-group history contains an unsupported group mode",
16444        ));
16445    }
16446    let expected_id = if mode == "select" {
16447        format!("select-calls:{base_sequence}:{size}")
16448    } else {
16449        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
16450    };
16451    if group_id != expected_id {
16452        return Err(invalid_recorded_history(
16453            "parallel_group_metadata_invalid",
16454            sequence,
16455            &expected_id,
16456            &group_id,
16457            "parallel-group history contains an incompatible stable group ID",
16458        ));
16459    }
16460    let selection_member_key = if mode == "select" {
16461        Some(selection_key_from_value(
16462            payload.get("selection_member_key"),
16463            sequence,
16464        )?)
16465    } else {
16466        None
16467    };
16468    let selection_member_index = if mode == "select" {
16469        Some(required_parallel_usize(
16470            payload,
16471            "selection_member_index",
16472            sequence,
16473        )?)
16474    } else {
16475        None
16476    };
16477    let selection_member_base_sequence = if mode == "select" {
16478        Some(
16479            payload
16480                .get("selection_member_base_sequence")
16481                .and_then(value_as_u64)
16482                .filter(|value| *value >= base_sequence)
16483                .ok_or_else(|| {
16484                    invalid_recorded_history(
16485                        "parallel_group_metadata_invalid",
16486                        sequence,
16487                        "selection member base within its group",
16488                        &payload.to_string(),
16489                        "selection history contains an invalid member base sequence",
16490                    )
16491                })?,
16492        )
16493    } else {
16494        None
16495    };
16496    let selection_member_size = if mode == "select" {
16497        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
16498        if member_size == 0 {
16499            return Err(invalid_recorded_history(
16500                "parallel_group_metadata_invalid",
16501                sequence,
16502                "positive selection member size",
16503                &payload.to_string(),
16504                "selection history contains an invalid member size",
16505            ));
16506        }
16507        Some(member_size)
16508    } else {
16509        None
16510    };
16511    let selection_member_kind = if mode == "select" {
16512        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
16513            invalid_recorded_history(
16514                "parallel_group_metadata_invalid",
16515                sequence,
16516                "selection member operation kind",
16517                &payload.to_string(),
16518                "selection history is missing its authored member kind",
16519            )
16520        })?;
16521        if !matches!(
16522            kind.as_str(),
16523            "activity" | "child" | "timer" | "signal" | "condition" | "group"
16524        ) {
16525            return Err(invalid_recorded_history(
16526                "parallel_group_metadata_invalid",
16527                sequence,
16528                "activity, child, timer, signal, condition, or group selection member kind",
16529                &kind,
16530                "selection history contains an unsupported member kind",
16531            ));
16532        }
16533        Some(kind)
16534    } else {
16535        None
16536    };
16537    if let (Some(member_base), Some(member_size)) =
16538        (selection_member_base_sequence, selection_member_size)
16539    {
16540        let member_end = member_base
16541            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
16542            .ok_or_else(|| {
16543                invalid_recorded_history(
16544                    "parallel_group_metadata_invalid",
16545                    sequence,
16546                    "bounded selection member range",
16547                    &payload.to_string(),
16548                    "selection member range overflowed",
16549                )
16550            })?;
16551        let group_end = base_sequence
16552            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
16553            .unwrap_or(u64::MAX);
16554        if sequence < member_base || sequence >= member_end || member_end > group_end {
16555            return Err(invalid_recorded_history(
16556                "parallel_group_metadata_invalid",
16557                sequence,
16558                "workflow sequence within one bounded selection member",
16559                &payload.to_string(),
16560                "selection member range does not contain its durable leaf",
16561            ));
16562        }
16563    }
16564    Ok(ParallelGroupMetadata {
16565        parallel_group_id: group_id,
16566        parallel_group_kind: kind,
16567        parallel_group_base_sequence: base_sequence,
16568        parallel_group_size: size,
16569        parallel_group_index: index,
16570        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
16571        selection_member_key,
16572        selection_member_index,
16573        selection_member_base_sequence,
16574        selection_member_size,
16575        selection_member_kind,
16576    })
16577}
16578
16579fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
16580    payload
16581        .get(field)
16582        .and_then(value_as_u64)
16583        .and_then(|value| usize::try_from(value).ok())
16584        .ok_or_else(|| {
16585            invalid_recorded_history(
16586                "parallel_group_metadata_invalid",
16587                sequence,
16588                &format!("non-negative integer {field}"),
16589                &payload.to_string(),
16590                "selection history contains invalid member metadata",
16591            )
16592        })
16593}
16594
16595fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
16596    match value {
16597        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
16598        Some(value) => value_as_u64(value)
16599            .and_then(|value| usize::try_from(value).ok())
16600            .map(SelectionKey::Index)
16601            .ok_or_else(|| {
16602                invalid_recorded_history(
16603                    "selection_member_key_invalid",
16604                    sequence,
16605                    "non-empty string or non-negative integer member key",
16606                    &value.to_string(),
16607                    "selection history contains an invalid member key",
16608                )
16609            }),
16610        None => Err(invalid_recorded_history(
16611            "selection_member_key_missing",
16612            sequence,
16613            "selection_member_key",
16614            "<missing>",
16615            "selection history is missing its stable member key",
16616        )),
16617    }
16618}
16619
16620fn recorded_parallel_group_path(
16621    events: &[&HistoryEvent],
16622    sequence: u64,
16623) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16624    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
16625    for event in events {
16626        let payload = &event.payload;
16627        let has_metadata = payload.get("parallel_group_path").is_some()
16628            || payload.get("parallel_group_id").is_some()
16629            || payload.get("parallel_group_kind").is_some()
16630            || payload.get("parallel_group_base_sequence").is_some()
16631            || payload.get("parallel_group_size").is_some()
16632            || payload.get("parallel_group_index").is_some()
16633            || payload.get("parallel_group_mode").is_some()
16634            || payload.get("selection_member_key").is_some();
16635        if !has_metadata {
16636            continue;
16637        }
16638
16639        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16640        let path = match payload.get("parallel_group_path") {
16641            None => vec![top_level.clone()],
16642            Some(Value::Array(entries)) if !entries.is_empty() => entries
16643                .iter()
16644                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16645                .collect::<Result<Vec<_>>>()?,
16646            Some(value) => {
16647                return Err(invalid_recorded_history(
16648                    "parallel_group_metadata_invalid",
16649                    sequence,
16650                    "non-empty parallel_group_path list",
16651                    &value.to_string(),
16652                    "parallel-group history contains an invalid group path",
16653                ));
16654            }
16655        };
16656        if path.last() != Some(&top_level) {
16657            return Err(invalid_recorded_history(
16658                "parallel_group_metadata_invalid",
16659                sequence,
16660                &serde_json::to_string(&path.last()).unwrap_or_default(),
16661                &serde_json::to_string(&top_level).unwrap_or_default(),
16662                "parallel-group top-level fields do not match the innermost path entry",
16663            ));
16664        }
16665        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16666            return Err(invalid_recorded_history(
16667                "parallel_group_history_conflict",
16668                sequence,
16669                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16670                &serde_json::to_string(&path).unwrap_or_default(),
16671                "parallel-group metadata changed between scheduling and resolution history",
16672            ));
16673        }
16674        recorded = Some(path);
16675    }
16676    Ok(recorded)
16677}
16678
16679fn recorded_commands(
16680    events: &[HistoryEvent],
16681    fallback_codec: &str,
16682    parent: WorkflowIdentity,
16683) -> Result<Vec<RecordedCommand>> {
16684    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16685    let mut last_new_sequence = None;
16686
16687    for event in events {
16688        let is_activity = matches!(
16689            event.event_type.as_str(),
16690            "ActivityScheduled"
16691                | "ActivityStarted"
16692                | "ActivityHeartbeatRecorded"
16693                | "ActivityRetryScheduled"
16694                | "ActivityCompleted"
16695                | "ActivityFailed"
16696                | "ActivityCancelled"
16697                | "ActivityTimedOut"
16698        );
16699        let is_workflow_timer = matches!(
16700            event.event_type.as_str(),
16701            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16702        ) && !is_internal_timer_event(event);
16703        let is_child_workflow = matches!(
16704            event.event_type.as_str(),
16705            "ChildWorkflowScheduled"
16706                | "ChildRunStarted"
16707                | "ChildRunCompleted"
16708                | "ChildRunFailed"
16709                | "ChildRunCancelled"
16710                | "ChildRunTerminated"
16711        );
16712        let is_signal_wait = is_recorded_signal_wait_event(event);
16713        let is_condition_wait = is_recorded_condition_wait_event(event);
16714        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16715        let is_side_effect = event.event_type == "SideEffectRecorded";
16716        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16717        let is_memo = event.event_type == "MemoUpserted";
16718        let is_service_operation = nexus::is_service_event(event);
16719        if !is_activity
16720            && !is_workflow_timer
16721            && !is_child_workflow
16722            && !is_signal_wait
16723            && !is_condition_wait
16724            && !is_search_attributes
16725            && !is_side_effect
16726            && !is_version_marker
16727            && !is_memo
16728            && !is_service_operation
16729        {
16730            continue;
16731        }
16732
16733        let sequence = durable_event_sequence(event).ok_or_else(|| {
16734            Error::NonDeterministicReplay(ReplayFailure::new(
16735                "durable_command_sequence_missing",
16736                None,
16737                Some("positive workflow sequence".to_string()),
16738                Some(event.event_type.clone()),
16739                "durable command history event has no workflow sequence",
16740            ))
16741        })?;
16742        if sequence == 0 {
16743            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16744                "durable_command_sequence_invalid",
16745                Some(sequence),
16746                Some("positive workflow sequence".to_string()),
16747                Some(sequence.to_string()),
16748                "durable command history uses an invalid workflow sequence",
16749            )));
16750        }
16751        if !events_by_sequence.contains_key(&sequence) {
16752            if let Some(previous) = last_new_sequence {
16753                if sequence < previous {
16754                    return Err(invalid_recorded_history(
16755                        "durable_command_sequence_mismatch",
16756                        sequence,
16757                        &format!("workflow sequence greater than {previous}"),
16758                        &sequence.to_string(),
16759                        "durable commands are not strictly ordered by their recorded workflow sequence",
16760                    ));
16761                }
16762            }
16763            last_new_sequence = Some(sequence);
16764        }
16765        events_by_sequence.entry(sequence).or_default().push(event);
16766    }
16767
16768    let commands: Vec<RecordedCommand> = events_by_sequence
16769        .into_iter()
16770        .map(|(sequence, sequence_events)| {
16771            let activity_events: Vec<_> = sequence_events
16772                .iter()
16773                .copied()
16774                .filter(|event| event.event_type.starts_with("Activity"))
16775                .collect();
16776            let timer_events: Vec<_> = sequence_events
16777                .iter()
16778                .copied()
16779                .filter(|event| event.event_type.starts_with("Timer"))
16780                .collect();
16781            let child_events: Vec<_> = sequence_events
16782                .iter()
16783                .copied()
16784                .filter(|event| {
16785                    event.event_type == "ChildWorkflowScheduled"
16786                        || event.event_type.starts_with("ChildRun")
16787                })
16788                .collect();
16789            let signal_wait_events: Vec<_> = sequence_events
16790                .iter()
16791                .copied()
16792                .filter(|event| is_recorded_signal_wait_event(event))
16793                .collect();
16794            let condition_wait_events: Vec<_> = sequence_events
16795                .iter()
16796                .copied()
16797                .filter(|event| is_recorded_condition_wait_event(event))
16798                .collect();
16799            let search_attribute_events: Vec<_> = sequence_events
16800                .iter()
16801                .copied()
16802                .filter(|event| event.event_type == "SearchAttributesUpserted")
16803                .collect();
16804            let side_effect_events: Vec<_> = sequence_events
16805                .iter()
16806                .copied()
16807                .filter(|event| event.event_type == "SideEffectRecorded")
16808                .collect();
16809            let version_marker_events: Vec<_> = sequence_events
16810                .iter()
16811                .copied()
16812                .filter(|event| event.event_type == "VersionMarkerRecorded")
16813                .collect();
16814            let memo_events: Vec<_> = sequence_events
16815                .iter()
16816                .copied()
16817                .filter(|event| event.event_type == "MemoUpserted")
16818                .collect();
16819            let service_events: Vec<_> = sequence_events.iter().copied()
16820                .filter(|event| nexus::is_service_event(event)).collect();
16821
16822            let command_kind_count = usize::from(!activity_events.is_empty())
16823                + usize::from(!timer_events.is_empty())
16824                + usize::from(!child_events.is_empty())
16825                + usize::from(!signal_wait_events.is_empty())
16826                + usize::from(!condition_wait_events.is_empty())
16827                + usize::from(!search_attribute_events.is_empty())
16828                + usize::from(!side_effect_events.is_empty())
16829                + usize::from(!version_marker_events.is_empty())
16830                + usize::from(!memo_events.is_empty())
16831                + usize::from(!service_events.is_empty());
16832            if command_kind_count > 1 {
16833                let actual = [
16834                    (!activity_events.is_empty()).then_some("activity"),
16835                    (!timer_events.is_empty()).then_some("timer"),
16836                    (!child_events.is_empty()).then_some("child workflow"),
16837                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16838                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16839                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16840                    (!side_effect_events.is_empty()).then_some("side effect"),
16841                    (!version_marker_events.is_empty()).then_some("version marker"),
16842                    (!memo_events.is_empty()).then_some("memo upsert"),
16843                    (!service_events.is_empty()).then_some("service operation"),
16844                ]
16845                .into_iter()
16846                .flatten()
16847                .collect::<Vec<_>>()
16848                .join(" and ");
16849                return Err(invalid_recorded_history(
16850                    "durable_command_sequence_collision",
16851                    sequence,
16852                    "one durable command kind",
16853                    &actual,
16854                    "one workflow sequence records more than one durable command kind",
16855                ));
16856            }
16857
16858            if !service_events.is_empty() {
16859                return Ok(RecordedCommand::ServiceOperation {
16860                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16861                });
16862            }
16863
16864            if !activity_events.is_empty() {
16865                let parallel_group_path =
16866                    recorded_parallel_group_path(&activity_events, sequence)?;
16867                let scheduled_count = activity_events
16868                    .iter()
16869                    .filter(|event| event.event_type == "ActivityScheduled")
16870                    .count();
16871                if scheduled_count > 1 {
16872                    return Err(invalid_recorded_history(
16873                        "duplicate_activity_schedule",
16874                        sequence,
16875                        "at most one ActivityScheduled event",
16876                        "multiple ActivityScheduled events",
16877                        "activity history schedules more than one command at one workflow sequence",
16878                    ));
16879                }
16880                let activity_type = activity_events.iter().find_map(|event| {
16881                    event
16882                        .payload
16883                        .get("activity_type")
16884                        .or_else(|| event.payload.get("activity_name"))
16885                        .and_then(Value::as_str)
16886                        .map(str::to_string)
16887                });
16888                if activity_events.iter().filter_map(|event| {
16889                    event
16890                        .payload
16891                        .get("activity_type")
16892                        .or_else(|| event.payload.get("activity_name"))
16893                        .and_then(Value::as_str)
16894                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16895                    return Err(invalid_recorded_history(
16896                        "activity_identity_mismatch",
16897                        sequence,
16898                        activity_type.as_deref().unwrap_or("one activity identity"),
16899                        "conflicting activity identities",
16900                        "activity lifecycle events at one workflow sequence disagree on identity",
16901                    ));
16902                }
16903                let terminal: Vec<_> = activity_events
16904                    .iter()
16905                    .copied()
16906                    .filter(|event| {
16907                        matches!(
16908                            event.event_type.as_str(),
16909                            "ActivityCompleted"
16910                                | "ActivityFailed"
16911                                | "ActivityCancelled"
16912                                | "ActivityTimedOut"
16913                        )
16914                    })
16915                    .collect();
16916                let duplicate_delivery = terminal.first().is_some_and(|first| {
16917                    terminal.iter().all(|event| {
16918                        event.event_type == first.event_type && event.payload == first.payload
16919                    })
16920                });
16921                if terminal.len() > 1 && !duplicate_delivery {
16922                    return Err(invalid_recorded_history(
16923                        "duplicate_activity_terminal_event",
16924                        sequence,
16925                        "at most one terminal activity event",
16926                        "multiple terminal activity events",
16927                        "activity history settles one command more than once",
16928                    ));
16929                }
16930                let outcome = terminal
16931                    .first()
16932                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16933                    .transpose()?;
16934                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16935                let activity_snapshot = activity_events
16936                    .iter()
16937                    .find(|event| event.event_type == "ActivityScheduled")
16938                    .and_then(|event| event.payload.get("activity"))
16939                    .and_then(Value::as_object);
16940                let options = Some(match activity_snapshot {
16941                    Some(activity) => RecordedActivityOptions {
16942                        task_queue: recorded_optional_string(activity, "queue"),
16943                        execution_mode,
16944                        retry_policy: recorded_activity_retry_snapshot(
16945                            activity.get("retry_policy"),
16946                        ),
16947                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16948                    },
16949                    None => RecordedActivityOptions {
16950                        task_queue: RecordedSnapshotValue::Unknown,
16951                        execution_mode,
16952                        retry_policy: recorded_activity_retry_snapshot(None),
16953                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16954                    },
16955                });
16956                return Ok(RecordedCommand::Activity {
16957                    sequence,
16958                    activity_type,
16959                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16960                    options,
16961                    outcome,
16962                    parallel_group_path,
16963                });
16964            }
16965
16966            if !child_events.is_empty() {
16967                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16968                let scheduled: Vec<_> = child_events
16969                    .iter()
16970                    .copied()
16971                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16972                    .collect();
16973                if scheduled.len() != 1 {
16974                    return Err(invalid_recorded_history(
16975                        "child_workflow_schedule_missing_or_duplicate",
16976                        sequence,
16977                        "one ChildWorkflowScheduled event",
16978                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16979                        "child workflow replay requires exactly one recorded schedule event",
16980                    ));
16981                }
16982                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16983                let workflow_type = child_events.iter().find_map(|event| {
16984                    event
16985                        .payload
16986                        .get("child_workflow_type")
16987                        .or_else(|| event.payload.get("workflow_type"))
16988                        .and_then(Value::as_str)
16989                        .filter(|value| !value.is_empty())
16990                        .map(str::to_string)
16991                });
16992                if child_events
16993                    .iter()
16994                    .filter_map(|event| {
16995                        event
16996                            .payload
16997                            .get("child_workflow_type")
16998                            .or_else(|| event.payload.get("workflow_type"))
16999                            .and_then(Value::as_str)
17000                    })
17001                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
17002                {
17003                    return Err(invalid_recorded_history(
17004                        "child_workflow_identity_mismatch",
17005                        sequence,
17006                        workflow_type
17007                            .as_deref()
17008                            .unwrap_or("one child workflow type"),
17009                        "conflicting child workflow types",
17010                        "child workflow lifecycle events at one sequence disagree on type",
17011                    ));
17012                }
17013                let mut outcomes = child_workflow_outcomes(
17014                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
17015                    fallback_codec,
17016                    parent.clone(),
17017                )?;
17018                let terminal_events = child_events
17019                    .iter()
17020                    .copied()
17021                    .filter(|event| event.event_type.starts_with("ChildRun"))
17022                    .collect::<Vec<_>>();
17023                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
17024                    terminal_events.iter().all(|event| {
17025                        event.event_type == first.event_type && event.payload == first.payload
17026                    })
17027                });
17028                if outcomes.len() > 1 && !duplicate_delivery {
17029                    return Err(invalid_recorded_history(
17030                        "duplicate_child_workflow_terminal_event",
17031                        sequence,
17032                        "at most one terminal child event",
17033                        "multiple terminal child events",
17034                        "child workflow history settles one command more than once",
17035                    ));
17036                }
17037                return Ok(RecordedCommand::ChildWorkflow {
17038                    sequence,
17039                    workflow_type,
17040                    policies,
17041                    outcome: outcomes.pop(),
17042                    parallel_group_path,
17043                });
17044            }
17045
17046            if !signal_wait_events.is_empty() {
17047                let opened: Vec<_> = signal_wait_events
17048                    .iter()
17049                    .copied()
17050                    .filter(|event| event.event_type == "SignalWaitOpened")
17051                    .collect();
17052                if opened.len() != 1 {
17053                    return Err(invalid_recorded_history(
17054                        "signal_wait_open_missing_or_duplicate",
17055                        sequence,
17056                        "one SignalWaitOpened event",
17057                        &format!("{} SignalWaitOpened events", opened.len()),
17058                        "signal replay requires exactly one canonical wait-open event",
17059                    ));
17060                }
17061
17062                let applied: Vec<_> = signal_wait_events
17063                    .iter()
17064                    .copied()
17065                    .filter(|event| event.event_type == "SignalApplied")
17066                    .collect();
17067                if applied.len() > 1 {
17068                    return Err(invalid_recorded_history(
17069                        "duplicate_signal_wait_apply",
17070                        sequence,
17071                        "at most one SignalApplied event",
17072                        "multiple SignalApplied events",
17073                        "signal history applies one durable wait more than once",
17074                    ));
17075                }
17076
17077                let signal_names = signal_wait_events
17078                    .iter()
17079                    .map(|event| required_signal_wait_name(event, sequence))
17080                    .collect::<Result<Vec<_>>>()?;
17081                let signal_name = signal_names
17082                    .first()
17083                    .expect("signal wait events are not empty")
17084                    .clone();
17085                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17086                    return Err(invalid_recorded_history(
17087                        "signal_wait_identity_mismatch",
17088                        sequence,
17089                        &signal_name,
17090                        "conflicting signal names",
17091                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17092                    ));
17093                }
17094                let value = applied
17095                    .first()
17096                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17097                    .transpose()?;
17098                return Ok(RecordedCommand::SignalWait {
17099                    sequence,
17100                    signal_name,
17101                    value,
17102                    parallel_group_path: recorded_parallel_group_path(
17103                        &signal_wait_events,
17104                        sequence,
17105                    )?,
17106                });
17107            }
17108
17109            if !condition_wait_events.is_empty() {
17110                return recorded_condition_wait(
17111                    sequence,
17112                    &condition_wait_events,
17113                    events,
17114                );
17115            }
17116
17117            if !search_attribute_events.is_empty() {
17118                if search_attribute_events.len() != 1 {
17119                    return Err(invalid_recorded_history(
17120                        "duplicate_search_attribute_update",
17121                        sequence,
17122                        "one SearchAttributesUpserted event",
17123                        &format!(
17124                            "{} SearchAttributesUpserted events",
17125                            search_attribute_events.len()
17126                        ),
17127                        "search-attribute history records one workflow command more than once",
17128                    ));
17129                }
17130                let payload = &search_attribute_events[0].payload;
17131                let attributes = payload
17132                    .get("attributes")
17133                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17134                    .cloned()
17135                    .ok_or_else(|| {
17136                        invalid_recorded_history(
17137                            "search_attribute_update_missing",
17138                            sequence,
17139                            "non-empty attributes object",
17140                            "missing or invalid attributes",
17141                            "search-attribute history is missing its recorded mutation",
17142                        )
17143                    })?;
17144                let attribute_types =
17145                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17146                return Ok(RecordedCommand::SearchAttributes {
17147                    sequence,
17148                    attributes,
17149                    attribute_types,
17150                });
17151            }
17152
17153            if !side_effect_events.is_empty() {
17154                if side_effect_events.len() != 1 {
17155                    return Err(invalid_recorded_history(
17156                        "duplicate_side_effect_record",
17157                        sequence,
17158                        "one SideEffectRecorded event",
17159                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17160                        "side-effect history records one workflow command more than once",
17161                    ));
17162                }
17163                let event = side_effect_events[0];
17164                let result = event.payload.get("result").ok_or_else(|| {
17165                    invalid_recorded_history(
17166                        "side_effect_result_missing",
17167                        sequence,
17168                        "recorded result payload",
17169                        "missing result",
17170                        "side-effect history is missing its recorded value",
17171                    )
17172                })?;
17173                let has_published_envelope = result.as_str().is_some()
17174                    || result.as_object().is_some_and(|envelope| {
17175                        envelope.get("codec").and_then(Value::as_str).is_some()
17176                            && envelope.get("blob").and_then(Value::as_str).is_some()
17177                    });
17178                if !has_published_envelope {
17179                    return Err(invalid_recorded_history(
17180                        "side_effect_payload_malformed",
17181                        sequence,
17182                        "payload blob or {codec, blob} envelope",
17183                        &result.to_string(),
17184                        "side-effect history result does not use a published payload envelope",
17185                    ));
17186                }
17187                let codec = event
17188                    .payload
17189                    .get("payload_codec")
17190                    .and_then(Value::as_str)
17191                    .unwrap_or(fallback_codec);
17192                let value = decode_wire_avro_value(result, codec).map_err(|error| {
17193                    if error.to_string().contains("unsupported_payload_codec") {
17194                        return error;
17195                    }
17196
17197                    invalid_recorded_history(
17198                        "side_effect_payload_incompatible",
17199                        sequence,
17200                        &format!("valid {codec} payload envelope"),
17201                        &error.to_string(),
17202                        "side-effect history payload cannot be decoded with its recorded codec",
17203                    )
17204                })?;
17205                return Ok(RecordedCommand::SideEffect { sequence, value });
17206            }
17207
17208            if !version_marker_events.is_empty() {
17209                if version_marker_events.len() != 1 {
17210                    return Err(invalid_recorded_history(
17211                        "duplicate_version_marker_record",
17212                        sequence,
17213                        "one VersionMarkerRecorded event",
17214                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
17215                        "version-marker history records one workflow command more than once",
17216                    ));
17217                }
17218                let payload = &version_marker_events[0].payload;
17219                let change_id = payload
17220                    .get("change_id")
17221                    .and_then(Value::as_str)
17222                    .filter(|value| !value.is_empty())
17223                    .map(str::to_string)
17224                    .ok_or_else(|| {
17225                        invalid_recorded_history(
17226                            "version_marker_field_missing",
17227                            sequence,
17228                            "non-empty change_id",
17229                            "missing or invalid change_id",
17230                            "version-marker history is missing its stable change ID",
17231                        )
17232                    })?;
17233                let version = required_version_i32(payload, "version", sequence)?;
17234                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
17235                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
17236                if min_supported > max_supported || version < min_supported || version > max_supported {
17237                    return Err(invalid_recorded_history(
17238                        "version_marker_history_range_invalid",
17239                        sequence,
17240                        "min_supported <= version <= max_supported",
17241                        &format!("{min_supported} <= {version} <= {max_supported}"),
17242                        "recorded version marker contains an internally incompatible range",
17243                    ));
17244                }
17245                return Ok(RecordedCommand::VersionMarker {
17246                    sequence,
17247                    change_id,
17248                    version,
17249                });
17250            }
17251
17252            if !memo_events.is_empty() {
17253                if memo_events.len() != 1 {
17254                    return Err(invalid_recorded_history(
17255                        "duplicate_memo_upsert_record",
17256                        sequence,
17257                        "one MemoUpserted event",
17258                        &format!("{} MemoUpserted events", memo_events.len()),
17259                        "memo history records one workflow update more than once",
17260                    ));
17261                }
17262                let payload = &memo_events[0].payload;
17263                let entries = payload.get("entries").cloned().ok_or_else(|| {
17264                    invalid_recorded_history(
17265                        "memo_entries_missing",
17266                        sequence,
17267                        "memo entries object",
17268                        "missing entries",
17269                        "MemoUpserted history is missing replay identity entries",
17270                    )
17271                })?;
17272                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
17273                    invalid_recorded_history(
17274                        "memo_entries_invalid",
17275                        sequence,
17276                        "valid canonical memo entries",
17277                        &error.to_string(),
17278                        "MemoUpserted history contains invalid replay identity entries",
17279                    )
17280                })?;
17281                let merged = payload.get("merged").cloned().ok_or_else(|| {
17282                    invalid_recorded_history(
17283                        "memo_merged_projection_missing",
17284                        sequence,
17285                        "merged memo projection",
17286                        "missing merged",
17287                        "MemoUpserted history is missing its merged projection",
17288                    )
17289                })?;
17290                decode_memo_history_map(&merged, false).map_err(|error| {
17291                    invalid_recorded_history(
17292                        "memo_merged_projection_invalid",
17293                        sequence,
17294                        "valid merged memo projection",
17295                        &error.to_string(),
17296                        "MemoUpserted history contains an invalid merged projection",
17297                    )
17298                })?;
17299
17300                return Ok(RecordedCommand::Memo { sequence, entries });
17301            }
17302            let scheduled: Vec<_> = timer_events
17303                .iter()
17304                .copied()
17305                .filter(|event| event.event_type == "TimerScheduled")
17306                .collect();
17307            let fired: Vec<_> = timer_events
17308                .iter()
17309                .copied()
17310                .filter(|event| event.event_type == "TimerFired")
17311                .collect();
17312            if scheduled.len() != 1 {
17313                return Err(invalid_recorded_history(
17314                    "timer_schedule_missing_or_duplicate",
17315                    sequence,
17316                    "one TimerScheduled event",
17317                    &format!("{} TimerScheduled events", scheduled.len()),
17318                    "timer replay requires exactly one recorded schedule event",
17319                ));
17320            }
17321            if fired.len() > 1 {
17322                return Err(invalid_recorded_history(
17323                    "duplicate_timer_fire",
17324                    sequence,
17325                    "at most one TimerFired event",
17326                    "multiple TimerFired events",
17327                    "timer history contains more than one fire event for a workflow sequence",
17328                ));
17329            }
17330
17331            let scheduled = scheduled[0];
17332            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17333            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17334            if let Some(fired) = fired.first() {
17335                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17336                if fired_timer_id != timer_id {
17337                    return Err(invalid_recorded_history(
17338                        "timer_identity_mismatch",
17339                        sequence,
17340                        &timer_id,
17341                        &fired_timer_id,
17342                        "TimerFired does not correspond to the recorded TimerScheduled event",
17343                    ));
17344                }
17345                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17346                if fired_delay != delay_seconds {
17347                    return Err(invalid_recorded_history(
17348                        "timer_history_delay_mismatch",
17349                        sequence,
17350                        &delay_seconds.to_string(),
17351                        &fired_delay.to_string(),
17352                        "TimerScheduled and TimerFired record different delays",
17353                    ));
17354                }
17355            }
17356
17357            Ok(RecordedCommand::Timer {
17358                sequence,
17359                delay_seconds,
17360                fired: !fired.is_empty(),
17361                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
17362            })
17363        })
17364        .collect::<Result<_>>()?;
17365
17366    let mut marker_decisions = HashMap::new();
17367    for command in &commands {
17368        if let RecordedCommand::VersionMarker {
17369            sequence,
17370            change_id,
17371            version,
17372        } = command
17373        {
17374            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
17375                if version != first_version {
17376                    return Err(invalid_recorded_history(
17377                        "version_marker_conflict",
17378                        *sequence,
17379                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
17380                        &format!("version {version} at sequence {sequence}"),
17381                        "workflow history contains conflicting decisions for one stable change ID",
17382                    ));
17383                }
17384            } else {
17385                marker_decisions.insert(change_id.clone(), (*version, *sequence));
17386            }
17387        }
17388    }
17389
17390    Ok(commands)
17391}
17392
17393fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
17394    payload
17395        .get(field)
17396        .and_then(Value::as_i64)
17397        .and_then(|value| i32::try_from(value).ok())
17398        .ok_or_else(|| {
17399            invalid_recorded_history(
17400                "version_marker_field_missing",
17401                sequence,
17402                &format!("integer {field}"),
17403                "missing or out-of-range integer",
17404                "version-marker history is missing a required integer field",
17405            )
17406        })
17407}
17408
17409fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
17410    event
17411        .payload
17412        .get("sequence")
17413        .or_else(|| event.payload.get("workflow_sequence"))
17414        .or_else(|| event.raw.get("sequence"))
17415        .or_else(|| event.raw.get("workflow_sequence"))
17416        .and_then(value_as_u64)
17417}
17418
17419fn is_internal_timer_event(event: &HistoryEvent) -> bool {
17420    matches!(
17421        event
17422            .payload
17423            .get("timer_kind")
17424            .or_else(|| event.raw.get("timer_kind"))
17425            .and_then(Value::as_str),
17426        Some("condition_timeout" | "signal_timeout")
17427    )
17428}
17429
17430fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
17431    matches!(
17432        event.event_type.as_str(),
17433        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17434    )
17435}
17436
17437fn recorded_condition_wait(
17438    sequence: u64,
17439    condition_events: &[&HistoryEvent],
17440    all_events: &[HistoryEvent],
17441) -> Result<RecordedCommand> {
17442    let opened = condition_events
17443        .iter()
17444        .copied()
17445        .filter(|event| event.event_type == "ConditionWaitOpened")
17446        .collect::<Vec<_>>();
17447    if opened.len() != 1 {
17448        return Err(invalid_recorded_history(
17449            "condition_wait_open_missing_or_duplicate",
17450            sequence,
17451            "one ConditionWaitOpened event",
17452            &format!("{} ConditionWaitOpened events", opened.len()),
17453            "condition replay requires exactly one canonical wait-open event",
17454        ));
17455    }
17456    let terminal = condition_events
17457        .iter()
17458        .copied()
17459        .filter(|event| {
17460            matches!(
17461                event.event_type.as_str(),
17462                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17463            )
17464        })
17465        .collect::<Vec<_>>();
17466    if terminal.len() > 1 {
17467        return Err(invalid_recorded_history(
17468            "duplicate_condition_wait_terminal_event",
17469            sequence,
17470            "at most one condition terminal event",
17471            "multiple condition terminal events",
17472            "condition history settles one durable wait more than once",
17473        ));
17474    }
17475
17476    let opened = opened[0];
17477    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
17478    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
17479    for event in condition_events
17480        .iter()
17481        .copied()
17482        .filter(|event| !std::ptr::eq(*event, opened))
17483    {
17484        let event_wait_id = required_condition_wait_id(event, sequence)?;
17485        if event_wait_id != condition_wait_id {
17486            return Err(invalid_recorded_history(
17487                "condition_wait_id_mismatch",
17488                sequence,
17489                &condition_wait_id,
17490                &event_wait_id,
17491                "condition lifecycle events at one sequence disagree on wait identity",
17492            ));
17493        }
17494        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
17495        if event_occurrence_id != occurrence_id {
17496            return Err(invalid_recorded_history(
17497                "condition_wait_occurrence_history_mismatch",
17498                sequence,
17499                &occurrence_id,
17500                &event_occurrence_id,
17501                "condition lifecycle events at one sequence disagree on authored occurrence identity",
17502            ));
17503        }
17504    }
17505
17506    let condition_key = optional_non_empty_history_string(opened, "condition_key");
17507    let predicate_identity = opened
17508        .payload
17509        .get("condition_definition_fingerprint")
17510        .and_then(Value::as_str)
17511        .filter(|value| !value.is_empty())
17512        .map(str::to_string)
17513        .ok_or_else(|| {
17514            invalid_recorded_history(
17515                "condition_wait_predicate_fingerprint_missing",
17516                sequence,
17517                "non-empty condition_definition_fingerprint",
17518                &opened.event_type,
17519                "canonical condition history is missing its predicate identity",
17520            )
17521        })?;
17522    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
17523    for event in condition_events
17524        .iter()
17525        .copied()
17526        .filter(|event| !std::ptr::eq(*event, opened))
17527    {
17528        for (field, opened_value) in [
17529            ("condition_key", condition_key.as_deref()),
17530            (
17531                "condition_definition_fingerprint",
17532                Some(predicate_identity.as_str()),
17533            ),
17534        ] {
17535            if let Some(value) = optional_non_empty_history_string(event, field) {
17536                if opened_value.is_some_and(|opened_value| opened_value != value) {
17537                    return Err(invalid_recorded_history(
17538                        "condition_wait_definition_history_mismatch",
17539                        sequence,
17540                        opened_value.unwrap_or_default(),
17541                        &value,
17542                        "condition lifecycle events disagree on the recorded definition",
17543                    ));
17544                }
17545            }
17546        }
17547        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
17548            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
17549                return Err(invalid_recorded_history(
17550                    "condition_wait_definition_history_mismatch",
17551                    sequence,
17552                    &format!("{}s", timeout_seconds.unwrap_or_default()),
17553                    &format!("{event_timeout}s"),
17554                    "condition lifecycle events disagree on the recorded timeout",
17555                ));
17556            }
17557        }
17558    }
17559
17560    let timeout_timer_events = all_events
17561        .iter()
17562        .filter(|event| {
17563            matches!(
17564                event.event_type.as_str(),
17565                "TimerScheduled" | "TimerCancelled" | "TimerFired"
17566            ) && event.payload.get("timer_kind").and_then(Value::as_str)
17567                == Some("condition_timeout")
17568                && event
17569                    .payload
17570                    .get("condition_wait_id")
17571                    .and_then(Value::as_str)
17572                    == Some(condition_wait_id.as_str())
17573        })
17574        .collect::<Vec<_>>();
17575    let scheduled = timeout_timer_events
17576        .iter()
17577        .copied()
17578        .filter(|event| event.event_type == "TimerScheduled")
17579        .collect::<Vec<_>>();
17580    let fired = timeout_timer_events
17581        .iter()
17582        .copied()
17583        .filter(|event| event.event_type == "TimerFired")
17584        .collect::<Vec<_>>();
17585    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
17586        return Err(invalid_recorded_history(
17587            "condition_wait_timeout_history_invalid",
17588            sequence,
17589            "one timeout schedule and at most one fire",
17590            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
17591            "condition timeout history has a missing or duplicate lifecycle event",
17592        ));
17593    }
17594    if let Some(scheduled) = scheduled.first() {
17595        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17596        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17597        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
17598            return Err(invalid_recorded_history(
17599                "condition_wait_timeout_delay_mismatch",
17600                sequence,
17601                &format!("{}s", timeout_seconds.unwrap_or_default()),
17602                &format!("{delay_seconds}s"),
17603                "condition timeout timer differs from the wait definition",
17604            ));
17605        }
17606        if let Some(fired) = fired.first() {
17607            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17608            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17609            if fired_timer_id != timer_id || fired_delay != delay_seconds {
17610                return Err(invalid_recorded_history(
17611                    "condition_wait_timeout_identity_mismatch",
17612                    sequence,
17613                    &format!("{timer_id}:{delay_seconds}s"),
17614                    &format!("{fired_timer_id}:{fired_delay}s"),
17615                    "condition timeout fire does not match its durable schedule",
17616                ));
17617            }
17618        }
17619    }
17620
17621    let result = terminal.first().map(|event| {
17622        if event.event_type == "ConditionWaitTimedOut" {
17623            ConditionWaitResult::TimedOut
17624        } else {
17625            ConditionWaitResult::Satisfied
17626        }
17627    });
17628    let result = if !fired.is_empty() {
17629        if result == Some(ConditionWaitResult::Satisfied) {
17630            return Err(invalid_recorded_history(
17631                "condition_wait_terminal_conflict",
17632                sequence,
17633                "one satisfied or timed-out outcome",
17634                "satisfied event and fired timeout",
17635                "condition history records conflicting terminal outcomes",
17636            ));
17637        }
17638        Some(ConditionWaitResult::TimedOut)
17639    } else {
17640        result
17641    };
17642
17643    Ok(RecordedCommand::ConditionWait {
17644        sequence,
17645        occurrence_id,
17646        condition_key,
17647        predicate_identity,
17648        timeout_seconds,
17649        result,
17650        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17651    })
17652}
17653
17654fn recorded_condition_group_path(
17655    condition_events: &[&HistoryEvent],
17656    all_events: &[HistoryEvent],
17657    sequence: u64,
17658) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17659    let opened = condition_events
17660        .iter()
17661        .copied()
17662        .find(|event| event.event_type == "ConditionWaitOpened")
17663        .expect("canonical condition opener is validated first");
17664    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17665    let previous_events = all_events
17666        .iter()
17667        .take_while(|event| !std::ptr::eq(*event, opened))
17668        .collect::<Vec<_>>();
17669    let originals = previous_events
17670        .iter()
17671        .copied()
17672        .filter(|event| event.event_type == "ConditionWaitOpened")
17673        .filter(|event| {
17674            event
17675                .payload
17676                .get("condition_wait_occurrence_id")
17677                .and_then(Value::as_str)
17678                == Some(occurrence.as_str())
17679        })
17680        .collect::<Vec<_>>();
17681    let Some(original) = originals.first().copied() else {
17682        return recorded_parallel_group_path(condition_events, sequence);
17683    };
17684    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17685    if authored_sequence == sequence {
17686        return recorded_parallel_group_path(condition_events, sequence);
17687    }
17688    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17689    if original_path.is_none() {
17690        return recorded_parallel_group_path(condition_events, sequence);
17691    }
17692    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17693    let identity_matches = [
17694        "condition_key",
17695        "condition_definition_fingerprint",
17696        "timeout_seconds",
17697    ]
17698    .iter()
17699    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17700    let previous = originals
17701        .iter()
17702        .copied()
17703        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17704        .max_by_key(|event| durable_event_sequence(event));
17705    let previously_satisfied = previous.is_some_and(|previous| {
17706        previous_events.iter().any(|event| {
17707            event.event_type == "ConditionWaitSatisfied"
17708                && event.payload.get("condition_wait_id")
17709                    == previous.payload.get("condition_wait_id")
17710                && event.payload.get("condition_wait_occurrence_id")
17711                    == previous.payload.get("condition_wait_occurrence_id")
17712                && durable_event_sequence(event) == durable_event_sequence(previous)
17713        })
17714    });
17715    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17716        return Err(invalid_recorded_history(
17717            "condition_wait_group_reopen_mismatch",
17718            sequence,
17719            "same authored condition and group path after a satisfied physical wait",
17720            &opened.payload.to_string(),
17721            "grouped condition reopen has no matching recorded predecessor",
17722        ));
17723    }
17724    Ok(reopened_path)
17725}
17726
17727fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17728    event
17729        .payload
17730        .get("condition_wait_occurrence_id")
17731        .and_then(Value::as_str)
17732        .filter(|value| !value.is_empty())
17733        .map(str::to_string)
17734        .ok_or_else(|| {
17735            invalid_recorded_history(
17736                "condition_wait_occurrence_id_missing",
17737                sequence,
17738                "non-empty condition_wait_occurrence_id",
17739                &event.event_type,
17740                "condition history is missing authored occurrence identity",
17741            )
17742        })
17743}
17744
17745fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17746    event
17747        .payload
17748        .get("condition_wait_id")
17749        .and_then(Value::as_str)
17750        .filter(|value| !value.is_empty())
17751        .map(str::to_string)
17752        .ok_or_else(|| {
17753            invalid_recorded_history(
17754                "condition_wait_id_missing",
17755                sequence,
17756                "non-empty condition_wait_id",
17757                &event.event_type,
17758                "canonical condition history is missing its durable wait identity",
17759            )
17760        })
17761}
17762
17763fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17764    event
17765        .payload
17766        .get(field)
17767        .and_then(Value::as_str)
17768        .filter(|value| !value.is_empty())
17769        .map(str::to_string)
17770}
17771
17772fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17773    match event.payload.get(field) {
17774        None | Some(Value::Null) => Ok(None),
17775        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17776            invalid_recorded_history(
17777                "condition_wait_definition_invalid",
17778                sequence,
17779                &format!("non-negative integer {field}"),
17780                &value.to_string(),
17781                "condition history contains an invalid numeric definition field",
17782            )
17783        }),
17784    }
17785}
17786
17787fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17788    event
17789        .payload
17790        .get("signal_name")
17791        .or_else(|| event.raw.get("signal_name"))
17792        .and_then(Value::as_str)
17793        .filter(|value| !value.is_empty())
17794        .map(str::to_string)
17795        .ok_or_else(|| {
17796            invalid_recorded_history(
17797                "signal_wait_name_missing",
17798                sequence,
17799                "non-empty signal_name",
17800                &event.event_type,
17801                "canonical signal-wait history is missing its signal identity",
17802            )
17803        })
17804}
17805
17806fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17807    // Applying a buffered control-plane signal has no authored call sequence.
17808    // Its outer sequence orders history events and must not become a wait.
17809    if event.event_type == "SignalApplied"
17810        && event
17811            .payload
17812            .get("signal_wait_id")
17813            .and_then(Value::as_str)
17814            .is_some_and(|id| id.starts_with("signal-command:"))
17815        && event.payload.get("sequence").is_none()
17816        && event.payload.get("workflow_sequence").is_none()
17817    {
17818        return false;
17819    }
17820    matches!(
17821        event.event_type.as_str(),
17822        "SignalWaitOpened" | "SignalApplied"
17823    )
17824}
17825
17826fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17827    event
17828        .payload
17829        .get(field)
17830        .and_then(Value::as_str)
17831        .filter(|value| !value.is_empty())
17832        .map(str::to_string)
17833        .ok_or_else(|| {
17834            invalid_recorded_history(
17835                "timer_history_field_missing",
17836                sequence,
17837                field,
17838                &event.event_type,
17839                "timer history is missing a required identity field",
17840            )
17841        })
17842}
17843
17844fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17845    event
17846        .payload
17847        .get(field)
17848        .and_then(value_as_u64)
17849        .ok_or_else(|| {
17850            invalid_recorded_history(
17851                "timer_history_field_missing",
17852                sequence,
17853                field,
17854                &event.event_type,
17855                "timer history is missing a required numeric field",
17856            )
17857        })
17858}
17859
17860fn recorded_search_attribute_types(
17861    payload: &Value,
17862    attributes: &Value,
17863    sequence: u64,
17864) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17865    let Some(raw_types) = payload.get("attribute_types") else {
17866        // This is the explicit compatibility rule for histories recorded
17867        // before typed identity was persisted. Values still constrain replay;
17868        // the unknown type snapshot does not assert a typed match.
17869        return Ok(RecordedSnapshotValue::Unknown);
17870    };
17871    let Some(raw_types) = raw_types.as_object() else {
17872        return Err(invalid_recorded_history(
17873            "search_attribute_types_malformed",
17874            sequence,
17875            "canonical attribute type map",
17876            &raw_types.to_string(),
17877            "search-attribute history contains malformed type identity",
17878        ));
17879    };
17880    let attribute_keys = attributes
17881        .as_object()
17882        .expect("recorded search attributes were validated as an object");
17883    let mut types = BTreeMap::new();
17884    for (key, value) in raw_types {
17885        let Some(attribute_type) = value.as_str() else {
17886            return Err(invalid_recorded_history(
17887                "search_attribute_types_malformed",
17888                sequence,
17889                "canonical string type name",
17890                &value.to_string(),
17891                "search-attribute history contains a non-string type identity",
17892            ));
17893        };
17894        if !attribute_keys.contains_key(key)
17895            || !matches!(
17896                attribute_type,
17897                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17898            )
17899        {
17900            return Err(invalid_recorded_history(
17901                "search_attribute_types_malformed",
17902                sequence,
17903                "canonical types for keys present in attributes",
17904                &format!("{key}:{attribute_type}"),
17905                "search-attribute history contains unsupported or orphaned type identity",
17906            ));
17907        }
17908        types.insert(key.clone(), attribute_type.to_string());
17909    }
17910    Ok(RecordedSnapshotValue::Known(types))
17911}
17912
17913fn invalid_recorded_history(
17914    reason: &str,
17915    sequence: u64,
17916    expected: &str,
17917    actual: &str,
17918    message: &str,
17919) -> Error {
17920    Error::NonDeterministicReplay(ReplayFailure::new(
17921        reason,
17922        Some(sequence),
17923        Some(expected.to_string()),
17924        Some(actual.to_string()),
17925        message,
17926    ))
17927}
17928
17929type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17930
17931fn activity_outcome(
17932    event: &HistoryEvent,
17933    fallback_codec: &str,
17934    recorded_activity_type: Option<String>,
17935) -> Result<ActivityOutcome> {
17936    if event.event_type == "ActivityCompleted" {
17937        let codec = event
17938            .payload
17939            .get("payload_codec")
17940            .and_then(Value::as_str)
17941            .unwrap_or(fallback_codec);
17942        return Ok(Ok(decode_wire_avro_value(
17943            event.payload.get("result").unwrap_or(&Value::Null),
17944            codec,
17945        )?));
17946    }
17947
17948    let payload = &event.payload;
17949    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17950        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17951        "ActivityCancelled" => (
17952            ActivityFailureKind::Cancelled,
17953            "cancelled",
17954            "activity was cancelled",
17955        ),
17956        "ActivityTimedOut" => (
17957            ActivityFailureKind::TimedOut,
17958            "timeout",
17959            "activity timed out",
17960        ),
17961        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17962    };
17963    let exception = payload
17964        .get("exception")
17965        .filter(|value| !value.is_null())
17966        .cloned();
17967    let failure_category = payload_string(payload, "failure_category");
17968    let timeout_kind = payload_string(payload, "timeout_kind");
17969    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17970        ActivityFailureKind::Failed => failure_category
17971            .clone()
17972            .unwrap_or_else(|| fallback_reason.to_string()),
17973        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17974        ActivityFailureKind::TimedOut => timeout_kind
17975            .clone()
17976            .unwrap_or_else(|| fallback_reason.to_string()),
17977    });
17978    let message = payload_string(payload, "message")
17979        .or_else(|| {
17980            exception
17981                .as_ref()
17982                .and_then(|value| payload_string(value, "message"))
17983        })
17984        .unwrap_or_else(|| fallback_message.to_string());
17985
17986    Ok(Err(ActivityFailure {
17987        kind,
17988        reason,
17989        message,
17990        activity_execution_id: payload_string(payload, "activity_execution_id"),
17991        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17992        activity_type: payload_string(payload, "activity_type")
17993            .or_else(|| payload_string(payload, "activity_name"))
17994            .or(recorded_activity_type),
17995        activity_class: payload_string(payload, "activity_class"),
17996        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17997        failure_id: payload_string(payload, "failure_id"),
17998        failure_category,
17999        timeout_kind,
18000        non_retryable: payload
18001            .get("non_retryable")
18002            .and_then(Value::as_bool)
18003            .unwrap_or(false),
18004        exception_type: payload_string(payload, "exception_type").or_else(|| {
18005            exception
18006                .as_ref()
18007                .and_then(|value| payload_string(value, "type"))
18008        }),
18009        exception_class: payload_string(payload, "exception_class").or_else(|| {
18010            exception
18011                .as_ref()
18012                .and_then(|value| payload_string(value, "class"))
18013        }),
18014        code: payload
18015            .get("code")
18016            .filter(|value| !value.is_null())
18017            .cloned(),
18018        exception,
18019    }))
18020}
18021
18022type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
18023
18024fn child_workflow_outcomes(
18025    events: &[HistoryEvent],
18026    fallback_codec: &str,
18027    parent: WorkflowIdentity,
18028) -> Result<Vec<ChildWorkflowOutcome>> {
18029    let mut outcomes = Vec::new();
18030
18031    for event in events {
18032        let kind = match event.event_type.as_str() {
18033            "ChildRunCompleted" => None,
18034            "ChildRunFailed" => Some((
18035                ChildWorkflowFailureKind::Failed,
18036                "child_workflow",
18037                "child workflow failed",
18038            )),
18039            "ChildRunCancelled" => Some((
18040                ChildWorkflowFailureKind::Cancelled,
18041                "cancelled",
18042                "child workflow was cancelled",
18043            )),
18044            "ChildRunTerminated" => Some((
18045                ChildWorkflowFailureKind::Terminated,
18046                "terminated",
18047                "child workflow was terminated",
18048            )),
18049            _ => continue,
18050        };
18051        let payload = &event.payload;
18052        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
18053        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
18054        let child_workflow_type = payload_string(payload, "child_workflow_type");
18055
18056        if let Some((kind, reason, fallback_message)) = kind {
18057            let exception = payload
18058                .get("exception")
18059                .filter(|value| !value.is_null())
18060                .cloned();
18061            let message = payload_string(payload, "message")
18062                .or_else(|| {
18063                    exception
18064                        .as_ref()
18065                        .and_then(|value| payload_string(value, "message"))
18066                })
18067                .unwrap_or_else(|| fallback_message.to_string());
18068            let exception_type = payload_string(payload, "exception_type").or_else(|| {
18069                exception
18070                    .as_ref()
18071                    .and_then(|value| payload_string(value, "type"))
18072            });
18073            let exception_class = payload_string(payload, "exception_class").or_else(|| {
18074                exception
18075                    .as_ref()
18076                    .and_then(|value| payload_string(value, "class"))
18077            });
18078            outcomes.push(Err(ChildWorkflowFailure {
18079                kind,
18080                reason: reason.to_string(),
18081                message,
18082                parent_workflow_id: parent.workflow_id.clone(),
18083                parent_workflow_run_id: parent.run_id.clone(),
18084                child_workflow_id,
18085                child_workflow_run_id,
18086                child_workflow_type,
18087                failure_id: payload_string(payload, "failure_id"),
18088                failure_category: payload_string(payload, "failure_category"),
18089                exception_type,
18090                exception_class,
18091                non_retryable: payload
18092                    .get("non_retryable")
18093                    .and_then(Value::as_bool)
18094                    .unwrap_or(false),
18095                code: payload
18096                    .get("code")
18097                    .filter(|value| !value.is_null())
18098                    .cloned(),
18099                exception,
18100            }));
18101            continue;
18102        }
18103
18104        let codec = payload
18105            .get("payload_codec")
18106            .and_then(Value::as_str)
18107            .unwrap_or(fallback_codec);
18108        let result = payload
18109            .get("result")
18110            .or_else(|| payload.get("output"))
18111            .unwrap_or(&Value::Null);
18112        outcomes.push(Ok(ChildWorkflowAvroResult {
18113            parent: parent.clone(),
18114            child: WorkflowIdentity {
18115                workflow_id: child_workflow_id,
18116                run_id: child_workflow_run_id,
18117            },
18118            child_workflow_type,
18119            result: decode_wire_avro_value(result, codec)?,
18120        }));
18121    }
18122
18123    Ok(outcomes)
18124}
18125
18126fn payload_string(payload: &Value, key: &str) -> Option<String> {
18127    payload
18128        .get(key)
18129        .and_then(Value::as_str)
18130        .filter(|value| !value.is_empty())
18131        .map(str::to_string)
18132}
18133
18134fn recorded_activity_failure_boundary(
18135    ctx: &WorkflowContext,
18136    error: &Error,
18137) -> Option<(u64, String)> {
18138    let Error::ActivityFailed(failure) = error else {
18139        return None;
18140    };
18141    if failure.kind != ActivityFailureKind::Failed {
18142        return None;
18143    }
18144    let activity_execution_id = failure
18145        .activity_execution_id
18146        .as_deref()
18147        .filter(|value| !value.is_empty())?;
18148    let state = ctx.state.lock().ok()?;
18149    let mut matches = state.recorded_commands.iter().filter_map(|command| {
18150        let RecordedCommand::Activity {
18151            sequence,
18152            outcome: Some(Err(recorded_failure)),
18153            ..
18154        } = command
18155        else {
18156            return None;
18157        };
18158        (*sequence > 0 && recorded_failure == failure)
18159            .then_some((*sequence, activity_execution_id.to_string()))
18160    });
18161    let boundary = matches.next()?;
18162    matches.next().is_none().then_some(boundary)
18163}
18164
18165fn workflow_failure_command(
18166    error: &Error,
18167    failed_activity_boundary: Option<(u64, String)>,
18168) -> Value {
18169    let (exception_type, exception_class, properties) = match error {
18170        Error::NexusOperationFailed(failure) => (
18171            "NexusOperationFailed",
18172            "durable_workflow::NexusOperationFailure",
18173            json!({"service_call_id":failure.service_call_id, "status":failure.status,
18174                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
18175        ),
18176        Error::ActivityFailed(failure) => (
18177            match failure.kind {
18178                ActivityFailureKind::Failed => "ActivityFailed",
18179                ActivityFailureKind::Cancelled => "ActivityCancelled",
18180                ActivityFailureKind::TimedOut => "ActivityTimedOut",
18181            },
18182            "durable_workflow::ActivityFailure",
18183            json!({
18184                "reason": failure.reason,
18185                "activity_execution_id": failure.activity_execution_id,
18186                "activity_attempt_id": failure.activity_attempt_id,
18187                "activity_type": failure.activity_type,
18188                "activity_class": failure.activity_class,
18189                "attempt_number": failure.attempt_number,
18190                "failure_id": failure.failure_id,
18191                "failure_category": failure.failure_category,
18192                "timeout_kind": failure.timeout_kind,
18193                "activity_non_retryable": failure.non_retryable,
18194                "activity_exception_type": failure.exception_type,
18195                "activity_exception_class": failure.exception_class,
18196                "activity_code": failure.code,
18197                "activity_exception": failure.exception,
18198            }),
18199        ),
18200        Error::ChildWorkflowFailed(failure) => (
18201            match failure.kind {
18202                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18203                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18204                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18205            },
18206            "durable_workflow::ChildWorkflowFailure",
18207            json!({
18208                "reason": failure.reason,
18209                "parent_workflow_id": failure.parent_workflow_id,
18210                "parent_workflow_run_id": failure.parent_workflow_run_id,
18211                "child_workflow_id": failure.child_workflow_id,
18212                "child_workflow_run_id": failure.child_workflow_run_id,
18213                "child_workflow_type": failure.child_workflow_type,
18214                "failure_id": failure.failure_id,
18215                "failure_category": failure.failure_category,
18216                "child_exception_type": failure.exception_type,
18217                "child_exception_class": failure.exception_class,
18218                "child_non_retryable": failure.non_retryable,
18219                "child_code": failure.code,
18220                "child_exception": failure.exception,
18221            }),
18222        ),
18223        Error::ParallelFailed(failure) => (
18224            "ParallelFailed",
18225            "durable_workflow::ParallelFailure",
18226            json!({
18227                "parallel_group_id": failure.group_id,
18228                "parallel_member_path": failure.member_path,
18229                "parallel_group_path": failure.group_path,
18230                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
18231                "cause_type": workflow_error_type(&failure.cause),
18232                "cause_message": failure.cause.to_string(),
18233            }),
18234        ),
18235        Error::SagaCompensationFailed(failure) => (
18236            "SagaCompensationFailed",
18237            "durable_workflow::SagaCompensationFailure",
18238            json!({
18239                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
18240                "initiating_failure_message": failure.initiating_failure.to_string(),
18241                "compensation_activity_type": failure.compensation_activity_type,
18242                "compensation_registration_order": failure.compensation_registration_order,
18243                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
18244                "compensation_failure_message": failure.compensation_failure.to_string(),
18245            }),
18246        ),
18247        Error::WorkflowCancellationRequested(_) => (
18248            "WorkflowCancellationRequested",
18249            "durable_workflow::WorkflowCancellationRequested",
18250            json!({"reason": "cancelled"}),
18251        ),
18252        Error::CooperativeCancellationRequested(cancellation) => (
18253            "WorkflowCancellationRequested",
18254            "durable_workflow::CooperativeCancellationRequested",
18255            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
18256                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
18257        ),
18258        Error::CancellationScopeRequested(cancellation) => (
18259            "WorkflowCancellationRequested",
18260            "durable_workflow::CancellationScopeRequested",
18261            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
18262                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
18263                "cancellation":cancellation.context.to_value()}),
18264        ),
18265        Error::NonDeterministicReplay(_) => (
18266            "NonDeterministicReplay",
18267            "durable_workflow::Error",
18268            Value::Null,
18269        ),
18270        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
18271    };
18272    let non_retryable = match error {
18273        Error::ActivityFailed(failure) => failure.non_retryable,
18274        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18275        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18276        Error::SagaCompensationFailed(failure) => {
18277            workflow_error_non_retryable(&failure.compensation_failure)
18278        }
18279        Error::WorkflowCancellationRequested(_)
18280        | Error::CooperativeCancellationRequested(_)
18281        | Error::CancellationScopeRequested(_) => true,
18282        Error::NonDeterministicReplay(_) => true,
18283        _ => false,
18284    };
18285
18286    let mut command = json!({
18287        "type": "fail_workflow",
18288        "message": error.to_string(),
18289        "exception_type": exception_type,
18290        "exception_class": exception_class,
18291        "non_retryable": non_retryable,
18292        "exception": {
18293            "type": exception_type,
18294            "class": exception_class,
18295            "message": error.to_string(),
18296            "properties": properties,
18297        }
18298    });
18299
18300    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
18301        command["failed_step_sequence"] = json!(sequence);
18302        command["failed_activity_execution_id"] = json!(activity_execution_id);
18303    }
18304
18305    command
18306}
18307
18308fn workflow_error_type(error: &Error) -> &'static str {
18309    match error {
18310        Error::NexusOperationFailed(_) => "NexusOperationFailed",
18311        Error::ActivityFailed(failure) => match failure.kind {
18312            ActivityFailureKind::Failed => "ActivityFailed",
18313            ActivityFailureKind::Cancelled => "ActivityCancelled",
18314            ActivityFailureKind::TimedOut => "ActivityTimedOut",
18315        },
18316        Error::ChildWorkflowFailed(failure) => match failure.kind {
18317            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18318            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18319            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18320        },
18321        Error::ParallelFailed(_) => "ParallelFailed",
18322        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
18323        Error::WorkflowCancellationRequested(_)
18324        | Error::CooperativeCancellationRequested(_)
18325        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
18326        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
18327        _ => "RustWorkflowError",
18328    }
18329}
18330
18331fn workflow_error_non_retryable(error: &Error) -> bool {
18332    match error {
18333        Error::ActivityFailed(failure) => failure.non_retryable,
18334        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18335        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18336        Error::SagaCompensationFailed(failure) => {
18337            workflow_error_non_retryable(&failure.compensation_failure)
18338        }
18339        Error::WorkflowCancellationRequested(_)
18340        | Error::CooperativeCancellationRequested(_)
18341        | Error::CancellationScopeRequested(_)
18342        | Error::NonDeterministicReplay(_) => true,
18343        _ => false,
18344    }
18345}
18346
18347fn workflow_task_integrity_error(error: &Error) -> bool {
18348    matches!(
18349        error,
18350        Error::NonDeterministicReplay(_)
18351            | Error::Protocol(_)
18352            | Error::CancellationScopeExecutionUnavailable
18353            | Error::MissingWorkflowCommandIdentity
18354            | Error::WorkflowStatePoisoned
18355    )
18356}
18357
18358fn decode_signal_event_arguments(
18359    event: &HistoryEvent,
18360    fallback_codec: &str,
18361) -> Result<Vec<AvroValue>> {
18362    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18363    validate_payload_codec(codec)?;
18364    let raw = signal_history_payload(&event.payload);
18365    let decoded = match raw.filter(|value| !value.is_null()) {
18366        Some(value) => decode_wire_avro_value(value, codec)?,
18367        None => AvroValue::Array(Vec::new()),
18368    };
18369    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18370        unreachable!("normalize_avro_arguments always returns an array");
18371    };
18372    Ok(arguments)
18373}
18374
18375fn decode_update_event_arguments(
18376    event: &HistoryEvent,
18377    fallback_codec: &str,
18378) -> Result<Vec<AvroValue>> {
18379    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18380    validate_payload_codec(codec)?;
18381    let decoded = match event
18382        .payload
18383        .get("arguments")
18384        .filter(|value| !value.is_null())
18385    {
18386        Some(value) => decode_wire_avro_value(value, codec)?,
18387        None => AvroValue::Array(Vec::new()),
18388    };
18389    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18390        unreachable!("normalize_avro_arguments always returns an array");
18391    };
18392    Ok(arguments)
18393}
18394
18395fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18396    let Some(export_events) = task
18397        .history_export
18398        .as_ref()
18399        .and_then(|export| export.get("history_events"))
18400        .and_then(Value::as_array)
18401    else {
18402        return Ok(());
18403    };
18404
18405    if export_events.len() > task.history_events.len() {
18406        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
18407    }
18408
18409    Ok(())
18410}
18411
18412fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18413    let Some(export) = task.history_export.as_ref() else {
18414        return Ok(());
18415    };
18416    let signals = export
18417        .get("signals")
18418        .and_then(Value::as_array)
18419        .cloned()
18420        .unwrap_or_default();
18421    let activities = export
18422        .get("activities")
18423        .and_then(Value::as_array)
18424        .cloned()
18425        .unwrap_or_default();
18426    let export_codec = export
18427        .get("payloads")
18428        .and_then(|payloads| payloads.get("codec"))
18429        .and_then(Value::as_str)
18430        .unwrap_or(&task.payload_codec)
18431        .to_string();
18432    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
18433
18434    for event in &mut task.history_events {
18435        if event.event_type == "ActivityCompleted" {
18436            let sequence = event
18437                .payload
18438                .get("sequence")
18439                .or_else(|| event.payload.get("workflow_sequence"))
18440                .and_then(value_as_u64);
18441            let Some(activity) = sequence.and_then(|sequence| {
18442                activities.iter().find(|activity| {
18443                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
18444                })
18445            }) else {
18446                continue;
18447            };
18448            let Some(payload) = event.payload.as_object_mut() else {
18449                continue;
18450            };
18451            if missing_payload(payload.get("result")) {
18452                if let Some(result) = activity
18453                    .get("result")
18454                    .filter(|value| !missing_payload(Some(value)))
18455                {
18456                    payload.insert("result".to_string(), result.clone());
18457                }
18458            }
18459            for field in ["payload_codec", "activity_type"] {
18460                if payload
18461                    .get(field)
18462                    .and_then(Value::as_str)
18463                    .unwrap_or_default()
18464                    .is_empty()
18465                {
18466                    if let Some(value) = activity.get(field) {
18467                        payload.insert(field.to_string(), value.clone());
18468                    }
18469                }
18470            }
18471            continue;
18472        }
18473
18474        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
18475            continue;
18476        }
18477        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18478        let command_id = event
18479            .payload
18480            .get("workflow_command_id")
18481            .or_else(|| event.raw.get("workflow_command_id"))
18482            .and_then(Value::as_str);
18483        let signal_name = event
18484            .payload
18485            .get("signal_name")
18486            .and_then(Value::as_str)
18487            .unwrap_or_default()
18488            .to_string();
18489        let matched = signals
18490            .iter()
18491            .find(|signal| {
18492                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
18493            })
18494            .or_else(|| {
18495                signals.iter().find(|signal| {
18496                    command_id.is_some()
18497                        && signal.get("command_id").and_then(Value::as_str) == command_id
18498                })
18499            })
18500            .or_else(|| {
18501                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
18502                let signal = signals
18503                    .iter()
18504                    .filter(|signal| {
18505                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
18506                    })
18507                    .nth(*offset);
18508                if signal.is_some() {
18509                    *offset += 1;
18510                }
18511                signal
18512            });
18513        let Some(signal) = matched else {
18514            continue;
18515        };
18516        let signal_codec = signal
18517            .get("payload_codec")
18518            .and_then(Value::as_str)
18519            .unwrap_or(&export_codec);
18520        let Some(payload) = event.payload.as_object_mut() else {
18521            continue;
18522        };
18523        if missing_payload(payload.get("arguments")) {
18524            if let Some(arguments) = signal
18525                .get("arguments")
18526                .filter(|value| !missing_payload(Some(value)))
18527            {
18528                let envelope = match arguments {
18529                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
18530                    other => other.clone(),
18531                };
18532                payload.insert("arguments".to_string(), envelope);
18533            }
18534        }
18535        if payload
18536            .get("payload_codec")
18537            .and_then(Value::as_str)
18538            .unwrap_or_default()
18539            .is_empty()
18540        {
18541            payload.insert("payload_codec".to_string(), json!(signal_codec));
18542        }
18543    }
18544
18545    Ok(())
18546}
18547
18548fn missing_payload(value: Option<&Value>) -> bool {
18549    match value {
18550        None | Some(Value::Null) => true,
18551        Some(Value::String(value)) => value.is_empty(),
18552        Some(_) => false,
18553    }
18554}
18555
18556fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
18557    history_signal_events(
18558        &task.history_events,
18559        task.history_export.as_ref(),
18560        &task.payload_codec,
18561    )
18562}
18563
18564fn history_signal_events(
18565    history_events: &[HistoryEvent],
18566    history_export: Option<&Value>,
18567    payload_codec: &str,
18568) -> Result<Vec<QuerySignal>> {
18569    let export_signals = history_export
18570        .and_then(|export| export.get("signals"))
18571        .and_then(Value::as_array)
18572        .cloned()
18573        .unwrap_or_default();
18574    let export_codec = history_export
18575        .and_then(|export| export.get("payloads"))
18576        .and_then(|payloads| payloads.get("codec"))
18577        .and_then(Value::as_str)
18578        .unwrap_or(payload_codec);
18579    let mut name_offsets: HashMap<String, usize> = HashMap::new();
18580    let mut signals: Vec<QuerySignal> = Vec::new();
18581    let mut signal_indices = HashMap::new();
18582    let mut command_indices = HashMap::new();
18583
18584    for event in history_events {
18585        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
18586            continue;
18587        }
18588
18589        let name = event
18590            .payload
18591            .get("signal_name")
18592            .and_then(Value::as_str)
18593            .unwrap_or_default();
18594        if name.is_empty() {
18595            continue;
18596        }
18597        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18598        let command_id = event
18599            .payload
18600            .get("workflow_command_id")
18601            .or_else(|| event.raw.get("workflow_command_id"))
18602            .and_then(Value::as_str);
18603        let matched_export = export_signals
18604            .iter()
18605            .find(|candidate| {
18606                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
18607            })
18608            .or_else(|| {
18609                export_signals.iter().find(|candidate| {
18610                    command_id.is_some()
18611                        && candidate.get("command_id").and_then(Value::as_str) == command_id
18612                })
18613            })
18614            .or_else(|| {
18615                let offset = name_offsets.entry(name.to_string()).or_default();
18616                let candidate = export_signals
18617                    .iter()
18618                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
18619                    .nth(*offset);
18620                if candidate.is_some() {
18621                    *offset += 1;
18622                }
18623                candidate
18624            });
18625        let codec = event
18626            .payload
18627            .get("payload_codec")
18628            .and_then(Value::as_str)
18629            .or_else(|| {
18630                matched_export
18631                    .and_then(|signal| signal.get("payload_codec"))
18632                    .and_then(Value::as_str)
18633            })
18634            .unwrap_or(export_codec);
18635        let raw_arguments = signal_history_payload(&event.payload)
18636            .filter(|value| !value.is_null())
18637            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
18638        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18639        let workflow_sequence = event
18640            .payload
18641            .get("workflow_sequence")
18642            .and_then(value_as_u64)
18643            .or_else(|| {
18644                matched_export
18645                    .and_then(|signal| signal.get("workflow_sequence"))
18646                    .and_then(value_as_u64)
18647            });
18648
18649        let id = signal_id.or_else(|| {
18650            matched_export
18651                .and_then(|signal| signal.get("id"))
18652                .and_then(Value::as_str)
18653        });
18654        let command_id = command_id.or_else(|| {
18655            matched_export
18656                .and_then(|signal| signal.get("command_id"))
18657                .and_then(Value::as_str)
18658        });
18659        let duplicate = id
18660            .and_then(|id| signal_indices.get(id))
18661            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18662            .copied();
18663        let index = duplicate.unwrap_or(signals.len());
18664        if let Some(index) = duplicate {
18665            let original = &mut signals[index];
18666            let same_arguments = if event.event_type == "SignalApplied" {
18667                if let Some(value) = event.payload.get("value") {
18668                    let expected = match original.avro_arguments.as_slice() {
18669                        [] => AvroValue::Boolean(true),
18670                        [value] => value.clone(),
18671                        values => AvroValue::Array(values.to_vec()),
18672                    };
18673                    let applied = decode_wire_avro_value(value, codec)?;
18674                    applied == expected
18675                        || applied == AvroValue::Array(original.avro_arguments.clone())
18676                } else {
18677                    original.avro_arguments == avro_arguments
18678                }
18679            } else {
18680                original.avro_arguments == avro_arguments
18681            };
18682            if original.name != name
18683                || !same_arguments
18684                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18685            {
18686                return Err(Error::Codec("conflicting committed signal identity".into()));
18687            }
18688            if original.id.is_none() {
18689                original.id = id.map(str::to_string);
18690            }
18691            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18692        } else {
18693            signals.push(QuerySignal {
18694                id: id.map(str::to_string),
18695                name: name.to_string(),
18696                arguments,
18697                avro_arguments,
18698                workflow_sequence,
18699            });
18700        }
18701        if let Some(id) = id {
18702            signal_indices.insert(id.to_string(), index);
18703        }
18704        if let Some(id) = command_id {
18705            command_indices.insert(id.to_string(), index);
18706        }
18707    }
18708
18709    if signals.is_empty() {
18710        for signal in export_signals {
18711            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18712                continue;
18713            }
18714            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18715                continue;
18716            };
18717            let codec = signal
18718                .get("payload_codec")
18719                .and_then(Value::as_str)
18720                .unwrap_or(export_codec);
18721            let (arguments, avro_arguments) =
18722                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18723            signals.push(QuerySignal {
18724                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18725                name: name.to_string(),
18726                arguments,
18727                avro_arguments,
18728                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18729            });
18730        }
18731        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18732    }
18733
18734    Ok(signals)
18735}
18736
18737fn decode_query_signal_arguments(
18738    raw: Option<&Value>,
18739    codec: &str,
18740) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18741    validate_payload_codec(codec)?;
18742    let decoded = match raw.filter(|value| !value.is_null()) {
18743        Some(value) => decode_wire_avro_value(value, codec)?,
18744        None => AvroValue::Array(Vec::new()),
18745    };
18746    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18747        unreachable!("normalize_avro_arguments always returns an array");
18748    };
18749    let arguments = avro_arguments
18750        .iter()
18751        .cloned()
18752        .map(AvroValue::into_json)
18753        .collect::<Result<Vec<_>>>()?;
18754    Ok((arguments, avro_arguments))
18755}
18756
18757fn value_as_u64(value: &Value) -> Option<u64> {
18758    value
18759        .as_u64()
18760        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18761}
18762
18763#[cfg(test)]
18764mod tests {
18765    use super::*;
18766    #[cfg(feature = "telemetry")]
18767    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
18768        tokio::sync::Mutex::const_new(());
18769    mod activity_cancellation_policies;
18770    mod activity_lease_worker;
18771    mod cancellation_scope_admission;
18772    mod cancellation_scope_authoring;
18773    mod cancellation_scope_history;
18774    mod cancellation_scope_opening;
18775    mod cancellation_scope_replay;
18776    mod child_workflow_policies;
18777    mod cooperative_cancellation;
18778    mod local_activity;
18779    mod nexus;
18780    mod runtime_payloads;
18781    mod runtime_uploads;
18782    mod version_marker_contract;
18783    mod worker_session;
18784    use std::{
18785        fs,
18786        io::{Read, Write},
18787        net::{SocketAddr, TcpListener, TcpStream},
18788        process::Command as ProcessCommand,
18789        sync::atomic::AtomicUsize,
18790        thread,
18791    };
18792
18793    #[derive(Clone, Copy, Debug)]
18794    enum InvalidTaskPayloadCodec {
18795        Missing,
18796        Null,
18797        NonString,
18798    }
18799
18800    impl InvalidTaskPayloadCodec {
18801        fn label(self) -> &'static str {
18802            match self {
18803                Self::Missing => "missing",
18804                Self::Null => "null",
18805                Self::NonString => "non-string",
18806            }
18807        }
18808
18809        fn apply(self, task: &mut Value) {
18810            let task = task.as_object_mut().expect("task fixture object");
18811            match self {
18812                Self::Missing => {
18813                    task.remove("payload_codec");
18814                }
18815                Self::Null => {
18816                    task.insert("payload_codec".to_string(), Value::Null);
18817                }
18818                Self::NonString => {
18819                    task.insert("payload_codec".to_string(), json!(42));
18820                }
18821            }
18822        }
18823    }
18824
18825    fn fixture_envelope(value: Value) -> Value {
18826        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18827    }
18828
18829    fn fixture_blob(value: Value) -> String {
18830        encode_payload(&value, DEFAULT_CODEC)
18831            .expect("encode Avro test fixture")
18832            .blob
18833    }
18834
18835    #[test]
18836    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18837        for base_url in [
18838            "http://127.0.0.1:8080/api",
18839            "http://localhost:8080/api/",
18840            "https://runtime.example.test/namespaces/orders/api",
18841        ] {
18842            let error = Client::builder(base_url)
18843                .build()
18844                .expect_err("SDK-owned /api suffix must be rejected during build");
18845
18846            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18847            assert!(
18848                error.to_string().contains("SDK appends /api automatically"),
18849                "the validation error must explain how to fix the endpoint"
18850            );
18851        }
18852    }
18853
18854    #[test]
18855    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18856        for (base_url, expected) in [
18857            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18858            (
18859                "http://localhost:8080/durable-workflow/",
18860                "http://localhost:8080/durable-workflow",
18861            ),
18862            (
18863                "https://runtime.example.test/namespaces/orders",
18864                "https://runtime.example.test/namespaces/orders",
18865            ),
18866            (
18867                "https://runtime.example.test/gateway/api/namespaces/orders",
18868                "https://runtime.example.test/gateway/api/namespaces/orders",
18869            ),
18870            (
18871                "https://api.example.test/runtime/orders/",
18872                "https://api.example.test/runtime/orders",
18873            ),
18874        ] {
18875            let client = Client::builder(base_url)
18876                .build()
18877                .expect("Server and Cloud runtime base URL must remain valid");
18878
18879            assert_eq!(client.base_url, expected);
18880        }
18881    }
18882
18883    #[test]
18884    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18885        assert_eq!(
18886            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18887            MINIMUM_WORKER_PROTOCOL_VERSION
18888        );
18889        assert_eq!(
18890            workflow_completion_protocol_version(&[json!({
18891                "type": "upsert_search_attributes",
18892                "attributes": {"OrderStatus": "waiting"},
18893            })]),
18894            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18895        );
18896        assert_eq!(
18897            workflow_completion_protocol_version(&[json!({
18898                "type": "upsert_search_attributes",
18899                "attributes": {"OrderStatus": "waiting"},
18900                "attribute_types": {"OrderStatus": "keyword"},
18901            })]),
18902            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18903        );
18904        assert_eq!(
18905            workflow_completion_protocol_version(&[
18906                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18907                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18908            ]),
18909            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18910        );
18911        assert_eq!(
18912            workflow_completion_protocol_version(&[
18913                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18914                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18915            ]),
18916            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18917        );
18918        assert_eq!(
18919            workflow_completion_protocol_version(&[json!({
18920                "type": "open_condition_wait",
18921                "condition_wait_occurrence_id": "rust:condition-wait:0",
18922                "condition_key": "ready",
18923            })]),
18924            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18925        );
18926        assert_eq!(
18927            workflow_completion_protocol_version_with_message_streams(
18928                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18929                true,
18930            ),
18931            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18932        );
18933        assert_eq!(
18934            workflow_completion_protocol_version_with_message_streams(
18935                &[json!({
18936                    "type": "open_condition_wait",
18937                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18938                    "condition_key": "ready",
18939                })],
18940                true,
18941            ),
18942            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18943        );
18944    }
18945
18946    #[test]
18947    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18948        let manifest = portable_worker_affinity_capability_manifest();
18949
18950        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18951            assert_eq!(manifest[capability]["supported"], json!(false));
18952            assert_eq!(
18953                manifest[capability]["minimum_protocol_version"],
18954                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18955            );
18956            assert!(manifest[capability]["reason"]
18957                .as_str()
18958                .is_some_and(|reason| !reason.is_empty()));
18959        }
18960    }
18961
18962    fn typed_fidelity_probe() -> AvroValue {
18963        AvroValue::Map(BTreeMap::from([
18964            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18965            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18966            (
18967                "numeric".to_string(),
18968                AvroValue::Map(BTreeMap::from([
18969                    ("0".to_string(), AvroValue::String("zero".to_string())),
18970                    ("1".to_string(), AvroValue::String("one".to_string())),
18971                ])),
18972            ),
18973            (
18974                "nested".to_string(),
18975                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18976                    "enabled".to_string(),
18977                    AvroValue::Boolean(true),
18978                )]))]),
18979            ),
18980            (
18981                "projection_collisions".to_string(),
18982                AvroValue::Array(projection_collision_probe()),
18983            ),
18984        ]))
18985    }
18986
18987    fn projection_collision_probe() -> Vec<AvroValue> {
18988        vec![
18989            AvroValue::Map(BTreeMap::from([
18990                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18991                (
18992                    "base64".to_string(),
18993                    AvroValue::String("ordinary user text".to_string()),
18994                ),
18995            ])),
18996            AvroValue::Map(BTreeMap::from([
18997                ("$type".to_string(), AvroValue::String("map".to_string())),
18998                (
18999                    "entries".to_string(),
19000                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
19001                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
19002                        (
19003                            "value".to_string(),
19004                            AvroValue::String("user map".to_string()),
19005                        ),
19006                    ]))]),
19007                ),
19008            ])),
19009        ]
19010    }
19011
19012    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19013    struct TypedContract {
19014        nested: TypedNested,
19015        mode: TypedMode,
19016        optional: Option<String>,
19017        absent: Option<String>,
19018        items: Vec<i64>,
19019        labels: BTreeMap<String, String>,
19020        bytes: serde_bytes::ByteBuf,
19021        signed: i64,
19022        finite: f64,
19023    }
19024
19025    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19026    struct TypedNested {
19027        enabled: bool,
19028    }
19029
19030    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19031    enum TypedMode {
19032        Detailed { label: String },
19033    }
19034
19035    fn typed_contract() -> TypedContract {
19036        TypedContract {
19037            nested: TypedNested { enabled: true },
19038            mode: TypedMode::Detailed {
19039                label: "compiler-checked".to_string(),
19040            },
19041            optional: Some("present".to_string()),
19042            absent: None,
19043            items: vec![i64::MIN, 0, i64::MAX],
19044            labels: BTreeMap::from([
19045                ("language".to_string(), "rust".to_string()),
19046                ("wire".to_string(), "avro".to_string()),
19047            ]),
19048            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
19049            signed: -9_223_372_036_854_775_000,
19050            finite: 12.5,
19051        }
19052    }
19053
19054    #[derive(Clone, Debug, Default, PartialEq)]
19055    struct ReplayCounterState {
19056        loaded: Option<String>,
19057        count: i64,
19058        finished: bool,
19059    }
19060
19061    fn replay_counter_worker() -> Worker {
19062        let client = Client::new("http://127.0.0.1:8080").expect("client");
19063        let mut worker = Worker::new(client, "rust-workers");
19064        worker.register_replayed_workflow(
19065            "replay-counter",
19066            ReplayCounterState::default,
19067            |ctx, _input, state| async move {
19068                let loaded = ctx.activity("load-counter", json!([])).await?;
19069                state.update(|current| {
19070                    current.loaded = loaded.as_str().map(str::to_string);
19071                })?;
19072                for _ in 0..2 {
19073                    let signal = ctx.wait_signal("increment").await?;
19074                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
19075                    state.update(|current| current.count += amount)?;
19076                }
19077                state.update(|current| current.finished = true)?;
19078                state.read(|current| Ok(json!(current.count)))?
19079            },
19080        );
19081        worker.register_replayed_query::<ReplayCounterState, _, _>(
19082            "replay-counter",
19083            "current",
19084            |_ctx, state, _args| async move {
19085                Ok(json!({
19086                    "loaded": state.loaded,
19087                    "count": state.count,
19088                    "finished": state.finished,
19089                }))
19090            },
19091        );
19092        worker.register_replayed_query::<ReplayCounterState, _, _>(
19093            "replay-counter",
19094            "detached-mutation",
19095            |_ctx, state, _args| async move {
19096                let mut detached = (*state).clone();
19097                detached.count = 999;
19098                Ok(json!(detached.count))
19099            },
19100        );
19101        worker.register_replayed_query::<ReplayCounterState, _, _>(
19102            "replay-counter",
19103            "failed-mutation",
19104            |_ctx, state, _args| async move {
19105                let mut detached = (*state).clone();
19106                detached.count = 999;
19107                Err(Error::WorkerLoop("query refused".to_string()))
19108            },
19109        );
19110        worker
19111    }
19112
19113    fn replay_counter_query(
19114        query_name: &str,
19115        history_events: Value,
19116        run_status: &str,
19117    ) -> QueryTask {
19118        let arguments = fixture_envelope(json!([]));
19119        serde_json::from_value(json!({
19120            "query_task_id": format!("query-{query_name}"),
19121            "workflow_type": "replay-counter",
19122            "query_name": query_name,
19123            "payload_codec": DEFAULT_CODEC,
19124            "workflow_arguments": arguments.clone(),
19125            "query_arguments": arguments,
19126            "history_events": history_events,
19127            "run_status": run_status,
19128        }))
19129        .expect("query task")
19130    }
19131
19132    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
19133        workflow_context_with_codec(history, DEFAULT_CODEC)
19134    }
19135
19136    fn workflow_context_with_codec(
19137        history: Vec<HistoryEvent>,
19138        payload_codec: &str,
19139    ) -> WorkflowContext {
19140        WorkflowContext {
19141            cancellation_scope_id: "root".into(),
19142            state: Arc::new(Mutex::new(
19143                WorkflowState::new_with_identity(
19144                    history,
19145                    None,
19146                    None,
19147                    "rust-workers".to_string(),
19148                    payload_codec.to_string(),
19149                    None,
19150                )
19151                .expect("valid workflow history"),
19152            )),
19153        }
19154    }
19155
19156    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
19157        HistoryEvent {
19158            event_type: event_type.to_string(),
19159            payload,
19160            raw: HashMap::new(),
19161        }
19162    }
19163
19164    fn parallel_path_entry(
19165        kind: &str,
19166        base: u64,
19167        size: usize,
19168        index: usize,
19169    ) -> ParallelGroupMetadata {
19170        parallel_group_entry(base, size, index, kind)
19171    }
19172
19173    fn parallel_history_event(
19174        event_type: &str,
19175        sequence: u64,
19176        identity_field: &str,
19177        identity: &str,
19178        path: Vec<ParallelGroupMetadata>,
19179        result: Option<Value>,
19180    ) -> HistoryEvent {
19181        let mut payload = serde_json::Map::from_iter([
19182            ("sequence".to_string(), json!(sequence)),
19183            (identity_field.to_string(), json!(identity)),
19184        ]);
19185        let inner = path.last().expect("parallel history path");
19186        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
19187        payload.insert("parallel_group_path".to_string(), json!(path));
19188        if let Some(result) = result {
19189            let field = if event_type == "ChildRunCompleted" {
19190                "result"
19191            } else {
19192                "result"
19193            };
19194            payload.insert(field.to_string(), fixture_envelope(result));
19195            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
19196        }
19197        history_event(event_type, Value::Object(payload))
19198    }
19199
19200    fn nested_parallel_operations() -> Vec<ParallelOperation> {
19201        vec![
19202            ParallelOperation::activity("first", json!([])),
19203            ParallelOperation::group(vec![
19204                ParallelOperation::child_workflow(
19205                    "second",
19206                    ChildWorkflowOptions::new("child-workers"),
19207                    json!([]),
19208                ),
19209                ParallelOperation::activity("third", json!([])),
19210            ]),
19211        ]
19212    }
19213
19214    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
19215        let outer = [
19216            parallel_path_entry("mixed", 1, 3, 0),
19217            parallel_path_entry("mixed", 1, 3, 1),
19218            parallel_path_entry("mixed", 1, 3, 2),
19219        ];
19220        [
19221            vec![outer[0].clone()],
19222            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
19223            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
19224        ]
19225    }
19226
19227    #[test]
19228    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
19229        let ctx = workflow_context(Vec::new());
19230        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19231        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19232
19233        assert!(matches!(
19234            call.as_mut().poll(&mut task_context),
19235            Poll::Pending
19236        ));
19237        let commands = ctx.take_commands().expect("parallel commands");
19238        assert_eq!(
19239            commands
19240                .iter()
19241                .map(|command| command["type"].as_str().unwrap_or_default())
19242                .collect::<Vec<_>>(),
19243            [
19244                "schedule_activity",
19245                "start_child_workflow",
19246                "schedule_activity"
19247            ]
19248        );
19249        let paths = nested_parallel_paths();
19250        for (command, path) in commands.iter().zip(paths) {
19251            assert_eq!(command["parallel_group_path"], json!(path));
19252            assert_eq!(
19253                command["parallel_group_id"],
19254                json!(path.last().expect("inner group").parallel_group_id)
19255            );
19256        }
19257    }
19258
19259    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
19260        let paths = nested_parallel_paths();
19261        let third = parallel_history_event(
19262            "ActivityCompleted",
19263            3,
19264            "activity_type",
19265            "third",
19266            paths[2].clone(),
19267            Some(json!("three")),
19268        );
19269        vec![
19270            parallel_history_event(
19271                "ActivityCompleted",
19272                1,
19273                "activity_type",
19274                "first",
19275                paths[0].clone(),
19276                Some(json!("one")),
19277            ),
19278            parallel_history_event(
19279                "ChildWorkflowScheduled",
19280                2,
19281                "child_workflow_type",
19282                "second",
19283                paths[1].clone(),
19284                None,
19285            ),
19286            parallel_history_event(
19287                "ChildRunCompleted",
19288                2,
19289                "child_workflow_type",
19290                "second",
19291                paths[1].clone(),
19292                Some(json!("two")),
19293            ),
19294            third.clone(),
19295            third,
19296        ]
19297    }
19298
19299    #[test]
19300    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
19301        for _restart_or_completed_replay in 0..2 {
19302            let ctx = workflow_context(completed_nested_parallel_history());
19303            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19304            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19305            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
19306                panic!("completed nested parallel history must replay");
19307            };
19308            assert_eq!(
19309                results,
19310                vec![
19311                    ParallelResult::Activity(json!("one")),
19312                    ParallelResult::Group(vec![
19313                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
19314                            parent: WorkflowIdentity {
19315                                workflow_id: None,
19316                                run_id: None,
19317                            },
19318                            child: WorkflowIdentity {
19319                                workflow_id: None,
19320                                run_id: None,
19321                            },
19322                            child_workflow_type: Some("second".to_string()),
19323                            result: json!("two"),
19324                        }),
19325                        ParallelResult::Activity(json!("three")),
19326                    ]),
19327                ]
19328            );
19329            assert!(ctx.take_commands().expect("commands").is_empty());
19330            ctx.ensure_history_consumed().expect("history consumed");
19331        }
19332    }
19333
19334    #[test]
19335    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
19336        let paths = nested_parallel_paths();
19337        let history = vec![
19338            parallel_history_event(
19339                "ActivityCompleted",
19340                1,
19341                "activity_type",
19342                "first",
19343                paths[0].clone(),
19344                Some(json!("one")),
19345            ),
19346            parallel_history_event(
19347                "ChildWorkflowScheduled",
19348                2,
19349                "child_workflow_type",
19350                "second",
19351                paths[1].clone(),
19352                None,
19353            ),
19354            parallel_history_event(
19355                "ChildRunFailed",
19356                2,
19357                "child_workflow_type",
19358                "second",
19359                paths[1].clone(),
19360                None,
19361            ),
19362            parallel_history_event(
19363                "ActivityCompleted",
19364                3,
19365                "activity_type",
19366                "third",
19367                paths[2].clone(),
19368                Some(json!("late")),
19369            ),
19370        ];
19371        let ctx = workflow_context(history);
19372        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19373        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19374        let outcome = call.as_mut().poll(&mut task_context);
19375        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
19376            panic!("one failed child must return a typed partial failure: {outcome:?}");
19377        };
19378        assert_eq!(failure.member_path, [1, 0]);
19379        assert_eq!(failure.group_id, "parallel-calls:1:3");
19380        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
19381        assert_eq!(
19382            failure
19383                .completed
19384                .iter()
19385                .map(|completion| completion.member_path.clone())
19386                .collect::<Vec<_>>(),
19387            [vec![0], vec![1, 1]]
19388        );
19389    }
19390
19391    #[test]
19392    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
19393        let paths = nested_parallel_paths();
19394        let history = vec![
19395            parallel_history_event(
19396                "ActivityScheduled",
19397                1,
19398                "activity_type",
19399                "first",
19400                paths[0].clone(),
19401                None,
19402            ),
19403            parallel_history_event(
19404                "ChildWorkflowScheduled",
19405                2,
19406                "child_workflow_type",
19407                "second",
19408                paths[1].clone(),
19409                None,
19410            ),
19411            parallel_history_event(
19412                "ActivityScheduled",
19413                3,
19414                "activity_type",
19415                "third",
19416                paths[2].clone(),
19417                None,
19418            ),
19419        ];
19420        for _restart in 0..2 {
19421            let ctx = workflow_context(history.clone());
19422            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19423            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19424            let outcome = call.as_mut().poll(&mut task_context);
19425            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
19426            assert!(ctx.take_commands().expect("commands").is_empty());
19427        }
19428    }
19429
19430    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
19431        vec![selection_group_entry(
19432            1,
19433            2,
19434            index,
19435            "activity",
19436            &SelectionMemberMetadata {
19437                key: SelectionKey::Name(key.to_string()),
19438                index,
19439                base_sequence: index as u64 + 1,
19440                size: 1,
19441                kind: "activity".to_string(),
19442            },
19443        )]
19444    }
19445
19446    fn selection_activity_event(
19447        event_type: &str,
19448        index: usize,
19449        key: &str,
19450        result: Option<Value>,
19451    ) -> HistoryEvent {
19452        let sequence = index as u64 + 1;
19453        let mut event = parallel_history_event(
19454            event_type,
19455            sequence,
19456            "activity_type",
19457            &format!("{key}-activity"),
19458            selection_path(index, key),
19459            result,
19460        );
19461        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
19462        event.raw.insert(
19463            "id".to_string(),
19464            json!(if event_type == "ActivityCompleted" {
19465                format!("event-{key}")
19466            } else {
19467                format!("{event_type}-{key}")
19468            }),
19469        );
19470        event
19471    }
19472
19473    fn selection_winner_marker() -> HistoryEvent {
19474        history_event(
19475            "SelectionResolved",
19476            json!({
19477                "selection_group_id": "select-calls:1:2",
19478                "selection_group_base_sequence": 1,
19479                "selection_group_size": 2,
19480                "member_key": "fast",
19481                "member_index": 1,
19482                "member_base_sequence": 2,
19483                "member_size": 1,
19484                "operation_kind": "activity",
19485                "operation_identity": "activity-fast",
19486                "outcome": "completed",
19487                "resolution_event_id": "event-fast",
19488                "resolution_event_type": "ActivityCompleted",
19489            }),
19490        )
19491    }
19492
19493    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
19494        ctx.select_keyed(vec![
19495            (
19496                "slow",
19497                ParallelOperation::activity_with_options(
19498                    "slow-activity",
19499                    ActivityOptions::new().task_queue("default"),
19500                    json!([]),
19501                ),
19502            ),
19503            (
19504                "fast",
19505                ParallelOperation::activity_with_options(
19506                    "fast-activity",
19507                    ActivityOptions::new().task_queue("default"),
19508                    json!([]),
19509                ),
19510            ),
19511        ])
19512    }
19513
19514    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
19515        let ctx = workflow_context(history);
19516        let mut call = Box::pin(keyed_activity_selection(&ctx));
19517        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19518        let selected = match call.as_mut().poll(&mut task_context) {
19519            Poll::Ready(Ok(selected)) => selected,
19520            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
19521            Poll::Pending => panic!("persisted selection winner must replay without pending"),
19522        };
19523        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
19524        assert_eq!(
19525            selected.value,
19526            Some(ParallelResult::Activity(json!("winner-value")))
19527        );
19528        let slow = selected
19529            .handle(&SelectionKey::Name("slow".to_string()))
19530            .expect("slow handle")
19531            .clone();
19532        let mut await_slow = Box::pin(slow.await_result());
19533        assert!(matches!(
19534            await_slow.as_mut().poll(&mut task_context),
19535            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
19536        ));
19537        assert!(ctx.take_commands().expect("commands").is_empty());
19538    }
19539
19540    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
19541
19542    fn canonical_selection_history() -> Vec<HistoryEvent> {
19543        const FIXTURE: &[u8] =
19544            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
19545        assert_eq!(
19546            format!("{:x}", Sha256::digest(FIXTURE)),
19547            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19548        );
19549        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
19550
19551        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
19552    }
19553
19554    #[test]
19555    fn selection_fresh_process_entrypoint() {
19556        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
19557            return;
19558        };
19559        let persisted = fs::read(path).expect("persisted selection history");
19560        assert_eq!(
19561            format!("{:x}", Sha256::digest(&persisted)),
19562            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19563        );
19564        let fixture: Value =
19565            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
19566        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
19567            .expect("valid persisted selection history");
19568
19569        assert_persisted_selection_replay(history);
19570    }
19571
19572    #[test]
19573    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
19574        let ctx = workflow_context(Vec::new());
19575        let mut call = Box::pin(keyed_activity_selection(&ctx));
19576        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19577
19578        assert!(matches!(
19579            call.as_mut().poll(&mut task_context),
19580            Poll::Pending
19581        ));
19582        let commands = ctx.take_commands().expect("selection commands");
19583        assert_eq!(commands.len(), 2);
19584        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
19585        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
19586        assert!(commands.iter().all(|command| {
19587            command["parallel_group_id"] == json!("select-calls:1:2")
19588                && command["parallel_group_mode"] == json!("select")
19589        }));
19590    }
19591
19592    #[test]
19593    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
19594        let ctx = workflow_context(Vec::new());
19595        let mut invalid = Box::pin(ctx.select_keyed(vec![(
19596            "",
19597            ParallelOperation::activity("invalid", json!([])),
19598        )]));
19599        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19600        assert!(matches!(
19601            invalid.as_mut().poll(&mut task_context),
19602            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
19603                reason: "selection_key_invalid",
19604                ..
19605            })))
19606        ));
19607
19608        for invalid_key in [json!(""), json!(-1)] {
19609            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
19610            event.payload["selection_member_key"] = invalid_key.clone();
19611            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
19612            assert!(matches!(
19613                WorkflowState::new_with_identity(
19614                    vec![event],
19615                    None,
19616                    None,
19617                    "rust-workers".to_string(),
19618                    DEFAULT_CODEC.to_string(),
19619                    None,
19620                ),
19621                Err(Error::NonDeterministicReplay(_))
19622            ));
19623        }
19624    }
19625
19626    #[test]
19627    fn selection_preserves_valid_named_and_numeric_keys() {
19628        let ctx = workflow_context(Vec::new());
19629        let mut selection = Box::pin(ctx.select_keyed(vec![
19630            (
19631                SelectionKey::Index(0),
19632                ParallelOperation::activity("numeric", json!([])),
19633            ),
19634            (
19635                SelectionKey::Name("named".to_string()),
19636                ParallelOperation::timer(Duration::from_secs(1)),
19637            ),
19638        ]));
19639        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19640
19641        assert!(matches!(
19642            selection.as_mut().poll(&mut task_context),
19643            Poll::Pending
19644        ));
19645        let commands = ctx.take_commands().expect("selection commands");
19646        assert_eq!(commands[0]["selection_member_key"], json!(0));
19647        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19648    }
19649
19650    #[test]
19651    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19652        let history = canonical_selection_history();
19653        assert_persisted_selection_replay(history.clone());
19654
19655        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19656            .join("tests/fixtures/durable_selection_runtime_history.json");
19657        let output =
19658            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19659                .args([
19660                    "--exact",
19661                    "tests::selection_fresh_process_entrypoint",
19662                    "--nocapture",
19663                ])
19664                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19665                .output()
19666                .expect("run fresh selection replay process");
19667
19668        assert!(
19669            output.status.success(),
19670            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19671            String::from_utf8_lossy(&output.stdout),
19672            String::from_utf8_lossy(&output.stderr),
19673        );
19674    }
19675
19676    #[test]
19677    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19678        let mut history = canonical_selection_history();
19679        history.retain(|event| event.event_type != "SelectionResolved");
19680        let ctx = workflow_context(history);
19681        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19682        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19683
19684        assert!(matches!(
19685            selection.as_mut().poll(&mut task_context),
19686            Poll::Pending
19687        ));
19688        assert!(ctx.take_commands().expect("commands").is_empty());
19689        assert!(
19690            ctx.matched_recorded_pending()
19691                .expect("selection pending state"),
19692            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19693        );
19694    }
19695
19696    #[test]
19697    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19698        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19699            ("ConditionWaitSatisfied", true, None),
19700            ("ConditionWaitTimedOut", false, Some(0)),
19701        ] {
19702            let member = SelectionMemberMetadata {
19703                key: SelectionKey::Name("condition".to_string()),
19704                index: 0,
19705                base_sequence: 1,
19706                size: 1,
19707                kind: "condition".to_string(),
19708            };
19709            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19710            let mut payload = json!({
19711                "sequence": 1,
19712                "condition_wait_id": "condition-1",
19713                "condition_wait_occurrence_id": "rust:condition-wait:0",
19714                "condition_key": "ready",
19715                "condition_definition_fingerprint": "sha256:ready-v1",
19716                "parallel_group_path": path,
19717            });
19718            payload
19719                .as_object_mut()
19720                .expect("condition history payload")
19721                .extend(
19722                    serde_json::to_value(&path[0])
19723                        .expect("condition selection metadata")
19724                        .as_object()
19725                        .expect("condition selection metadata object")
19726                        .clone(),
19727                );
19728            if let Some(timeout_seconds) = timeout_seconds {
19729                payload["timeout_seconds"] = json!(timeout_seconds);
19730            }
19731            let history = vec![
19732                history_event("ConditionWaitOpened", payload.clone()),
19733                history_event(terminal_event, payload),
19734            ];
19735            let ctx = workflow_context(history);
19736            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19737            if timeout_seconds.is_some() {
19738                options = options.timeout(Duration::ZERO);
19739            }
19740            let mut selection = Box::pin(ctx.select_keyed(vec![(
19741                "condition",
19742                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19743            )]));
19744            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19745
19746            assert!(matches!(
19747                selection.as_mut().poll(&mut task_context),
19748                Poll::Pending
19749            ));
19750            assert!(ctx.take_commands().expect("commands").is_empty());
19751            assert!(
19752                ctx.matched_recorded_pending()
19753                    .expect("condition selection pending state"),
19754                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19755            );
19756        }
19757    }
19758
19759    #[test]
19760    fn selection_immediate_condition_members_open_a_durable_wait() {
19761        for predicate_satisfied in [true, false] {
19762            let ctx = workflow_context(Vec::new());
19763            let mut selection = Box::pin(ctx.select_keyed(vec![(
19764                "condition",
19765                ParallelOperation::condition(
19766                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19767                    move || Ok(predicate_satisfied),
19768                ),
19769            )]));
19770            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19771
19772            assert!(matches!(
19773                selection.as_mut().poll(&mut task_context),
19774                Poll::Pending
19775            ));
19776            let commands = ctx.take_commands().expect("condition selection command");
19777            assert_eq!(commands.len(), 1);
19778            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19779            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19780            assert_eq!(
19781                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19782                json!("select")
19783            );
19784        }
19785    }
19786
19787    #[test]
19788    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19789        let history = vec![
19790            selection_activity_event("ActivityScheduled", 0, "slow", None),
19791            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19792            selection_winner_marker(),
19793        ];
19794        let ctx = workflow_context(history.clone());
19795        let mut call = Box::pin(keyed_activity_selection(&ctx));
19796        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19797        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19798            panic!("winner must replay");
19799        };
19800        let slow = selected
19801            .handle(&SelectionKey::Name("slow".to_string()))
19802            .expect("slow handle")
19803            .clone();
19804        let mut cancel = Box::pin(slow.cancel());
19805        assert!(matches!(
19806            cancel.as_mut().poll(&mut task_context),
19807            Poll::Ready(Ok(()))
19808        ));
19809        assert!(matches!(
19810            cancel.as_mut().poll(&mut task_context),
19811            Poll::Ready(Ok(()))
19812        ));
19813        let mut outcome = Box::pin(slow.await_result());
19814        assert!(matches!(
19815            outcome.as_mut().poll(&mut task_context),
19816            Poll::Pending
19817        ));
19818        let commands = ctx.take_commands().expect("cancel command");
19819        assert_eq!(commands.len(), 1);
19820        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19821        assert_eq!(commands[0]["member_key"], json!("slow"));
19822
19823        let mut cancelled_history = history;
19824        cancelled_history.push(history_event(
19825            "SelectionOperationCancelled",
19826            json!({
19827                "selection_group_id": "select-calls:1:2",
19828                "member_key": "slow",
19829                "member_index": 0,
19830                "member_base_sequence": 1,
19831                "member_size": 1,
19832                "operation_kind": "activity",
19833                "operation_identity": "activity-slow",
19834                "cancelled_at": "2026-08-27T00:00:00Z",
19835            }),
19836        ));
19837        let replayed = workflow_context(cancelled_history);
19838        let mut call = Box::pin(keyed_activity_selection(&replayed));
19839        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19840            panic!("winner must replay after cancellation");
19841        };
19842        let slow = selected
19843            .handle(&SelectionKey::Name("slow".to_string()))
19844            .expect("slow handle")
19845            .clone();
19846        let mut cancel = Box::pin(slow.cancel());
19847        assert!(matches!(
19848            cancel.as_mut().poll(&mut task_context),
19849            Poll::Ready(Ok(()))
19850        ));
19851        assert!(replayed.take_commands().expect("commands").is_empty());
19852    }
19853
19854    #[test]
19855    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19856        let base_history = vec![
19857            selection_activity_event("ActivityScheduled", 0, "slow", None),
19858            selection_activity_event("ActivityScheduled", 1, "fast", None),
19859            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19860            selection_winner_marker(),
19861        ];
19862        for (field, corrupt) in [
19863            ("member_key", json!("fast")),
19864            ("member_index", json!(1)),
19865            ("member_base_sequence", json!(3)),
19866            ("member_size", json!(2)),
19867            ("operation_kind", json!("timer")),
19868            ("operation_identity", json!("forged")),
19869        ] {
19870            let mut cancellation = json!({
19871                "selection_group_id": "select-calls:1:2",
19872                "member_key": "slow",
19873                "member_index": 0,
19874                "member_base_sequence": 1,
19875                "member_size": 1,
19876                "operation_kind": "activity",
19877                "operation_identity": "activity-slow",
19878            });
19879            cancellation[field] = corrupt;
19880            let mut history = base_history.clone();
19881            history.push(history_event("SelectionOperationCancelled", cancellation));
19882            let ctx = workflow_context(history);
19883            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19884            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19885
19886            assert!(matches!(
19887                selection.as_mut().poll(&mut task_context),
19888                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19889            ));
19890        }
19891    }
19892
19893    #[test]
19894    fn selection_child_identity_prefers_the_durable_run_id() {
19895        let ctx = workflow_context(vec![history_event(
19896            "ChildWorkflowScheduled",
19897            json!({
19898                "sequence": 1,
19899                "child_workflow_type": "child",
19900                "child_workflow_instance_id": "child-instance",
19901                "child_workflow_run_id": "child-run",
19902            }),
19903        )]);
19904        let state = ctx.state.lock().expect("workflow state");
19905
19906        assert_eq!(
19907            selection_operation_identity(&state, "child", 1, 1),
19908            "child-run"
19909        );
19910    }
19911
19912    #[test]
19913    fn selection_activity_identity_requires_canonical_execution_id() {
19914        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19915        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19916        let mut fast_completed =
19917            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19918        for event in [&mut fast_open, &mut fast_completed] {
19919            event
19920                .payload
19921                .as_object_mut()
19922                .expect("activity payload")
19923                .remove("activity_execution_id");
19924            event.payload["activity_id"] = json!("forged-activity-id");
19925        }
19926        let mut marker = selection_winner_marker();
19927        marker.payload["operation_identity"] = json!("forged-activity-id");
19928        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19929        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19930        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19931
19932        assert!(matches!(
19933            selection.as_mut().poll(&mut task_context),
19934            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19935        ));
19936    }
19937
19938    #[test]
19939    fn selection_completion_before_cancellation_remains_awaitable() {
19940        let history = vec![
19941            selection_activity_event("ActivityScheduled", 0, "slow", None),
19942            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19943            selection_winner_marker(),
19944            selection_activity_event(
19945                "ActivityCompleted",
19946                0,
19947                "slow",
19948                Some(json!("completed-first")),
19949            ),
19950        ];
19951        let ctx = workflow_context(history);
19952        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19953        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19954        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19955            panic!("winner must replay");
19956        };
19957        let slow = selected
19958            .handle(&SelectionKey::Name("slow".to_string()))
19959            .expect("slow handle")
19960            .clone();
19961        let mut cancel = Box::pin(slow.cancel());
19962        assert!(matches!(
19963            cancel.as_mut().poll(&mut task_context),
19964            Poll::Ready(Ok(()))
19965        ));
19966        let mut await_slow = Box::pin(slow.await_result());
19967        assert!(matches!(
19968            await_slow.as_mut().poll(&mut task_context),
19969            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19970        ));
19971        let commands = ctx.take_commands().expect("commands");
19972        assert!(commands.is_empty());
19973    }
19974
19975    #[test]
19976    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19977        let nested_member = SelectionMemberMetadata {
19978            key: SelectionKey::Name("nested".to_string()),
19979            index: 0,
19980            base_sequence: 1,
19981            size: 2,
19982            kind: "group".to_string(),
19983        };
19984        let deadline_member = SelectionMemberMetadata {
19985            key: SelectionKey::Name("deadline".to_string()),
19986            index: 1,
19987            base_sequence: 3,
19988            size: 1,
19989            kind: "timer".to_string(),
19990        };
19991        let nested_paths = [
19992            vec![
19993                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19994                parallel_group_entry(1, 2, 0, "activity"),
19995            ],
19996            vec![
19997                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19998                parallel_group_entry(1, 2, 1, "activity"),
19999            ],
20000        ];
20001        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
20002        let mut timer_fired = parallel_history_event(
20003            "TimerFired",
20004            3,
20005            "timer_id",
20006            "timer-3",
20007            deadline_path.clone(),
20008            None,
20009        );
20010        timer_fired.payload["delay_seconds"] = json!(0);
20011        timer_fired
20012            .raw
20013            .insert("id".to_string(), json!("timer-fired"));
20014        let mut timer_scheduled = parallel_history_event(
20015            "TimerScheduled",
20016            3,
20017            "timer_id",
20018            "timer-3",
20019            deadline_path,
20020            None,
20021        );
20022        timer_scheduled.payload["delay_seconds"] = json!(0);
20023        let history = vec![
20024            parallel_history_event(
20025                "ActivityScheduled",
20026                1,
20027                "activity_type",
20028                "nested-first",
20029                nested_paths[0].clone(),
20030                None,
20031            ),
20032            parallel_history_event(
20033                "ActivityScheduled",
20034                2,
20035                "activity_type",
20036                "nested-second",
20037                nested_paths[1].clone(),
20038                None,
20039            ),
20040            timer_scheduled,
20041            timer_fired,
20042            history_event(
20043                "SelectionResolved",
20044                json!({
20045                    "selection_group_id": "select-calls:1:3",
20046                    "selection_group_base_sequence": 1,
20047                    "selection_group_size": 3,
20048                    "member_key": "deadline",
20049                    "member_index": 1,
20050                    "member_base_sequence": 3,
20051                    "member_size": 1,
20052                    "operation_kind": "timer",
20053                    "operation_identity": "timer-3",
20054                    "outcome": "completed",
20055                    "resolution_event_id": "timer-fired",
20056                    "resolution_event_type": "TimerFired",
20057                }),
20058            ),
20059            parallel_history_event(
20060                "ActivityFailed",
20061                2,
20062                "activity_type",
20063                "nested-second",
20064                nested_paths[1].clone(),
20065                None,
20066            ),
20067        ];
20068        let ctx = workflow_context(history);
20069        let mut selection = Box::pin(ctx.select_keyed(vec![
20070            (
20071                "nested",
20072                ParallelOperation::group(vec![
20073                    ParallelOperation::activity("nested-first", json!([])),
20074                    ParallelOperation::activity("nested-second", json!([])),
20075                ]),
20076            ),
20077            ("deadline", ParallelOperation::timer(Duration::ZERO)),
20078        ]));
20079        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20080        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20081            panic!("deadline winner must replay");
20082        };
20083        let nested = selected
20084            .handle(&SelectionKey::Name("nested".to_string()))
20085            .expect("nested handle")
20086            .clone();
20087        let mut cancel = Box::pin(nested.cancel());
20088        assert!(matches!(
20089            cancel.as_mut().poll(&mut task_context),
20090            Poll::Ready(Ok(()))
20091        ));
20092        let mut await_nested = Box::pin(nested.await_result());
20093
20094        assert!(matches!(
20095            await_nested.as_mut().poll(&mut task_context),
20096            Poll::Ready(Err(Error::ActivityFailed(_)))
20097        ));
20098        assert!(ctx.take_commands().expect("commands").is_empty());
20099    }
20100
20101    #[test]
20102    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
20103        let ctx = workflow_context(Vec::new());
20104        let mut call = Box::pin(ctx.select(vec![
20105            ParallelOperation::child_workflow(
20106                "child",
20107                ChildWorkflowOptions::new("children"),
20108                json!([]),
20109            ),
20110            ParallelOperation::timer(Duration::from_secs(30)),
20111            ParallelOperation::signal("approval"),
20112            ParallelOperation::condition(
20113                ConditionWaitOptions::new("ready", "sha256:ready"),
20114                || Ok(false),
20115            ),
20116            ParallelOperation::group(vec![
20117                ParallelOperation::activity("nested-one", json!([])),
20118                ParallelOperation::activity("nested-two", json!([])),
20119            ]),
20120        ]));
20121        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20122        assert!(matches!(
20123            call.as_mut().poll(&mut task_context),
20124            Poll::Pending
20125        ));
20126        let commands = ctx.take_commands().expect("selection commands");
20127        assert_eq!(
20128            commands
20129                .iter()
20130                .map(|command| command["type"].as_str().unwrap_or_default())
20131                .collect::<Vec<_>>(),
20132            [
20133                "start_child_workflow",
20134                "start_timer",
20135                "open_signal_wait",
20136                "open_condition_wait",
20137                "schedule_activity",
20138                "schedule_activity",
20139            ]
20140        );
20141        assert!(commands.iter().all(|command| {
20142            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
20143        }));
20144        assert_eq!(
20145            commands[4]["parallel_group_path"].as_array().map(Vec::len),
20146            Some(2)
20147        );
20148        assert_eq!(
20149            commands[4]["parallel_group_path"][0]["selection_member_kind"],
20150            json!("group")
20151        );
20152        assert_eq!(
20153            commands[5]["parallel_group_path"][0]["selection_member_kind"],
20154            json!("group")
20155        );
20156
20157        let one_leaf_ctx = workflow_context(Vec::new());
20158        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
20159            ParallelOperation::activity("nested-only", json!([])),
20160        ])]));
20161        assert!(matches!(
20162            one_leaf.as_mut().poll(&mut task_context),
20163            Poll::Pending
20164        ));
20165        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
20166        assert_eq!(one_leaf_commands.len(), 1);
20167        assert_eq!(
20168            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
20169            json!("group")
20170        );
20171        assert_eq!(
20172            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
20173            json!(1)
20174        );
20175    }
20176
20177    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
20178        let mut saga = ctx.saga();
20179        let outcome = async {
20180            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20181            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20182            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
20183            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
20184            ctx.activity("trip.charge", json!([])).await?;
20185            Ok(json!({"status": "booked"}))
20186        }
20187        .await;
20188        saga.finish(outcome).await
20189    }
20190
20191    fn saga_activity(
20192        event_type: &str,
20193        sequence: u64,
20194        activity_type: &str,
20195        result: Option<Value>,
20196    ) -> HistoryEvent {
20197        let mut payload = json!({
20198            "sequence": sequence,
20199            "activity_type": activity_type,
20200            "message": format!("{activity_type} failed"),
20201            "exception_type": "PlannedFailure",
20202            "non_retryable": true,
20203        });
20204        if let Some(result) = result {
20205            payload["result"] = fixture_envelope(result);
20206        }
20207        history_event(event_type, payload)
20208    }
20209
20210    #[test]
20211    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
20212        let completed_hotel_compensation = saga_activity(
20213            "ActivityCompleted",
20214            4,
20215            "trip.cancel-hotel",
20216            Some(Value::Null),
20217        );
20218        let history = vec![
20219            saga_activity(
20220                "ActivityCompleted",
20221                1,
20222                "trip.reserve-flight",
20223                Some(json!("flight-1")),
20224            ),
20225            saga_activity(
20226                "ActivityCompleted",
20227                2,
20228                "trip.reserve-hotel",
20229                Some(json!("hotel-1")),
20230            ),
20231            saga_activity("ActivityFailed", 3, "trip.charge", None),
20232            completed_hotel_compensation.clone(),
20233            completed_hotel_compensation,
20234        ];
20235
20236        for _restart in 0..2 {
20237            let ctx = workflow_context(history.clone());
20238            let mut future = Box::pin(trip_saga(ctx.clone()));
20239            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20240            assert!(matches!(
20241                future.as_mut().poll(&mut task_context),
20242                Poll::Pending
20243            ));
20244            let commands = ctx.take_commands().expect("compensation command");
20245            assert_eq!(commands.len(), 1);
20246            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20247        }
20248    }
20249
20250    #[test]
20251    fn saga_compensation_failure_preserves_both_typed_failures() {
20252        let history = vec![
20253            saga_activity(
20254                "ActivityCompleted",
20255                1,
20256                "trip.reserve-flight",
20257                Some(json!("flight-1")),
20258            ),
20259            saga_activity(
20260                "ActivityCompleted",
20261                2,
20262                "trip.reserve-hotel",
20263                Some(json!("hotel-1")),
20264            ),
20265            saga_activity("ActivityFailed", 3, "trip.charge", None),
20266            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
20267        ];
20268        let ctx = workflow_context(history);
20269        let mut future = Box::pin(trip_saga(ctx));
20270        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20271        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
20272            future.as_mut().poll(&mut task_context)
20273        else {
20274            panic!("compensation failure must remain structured");
20275        };
20276        assert!(matches!(
20277            *failure.initiating_failure,
20278            Error::ActivityFailed(_)
20279        ));
20280        assert!(matches!(
20281            *failure.compensation_failure,
20282            Error::ActivityFailed(_)
20283        ));
20284        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
20285        assert_eq!(failure.compensation_registration_order, 2);
20286    }
20287
20288    #[test]
20289    fn saga_compensates_cooperative_cancellation() {
20290        let ctx = workflow_context(vec![saga_activity(
20291            "ActivityCompleted",
20292            1,
20293            "trip.reserve-flight",
20294            Some(json!("flight-1")),
20295        )]);
20296        ctx.state.lock().expect("state").cancel_requested = true;
20297        let run = {
20298            let ctx = ctx.clone();
20299            async move {
20300                let mut saga = ctx.saga();
20301                let outcome = async {
20302                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20303                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20304                    ctx.throw_if_cancellation_requested()?;
20305                    Ok(json!("unexpected"))
20306                }
20307                .await;
20308                saga.finish(outcome).await
20309            }
20310        };
20311        let mut future = Box::pin(run);
20312        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20313        assert!(matches!(
20314            future.as_mut().poll(&mut task_context),
20315            Poll::Pending
20316        ));
20317        let commands = ctx.take_commands().expect("cancellation compensation");
20318        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20319    }
20320
20321    #[test]
20322    fn optional_task_observability_fields_round_trip_without_interpretation() {
20323        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
20324        let dispatch = json!({"task_id": "other-task"});
20325        let links = json!({"links": []});
20326        let mut value = json!({
20327            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
20328            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
20329        });
20330        let workflow: WorkflowTask =
20331            serde_json::from_value(value.clone()).expect("legacy workflow task");
20332        let activity: ActivityTask =
20333            serde_json::from_value(value.clone()).expect("legacy activity task");
20334        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
20335        assert!(workflow.observability_context.is_none());
20336        assert!(activity.observability_context.is_none());
20337        assert!(query.observability_context.is_none());
20338        assert!(activity.workflow_id.is_none());
20339        assert!(activity.run_id.is_none());
20340        assert!(activity.activity_execution_id.is_none());
20341
20342        value["observability_context"] = context.clone();
20343        value["dispatch_observability_context"] = dispatch.clone();
20344        value["observability_links"] = links.clone();
20345        value["workflow_id"] = json!("workflow-id");
20346        value["run_id"] = json!("run-id");
20347        value["activity_execution_id"] = json!("activity-id");
20348        let workflow: WorkflowTask =
20349            serde_json::from_value(value.clone()).expect("workflow metadata");
20350        let activity: ActivityTask =
20351            serde_json::from_value(value.clone()).expect("activity metadata");
20352        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
20353        for fields in [
20354            (
20355                workflow.observability_context,
20356                workflow.dispatch_observability_context,
20357                workflow.observability_links,
20358            ),
20359            (
20360                activity.observability_context,
20361                activity.dispatch_observability_context,
20362                activity.observability_links,
20363            ),
20364            (
20365                query.observability_context,
20366                query.dispatch_observability_context,
20367                query.observability_links,
20368            ),
20369        ] {
20370            assert_eq!(
20371                fields,
20372                (
20373                    Some(context.clone()),
20374                    Some(dispatch.clone()),
20375                    Some(links.clone())
20376                )
20377            );
20378        }
20379        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
20380        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
20381        assert_eq!(
20382            activity.activity_execution_id.as_deref(),
20383            Some("activity-id")
20384        );
20385    }
20386
20387    fn workflow_task(
20388        workflow_type: &str,
20389        history_events: Vec<HistoryEvent>,
20390        payload_codec: &str,
20391    ) -> WorkflowTask {
20392        WorkflowTask {
20393            task_id: format!("wft-{workflow_type}"),
20394            observability_context: None,
20395            dispatch_observability_context: None,
20396            observability_links: None,
20397            workflow_command_id: None,
20398            workflow_id: Some(format!("wf-{workflow_type}")),
20399            run_id: Some(format!("run-{workflow_type}")),
20400            workflow_type: workflow_type.to_string(),
20401            cancel_requested: false,
20402            payload_codec: payload_codec.to_string(),
20403            arguments: Some(
20404                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
20405            ),
20406            total_history_events: Some(history_events.len() as u64),
20407            history_size_bytes: None,
20408            continue_as_new_recommended: None,
20409            history_budget_pressure: None,
20410            history_events,
20411            next_history_page_token: None,
20412            workflow_task_attempt: 1,
20413            workflow_signal_id: None,
20414            signal_name: None,
20415            signal_arguments: None,
20416            workflow_update_id: None,
20417            update_name: None,
20418            lease_owner: Some("rust-worker".to_string()),
20419        }
20420    }
20421
20422    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20423    struct SideEffectProbe {
20424        request_id: String,
20425        attempt: u32,
20426    }
20427
20428    #[test]
20429    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
20430        let calls = AtomicUsize::new(0);
20431        let ctx = workflow_context(Vec::new());
20432        let value = ctx
20433            .side_effect(|| {
20434                calls.fetch_add(1, Ordering::SeqCst);
20435                SideEffectProbe {
20436                    request_id: "request-42".to_string(),
20437                    attempt: 3,
20438                }
20439            })
20440            .expect("first side effect");
20441        assert_eq!(value.attempt, 3);
20442        assert_eq!(calls.load(Ordering::SeqCst), 1);
20443        let commands = ctx.take_commands().expect("commands");
20444        assert_eq!(commands.len(), 1);
20445        assert_eq!(commands[0]["type"], "record_side_effect");
20446        assert_eq!(
20447            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20448            serde_json::to_value(&value).expect("value")
20449        );
20450
20451        let replay = workflow_context(vec![history_event(
20452            "SideEffectRecorded",
20453            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20454        )]);
20455        let replayed: SideEffectProbe = replay
20456            .side_effect(|| {
20457                calls.fetch_add(1, Ordering::SeqCst);
20458                panic!("committed side-effect callbacks must not run during replay")
20459            })
20460            .expect("replayed side effect");
20461        assert_eq!(replayed, value);
20462        assert_eq!(calls.load(Ordering::SeqCst), 1);
20463        assert!(replay.take_commands().expect("commands").is_empty());
20464        replay.ensure_history_consumed().expect("history consumed");
20465    }
20466
20467    #[test]
20468    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
20469        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20470        let value = ctx
20471            .side_effect(|| SideEffectProbe {
20472                request_id: "avro-request".to_string(),
20473                attempt: 1,
20474            })
20475            .expect("Avro side effect");
20476        let uuid = ctx.uuid_v4().expect("deterministic UUID");
20477        let commands = ctx.take_commands().expect("commands");
20478        assert_eq!(commands.len(), 2);
20479        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
20480        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
20481        assert_eq!(
20482            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20483            serde_json::to_value(&value).expect("value")
20484        );
20485
20486        let replay = workflow_context_with_codec(
20487            vec![
20488                history_event(
20489                    "SideEffectRecorded",
20490                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20491                ),
20492                history_event(
20493                    "SideEffectRecorded",
20494                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
20495                ),
20496            ],
20497            DEFAULT_CODEC,
20498        );
20499        let replayed: SideEffectProbe = replay
20500            .side_effect(|| panic!("Avro callback must not run"))
20501            .expect("replayed Avro value");
20502        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
20503        assert_eq!(replayed, value);
20504        assert_eq!(replayed_uuid, uuid);
20505        assert!(replay.take_commands().expect("commands").is_empty());
20506    }
20507
20508    #[test]
20509    fn typed_side_effect_replay_preserves_bytes_and_maps() {
20510        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20511        let value = ctx
20512            .side_effect_avro_value(typed_fidelity_probe)
20513            .expect("typed side effect");
20514        let commands = ctx.take_commands().expect("side-effect command");
20515        assert_eq!(
20516            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20517                .expect("recorded side effect"),
20518            value
20519        );
20520
20521        let replay = workflow_context_with_codec(
20522            vec![history_event(
20523                "SideEffectRecorded",
20524                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20525            )],
20526            DEFAULT_CODEC,
20527        );
20528        assert_eq!(
20529            replay
20530                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
20531                .expect("replayed typed side effect"),
20532            value
20533        );
20534    }
20535
20536    #[test]
20537    fn ordered_side_effects_share_the_durable_command_stream() {
20538        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
20539        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
20540        let ctx = workflow_context(vec![
20541            history_event(
20542                "SideEffectRecorded",
20543                json!({"sequence": 1, "result": first}),
20544            ),
20545            history_event(
20546                "SideEffectRecorded",
20547                json!({"sequence": 2, "result": second}),
20548            ),
20549        ]);
20550        let first: String = ctx
20551            .side_effect(|| panic!("first callback must not run"))
20552            .expect("first replay");
20553        let second: i32 = ctx
20554            .side_effect(|| panic!("second callback must not run"))
20555            .expect("second replay");
20556        assert_eq!(first, "first");
20557        assert_eq!(second, 29);
20558        ctx.ensure_history_consumed().expect("ordered history");
20559
20560        let reordered = workflow_context(vec![history_event(
20561            "VersionMarkerRecorded",
20562            json!({
20563                "sequence": 1,
20564                "change_id": "before-side-effect",
20565                "version": 1,
20566                "min_supported": 1,
20567                "max_supported": 1,
20568            }),
20569        )]);
20570        let error = reordered
20571            .side_effect(|| "new".to_string())
20572            .expect_err("command reordering must fail");
20573        assert!(matches!(
20574            error,
20575            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20576                if reason == "recorded_command_mismatch"
20577        ));
20578    }
20579
20580    #[test]
20581    fn legacy_patch_preserves_pending_and_completed_activity_history() {
20582        for completed in [false, true] {
20583            let mut history = vec![history_event(
20584                "ActivityScheduled",
20585                json!({"sequence": 1, "activity_type": "old"}),
20586            )];
20587            if completed {
20588                history.push(history_event(
20589                    "ActivityCompleted",
20590                    json!({
20591                        "sequence": 1,
20592                        "activity_type": "old",
20593                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
20594                    }),
20595                ));
20596            }
20597            for _cold_replay in 0..2 {
20598                let ctx = workflow_context(history.clone());
20599                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
20600                assert!(!ctx.patched("added-step").expect("same frozen decision"));
20601                ctx.deprecate_patch("added-step")
20602                    .expect("retained boundary");
20603                let mut activity = Box::pin(ctx.activity("old", json!([])));
20604                let mut context = TaskContext::from_waker(noop_waker_ref());
20605                match activity.as_mut().poll(&mut context) {
20606                    Poll::Ready(result) => {
20607                        assert!(completed);
20608                        assert_eq!(result.expect("recorded result"), json!(41));
20609                        ctx.ensure_history_consumed().expect("old command retained");
20610                    }
20611                    Poll::Pending => assert!(!completed),
20612                }
20613                assert!(ctx.take_commands().expect("commands").is_empty());
20614            }
20615        }
20616    }
20617
20618    #[test]
20619    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
20620        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
20621        assert!(!ctx.patched("added-step").expect("legacy completed run"));
20622        ctx.deprecate_patch("added-step")
20623            .expect("same legacy decision");
20624        assert!(ctx.take_commands().expect("commands").is_empty());
20625        ctx.ensure_history_consumed().expect("completed history");
20626    }
20627
20628    #[test]
20629    fn legacy_patch_rejects_a_range_without_the_original_branch() {
20630        let ctx = workflow_context(vec![history_event(
20631            "ActivityScheduled",
20632            json!({"sequence": 1, "activity_type": "old"}),
20633        )]);
20634        let error = ctx
20635            .get_version("added-step", 0, 1)
20636            .expect_err("legacy is unsupported");
20637        assert!(matches!(
20638            error,
20639            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20640                if reason == "version_marker_incompatible_range"
20641        ));
20642        assert!(!ctx
20643            .patched("supported-step")
20644            .expect("failed check did not consume history"));
20645        assert!(ctx.take_commands().expect("commands").is_empty());
20646    }
20647
20648    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20649        let mut event = history_event(
20650            "VersionMarkerRecorded",
20651            json!({
20652                "sequence": sequence,
20653                "change_id": "retained-patch",
20654                "version": version,
20655                "min_supported": -1,
20656                "max_supported": 1,
20657            }),
20658        );
20659        event.raw.insert("timestamp".into(), json!(time));
20660        event
20661    }
20662
20663    #[test]
20664    fn retained_patch_markers_preserve_each_original_boundary() {
20665        for completed in [false, true] {
20666            let mut history = vec![
20667                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20668                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20669                history_event(
20670                    "ActivityScheduled",
20671                    json!({"sequence": 3, "activity_type": "old"}),
20672                ),
20673            ];
20674            if completed {
20675                history.push(history_event(
20676                    "ActivityCompleted",
20677                    json!({
20678                        "sequence": 3,
20679                        "activity_type": "old",
20680                        "result": fixture_envelope(json!(41)),
20681                    }),
20682                ));
20683            }
20684            for _cold_replay in 0..2 {
20685                let ctx = workflow_context(history.clone());
20686                assert!(ctx.patched("retained-patch").unwrap());
20687                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20688                assert!(ctx.patched("retained-patch").unwrap());
20689                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20690                ctx.deprecate_patch("retained-patch").unwrap();
20691                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20692                let mut activity = Box::pin(ctx.activity("old", json!([])));
20693                let mut context = TaskContext::from_waker(noop_waker_ref());
20694                match activity.as_mut().poll(&mut context) {
20695                    Poll::Ready(result) => {
20696                        assert!(completed);
20697                        assert_eq!(result.unwrap(), json!(41));
20698                        ctx.ensure_history_consumed().unwrap();
20699                    }
20700                    Poll::Pending => assert!(!completed),
20701                }
20702                assert!(ctx.take_commands().unwrap().is_empty());
20703                let state = ctx.state.lock().unwrap();
20704                for (actual, original) in state.history_events.iter().zip(&history) {
20705                    assert_eq!(actual.payload, original.payload);
20706                    assert_eq!(actual.raw, original.raw);
20707                }
20708            }
20709        }
20710    }
20711
20712    #[test]
20713    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20714        let ctx = workflow_context(vec![
20715            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20716            history_event(
20717                "SideEffectRecorded",
20718                json!({
20719                    "sequence": 2, "result": fixture_envelope(json!("between")),
20720                }),
20721            ),
20722            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20723            history_event(
20724                "VersionMarkerRecorded",
20725                json!({
20726                    "sequence": 4, "change_id": "other-patch", "version": 1,
20727                    "min_supported": -1, "max_supported": 1,
20728                }),
20729            ),
20730        ]);
20731        assert!(ctx.patched("retained-patch").unwrap());
20732        assert!(ctx.patched("retained-patch").unwrap());
20733        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20734        assert_eq!(
20735            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20736            "between"
20737        );
20738        ctx.deprecate_patch("retained-patch").unwrap();
20739        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20740        ctx.deprecate_patch("retained-patch").unwrap();
20741        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20742        assert!(ctx.patched("other-patch").unwrap());
20743        ctx.ensure_history_consumed().unwrap();
20744        assert!(ctx.take_commands().unwrap().is_empty());
20745    }
20746
20747    #[test]
20748    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20749        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20750        alias.payload["max_supported"] = json!(3);
20751        let ctx = workflow_context(vec![
20752            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20753            alias,
20754        ]);
20755        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20756        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20757        assert!(matches!(error,
20758            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20759                if reason == "version_marker_incompatible_range"));
20760        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20761        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20762        ctx.ensure_history_consumed().unwrap();
20763        assert!(ctx.take_commands().unwrap().is_empty());
20764    }
20765
20766    #[test]
20767    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20768        let ctx = workflow_context(Vec::new());
20769        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20770        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20771        assert!(ctx.patched("new-search").expect("patch"));
20772        ctx.deprecate_patch("new-search").expect("deprecate patch");
20773        let commands = ctx.take_commands().expect("commands");
20774        assert_eq!(commands.len(), 2);
20775        assert_eq!(commands[0]["type"], "record_version_marker");
20776        assert_eq!(commands[0]["version"], 2);
20777        assert_eq!(commands[1]["change_id"], "new-search");
20778
20779        let replay = workflow_context(vec![history_event(
20780            "VersionMarkerRecorded",
20781            json!({
20782                "sequence": 1,
20783                "change_id": "checkout-v2",
20784                "version": 2,
20785                "min_supported": 1,
20786                "max_supported": 2,
20787            }),
20788        )]);
20789        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20790        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20791        assert!(replay.take_commands().expect("commands").is_empty());
20792        replay.ensure_history_consumed().expect("history consumed");
20793    }
20794
20795    #[test]
20796    fn version_markers_reject_incompatible_or_malformed_history() {
20797        let incompatible = workflow_context(vec![history_event(
20798            "VersionMarkerRecorded",
20799            json!({
20800                "sequence": 1,
20801                "change_id": "checkout-v2",
20802                "version": 1,
20803                "min_supported": 1,
20804                "max_supported": 2,
20805            }),
20806        )]);
20807        let error = incompatible
20808            .get_version("checkout-v2", 2, 3)
20809            .expect_err("old version is unsupported");
20810        assert!(matches!(
20811            error,
20812            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20813                if reason == "version_marker_incompatible_range"
20814        ));
20815
20816        for (history, reason) in [
20817            (
20818                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20819                "side_effect_result_missing",
20820            ),
20821            (
20822                vec![history_event(
20823                    "SideEffectRecorded",
20824                    json!({
20825                        "sequence": 1,
20826                        "result": {"codec": "avro", "blob": "not-base64"},
20827                    }),
20828                )],
20829                "side_effect_payload_incompatible",
20830            ),
20831            (
20832                vec![history_event(
20833                    "SideEffectRecorded",
20834                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20835                )],
20836                "side_effect_payload_malformed",
20837            ),
20838            (
20839                vec![history_event(
20840                    "VersionMarkerRecorded",
20841                    json!({
20842                        "sequence": 1,
20843                        "change_id": "change",
20844                        "version": 1,
20845                        "min_supported": 2,
20846                        "max_supported": 1,
20847                    }),
20848                )],
20849                "version_marker_history_range_invalid",
20850            ),
20851        ] {
20852            let error = WorkflowState::new(
20853                history,
20854                "rust-workers".to_string(),
20855                DEFAULT_CODEC.to_string(),
20856                None,
20857            )
20858            .expect_err("malformed history must fail");
20859            assert!(matches!(
20860                error,
20861                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20862                    if actual == reason
20863            ));
20864        }
20865    }
20866
20867    #[test]
20868    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20869        let history = vec![history_event(
20870            "SearchAttributesUpserted",
20871            json!({
20872                "sequence": 1,
20873                "attributes": {"customer_tier": "gold"},
20874                "attribute_types": {"customer_tier": "keyword"},
20875                "merged": {"customer_tier": "gold"}
20876            }),
20877        )];
20878
20879        let matching = workflow_context(history.clone());
20880        matching
20881            .upsert_search_attributes(
20882                SearchAttributeUpdate::new()
20883                    .keyword("customer_tier", "gold")
20884                    .expect("keyword update"),
20885            )
20886            .expect("matching typed update must replay");
20887        matching
20888            .ensure_history_consumed()
20889            .expect("history consumed");
20890
20891        let changed_type = workflow_context(history.clone());
20892        let error = changed_type
20893            .upsert_search_attributes(
20894                SearchAttributeUpdate::new()
20895                    .string("customer_tier", "gold")
20896                    .expect("string update"),
20897            )
20898            .expect_err("same JSON value with a different declaration must be nondeterministic");
20899        let Error::NonDeterministicReplay(failure) = error else {
20900            panic!("typed identity drift must be a replay failure");
20901        };
20902        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20903        assert_eq!(failure.sequence, Some(1));
20904
20905        let changed_value = workflow_context(history);
20906        let error = changed_value
20907            .upsert_search_attributes(
20908                SearchAttributeUpdate::new()
20909                    .keyword("customer_tier", "platinum")
20910                    .expect("keyword update"),
20911            )
20912            .expect_err("changed values must be nondeterministic");
20913        let Error::NonDeterministicReplay(failure) = error else {
20914            panic!("value drift must be a replay failure");
20915        };
20916        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20917    }
20918
20919    #[test]
20920    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20921        let history = vec![history_event(
20922            "SearchAttributesUpserted",
20923            json!({
20924                "sequence": 1,
20925                "attributes": {"customer_tier": "gold"},
20926                "merged": {"customer_tier": "gold"}
20927            }),
20928        )];
20929
20930        for update in [
20931            SearchAttributeUpdate::new()
20932                .keyword("customer_tier", "gold")
20933                .expect("keyword update"),
20934            SearchAttributeUpdate::new()
20935                .string("customer_tier", "gold")
20936                .expect("string update"),
20937        ] {
20938            let restarted = workflow_context(history.clone());
20939            restarted
20940                .upsert_search_attributes(update)
20941                .expect("legacy history constrains values but has unknown type identity");
20942            restarted
20943                .ensure_history_consumed()
20944                .expect("history consumed");
20945        }
20946    }
20947
20948    #[test]
20949    fn search_attribute_command_emits_canonical_types() {
20950        let ctx = workflow_context(Vec::new());
20951        ctx.upsert_search_attributes(
20952            SearchAttributeUpdate::new()
20953                .keyword("customer_tier", "gold")
20954                .expect("keyword update")
20955                .int("attempts", 3)
20956                .expect("int update")
20957                .delete("obsolete")
20958                .expect("delete update"),
20959        )
20960        .expect("valid search attributes");
20961
20962        assert_eq!(
20963            ctx.take_commands().expect("commands"),
20964            vec![json!({
20965                "type": "upsert_search_attributes",
20966                "attributes": {
20967                    "attempts": 3,
20968                    "customer_tier": "gold",
20969                    "obsolete": null
20970                },
20971                "attribute_types": {
20972                    "attempts": "int",
20973                    "customer_tier": "keyword"
20974                }
20975            })]
20976        );
20977    }
20978
20979    #[test]
20980    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20981        let duplicate_side_effect = WorkflowState::new(
20982            vec![
20983                history_event(
20984                    "SideEffectRecorded",
20985                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
20986                ),
20987                history_event(
20988                    "SideEffectRecorded",
20989                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
20990                ),
20991            ],
20992            "rust-workers".to_string(),
20993            DEFAULT_CODEC.to_string(),
20994            None,
20995        )
20996        .expect_err("duplicate side effect");
20997        assert!(matches!(
20998            duplicate_side_effect,
20999            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21000                if reason == "duplicate_side_effect_record"
21001        ));
21002
21003        let marker = |sequence, version| {
21004            history_event(
21005                "VersionMarkerRecorded",
21006                json!({
21007                    "sequence": sequence,
21008                    "change_id": "same-change",
21009                    "version": version,
21010                    "min_supported": -1,
21011                    "max_supported": 1,
21012                }),
21013            )
21014        };
21015        let duplicate_marker = WorkflowState::new(
21016            vec![marker(1, 1), marker(3, -1)],
21017            "rust-workers".to_string(),
21018            DEFAULT_CODEC.to_string(),
21019            None,
21020        )
21021        .expect_err("conflicting marker");
21022        assert!(matches!(
21023            duplicate_marker,
21024            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21025                if reason == "version_marker_conflict"
21026        ));
21027    }
21028
21029    #[test]
21030    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
21031        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
21032        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21033        invalid_alias.payload["max_supported"] = json!(0);
21034        for (history, expected_reason) in [
21035            (
21036                vec![marker.clone(), marker.clone()],
21037                "duplicate_version_marker_record",
21038            ),
21039            (
21040                vec![marker, invalid_alias],
21041                "version_marker_history_range_invalid",
21042            ),
21043        ] {
21044            let error =
21045                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
21046                    .expect_err("invalid historical alias");
21047            assert!(matches!(error,
21048                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
21049                    if reason == expected_reason));
21050        }
21051    }
21052
21053    #[test]
21054    fn retained_patch_aliases_require_the_original_call_boundary() {
21055        let ctx = workflow_context(vec![
21056            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21057            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21058        ]);
21059        assert!(ctx.patched("retained-patch").unwrap());
21060        assert!(ctx.ensure_history_consumed().is_err());
21061        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21062        ctx.deprecate_patch("retained-patch").unwrap();
21063        ctx.ensure_history_consumed().unwrap();
21064        assert!(ctx.take_commands().unwrap().is_empty());
21065    }
21066
21067    #[test]
21068    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
21069        let ctx = workflow_context(vec![
21070            history_event(
21071                "SideEffectRecorded",
21072                json!({
21073                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
21074                }),
21075            ),
21076            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21077        ]);
21078        assert!(!ctx.patched("retained-patch").unwrap());
21079        assert_eq!(
21080            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21081            "old-operation"
21082        );
21083        let error = ctx.patched("retained-patch").unwrap_err();
21084        assert!(matches!(error,
21085            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21086                if reason == "version_marker_conflict"));
21087        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21088        assert!(ctx.take_commands().unwrap().is_empty());
21089    }
21090
21091    #[test]
21092    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
21093        let mut state = WorkflowState::new(
21094            Vec::new(),
21095            "rust-workers".to_string(),
21096            DEFAULT_CODEC.to_string(),
21097            None,
21098        )
21099        .expect("workflow state");
21100        state.workflow_command_identity = "command-7".to_string();
21101        let context = WorkflowContext {
21102            state: Arc::new(Mutex::new(state)),
21103            cancellation_scope_id: "root".into(),
21104        };
21105        let item =
21106            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
21107
21108        context
21109            .append_workflow_stream("output", &[item], Some(10))
21110            .expect("append command");
21111        context
21112            .error_workflow_stream("output", "producer failed", None)
21113            .expect("error command");
21114        let commands = context.take_commands().expect("commands");
21115
21116        assert_eq!(commands[0]["type"], "record_side_effect");
21117        assert_eq!(
21118            commands[0]["workflow_stream"]["command_identity"],
21119            "command-7"
21120        );
21121        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
21122        assert_eq!(
21123            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21124            "dw-stream:command-7:0:0"
21125        );
21126        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
21127
21128        let recorded = history_event(
21129            "SideEffectRecorded",
21130            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
21131        );
21132        let mut replay_state = WorkflowState::new(
21133            vec![recorded],
21134            "rust-workers".to_string(),
21135            DEFAULT_CODEC.to_string(),
21136            None,
21137        )
21138        .expect("replay state");
21139        replay_state.workflow_command_identity = "command-7".to_string();
21140        let replay_context = WorkflowContext {
21141            state: Arc::new(Mutex::new(replay_state)),
21142            cancellation_scope_id: "root".into(),
21143        };
21144        replay_context
21145            .append_workflow_stream(
21146                "output",
21147                &[WorkflowStreamAppendItem::from_reference(
21148                    "s3://bucket/item.avro",
21149                )],
21150                Some(10),
21151            )
21152            .expect("replayed append");
21153        assert!(replay_context
21154            .take_commands()
21155            .expect("replayed commands")
21156            .is_empty());
21157    }
21158
21159    #[test]
21160    fn workflow_stream_authoring_requires_server_durable_command_identity() {
21161        let context = workflow_context(Vec::new());
21162        let error = context
21163            .append_workflow_stream(
21164                "output",
21165                &[WorkflowStreamAppendItem::from_reference(
21166                    "s3://bucket/item.avro",
21167                )],
21168                None,
21169            )
21170            .expect_err("stream append without durable command identity must fail closed");
21171
21172        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
21173        assert!(context.take_commands().expect("commands").is_empty());
21174    }
21175
21176    #[test]
21177    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
21178        let client = Client::builder("http://localhost:8080").build().unwrap();
21179        let mut worker = Worker::new(client, "rust-workers");
21180        worker.register_workflow("streams.worker", |ctx, _| async move {
21181            ctx.append_workflow_stream(
21182                "output",
21183                &[WorkflowStreamAppendItem::new(json!("hello"))?],
21184                None,
21185            )?;
21186            ctx.close_workflow_stream("output", None)?;
21187            Ok(json!("done"))
21188        });
21189        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
21190            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21191            task.workflow_command_id = command_id.clone();
21192            let expected_identity = command_id
21193                .as_deref()
21194                .filter(|id| !id.is_empty())
21195                .unwrap_or(&task.task_id)
21196                .to_string();
21197            let commands = worker
21198                .execute_workflow_task(task)
21199                .expect("ordinary worker stream output");
21200            assert_eq!(commands.len(), 3);
21201            assert_eq!(
21202                commands[0]["workflow_stream"]["command_identity"],
21203                expected_identity
21204            );
21205            assert_eq!(
21206                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21207                format!("dw-stream:{expected_identity}:0:0")
21208            );
21209            assert_eq!(
21210                commands[1]["workflow_stream"]["command_identity"],
21211                expected_identity
21212            );
21213            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
21214            let history = commands[..2]
21215                .iter()
21216                .enumerate()
21217                .map(|(index, command)| {
21218                    history_event(
21219                        "SideEffectRecorded",
21220                        json!({"sequence":index + 1,"result":command["result"]}),
21221                    )
21222                })
21223                .collect();
21224            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
21225            replay.task_id = "replacement-task".to_string();
21226            let replayed = worker
21227                .execute_workflow_task(replay)
21228                .expect("replacement worker consumes recorded stream effects");
21229            assert_eq!(replayed.len(), 1);
21230            assert_eq!(replayed[0]["type"], "complete_workflow");
21231        }
21232        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21233        missing.task_id.clear();
21234        assert!(matches!(
21235            worker.execute_workflow_task(missing),
21236            Err(Error::MissingWorkflowCommandIdentity)
21237        ));
21238    }
21239
21240    #[test]
21241    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
21242        fn worker(calls: Arc<AtomicUsize>) -> Worker {
21243            let client = Client::new("http://127.0.0.1:8080").expect("client");
21244            let mut worker = Worker::new(client, "rust-workers");
21245            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
21246                let calls = Arc::clone(&calls);
21247                async move {
21248                    let captured = ctx.side_effect(|| {
21249                        calls.fetch_add(1, Ordering::SeqCst);
21250                        "captured-once".to_string()
21251                    })?;
21252                    let version = ctx.get_version("cold-restart", 1, 2)?;
21253                    Ok(json!({"captured": captured, "version": version}))
21254                }
21255            });
21256            worker
21257        }
21258
21259        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
21260            WorkflowTask {
21261                task_id: "wft-side-effect-version".to_string(),
21262                observability_context: None,
21263                dispatch_observability_context: None,
21264                observability_links: None,
21265                workflow_command_id: None,
21266                workflow_id: Some("wf-side-effect-version".to_string()),
21267                run_id: Some("run-side-effect-version".to_string()),
21268                workflow_type: "rust.side-effect-version".to_string(),
21269                cancel_requested: false,
21270                payload_codec: DEFAULT_CODEC.to_string(),
21271                arguments: Some(
21272                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
21273                ),
21274                history_events,
21275                total_history_events: None,
21276                history_size_bytes: None,
21277                continue_as_new_recommended: None,
21278                history_budget_pressure: None,
21279                next_history_page_token: None,
21280                workflow_task_attempt: 1,
21281                workflow_signal_id: None,
21282                signal_name: None,
21283                signal_arguments: None,
21284                workflow_update_id: None,
21285                update_name: None,
21286                lease_owner: Some("rust-worker".to_string()),
21287            }
21288        }
21289
21290        let calls = Arc::new(AtomicUsize::new(0));
21291        let initial = worker(Arc::clone(&calls))
21292            .execute_workflow_task(task(Vec::new()))
21293            .expect("initial execution");
21294        assert_eq!(
21295            initial
21296                .iter()
21297                .map(|command| &command["type"])
21298                .collect::<Vec<_>>(),
21299            vec![
21300                "record_side_effect",
21301                "record_version_marker",
21302                "complete_workflow"
21303            ]
21304        );
21305        assert_eq!(calls.load(Ordering::SeqCst), 1);
21306
21307        let restarted = worker(Arc::clone(&calls));
21308        let replayed = restarted
21309            .execute_workflow_task(task(vec![
21310                history_event(
21311                    "SideEffectRecorded",
21312                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
21313                ),
21314                history_event(
21315                    "VersionMarkerRecorded",
21316                    json!({
21317                        "sequence": 2,
21318                        "change_id": "cold-restart",
21319                        "version": 2,
21320                        "min_supported": 1,
21321                        "max_supported": 2,
21322                    }),
21323                ),
21324            ]))
21325            .expect("cold replay");
21326        assert_eq!(replayed.len(), 1);
21327        assert_eq!(replayed[0]["type"], "complete_workflow");
21328        assert_eq!(calls.load(Ordering::SeqCst), 1);
21329    }
21330
21331    #[test]
21332    fn side_effect_replay_rejects_changed_rust_value_type() {
21333        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
21334        let ctx = workflow_context(vec![history_event(
21335            "SideEffectRecorded",
21336            json!({"sequence": 1, "result": result}),
21337        )]);
21338        let error = ctx
21339            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
21340            .expect_err("changed type must fail replay");
21341        assert!(matches!(
21342            error,
21343            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21344                if reason == "side_effect_type_mismatch"
21345        ));
21346    }
21347
21348    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
21349        vec![
21350            history_event(
21351                "ActivityScheduled",
21352                json!({
21353                    "sequence": 1,
21354                    "activity_type": "flaky",
21355                    "activity_execution_id": "act-1",
21356                    "activity": {
21357                        "id": "act-1",
21358                        "sequence": 1,
21359                        "type": "flaky",
21360                        "queue": "critical-activities",
21361                        "execution_mode": null,
21362                        "retry_policy": {
21363                            "snapshot_version": 1,
21364                            "max_attempts": 3,
21365                            "backoff_seconds": [2, 4],
21366                            "start_to_close_timeout": 30,
21367                            "schedule_to_start_timeout": 5,
21368                            "schedule_to_close_timeout": 90,
21369                            "heartbeat_timeout": 10,
21370                            "non_retryable_error_types": ["PermanentError"]
21371                        }
21372                    }
21373                }),
21374            ),
21375            history_event(
21376                "ActivityStarted",
21377                json!({
21378                    "sequence": 1,
21379                    "activity_type": "flaky",
21380                    "activity_execution_id": "act-1",
21381                    "activity_attempt_id": "attempt-1",
21382                    "attempt_number": 1
21383                }),
21384            ),
21385            history_event(
21386                "ActivityRetryScheduled",
21387                json!({
21388                    "sequence": 1,
21389                    "activity_type": "flaky",
21390                    "activity_execution_id": "act-1",
21391                    "activity_attempt_id": "attempt-1",
21392                    "attempt_number": 1,
21393                    "retry_after_attempt": 1,
21394                    "retry_backoff_seconds": 2,
21395                    "failure_category": "activity",
21396                    "exception_type": "TransientError"
21397                }),
21398            ),
21399            history_event(
21400                "ActivityStarted",
21401                json!({
21402                    "sequence": 1,
21403                    "activity_type": "flaky",
21404                    "activity_execution_id": "act-1",
21405                    "activity_attempt_id": "attempt-2",
21406                    "attempt_number": 2
21407                }),
21408            ),
21409            history_event(
21410                "ActivityCompleted",
21411                json!({
21412                    "sequence": 1,
21413                    "activity_type": "flaky",
21414                    "activity_execution_id": "act-1",
21415                    "activity_attempt_id": "attempt-2",
21416                    "attempt_number": 2,
21417                    "payload_codec": DEFAULT_CODEC,
21418                    "result": fixture_envelope(json!({"status":"recovered"}))
21419                }),
21420            ),
21421        ]
21422    }
21423
21424    fn retry_activity_options() -> ActivityOptions {
21425        ActivityOptions::new()
21426            .task_queue("critical-activities")
21427            .retry_policy(
21428                ActivityRetryPolicy::new(3)
21429                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
21430                    .non_retryable_error_type("PermanentError"),
21431            )
21432            .start_to_close_timeout(Duration::from_secs(30))
21433            .schedule_to_start_timeout(Duration::from_secs(5))
21434            .schedule_to_close_timeout(Duration::from_secs(90))
21435            .heartbeat_timeout(Duration::from_secs(10))
21436    }
21437
21438    #[test]
21439    fn fixed_avro_value_round_trips_json_values() {
21440        let value = json!({"greeting": "hello", "count": 3, "ok": true});
21441        let envelope = PayloadEnvelope::avro(&value).expect("encode");
21442        assert_eq!(envelope.codec, DEFAULT_CODEC);
21443        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
21444    }
21445
21446    #[tokio::test]
21447    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
21448        let client = Client::new("http://127.0.0.1:8080").expect("client");
21449        let mut worker = Worker::new(client, "rust-workers");
21450        worker.register_typed_workflow(
21451            "typed.contract.workflow",
21452            |_ctx, input: TypedContract| async move { Ok(input) },
21453        );
21454        worker.register_typed_activity(
21455            "typed.contract.activity",
21456            |_ctx, input: TypedContract| async move { Ok(input) },
21457        );
21458
21459        let expected = typed_contract();
21460        let arguments = AvroValue::Array(vec![
21461            AvroValue::from_serialize(&expected).expect("typed request")
21462        ]);
21463        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
21464        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
21465        workflow.arguments = Some(envelope.clone());
21466        let commands = worker
21467            .execute_workflow_task(workflow)
21468            .expect("typed workflow task");
21469        let workflow_result: TypedContract =
21470            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21471                .expect("workflow result envelope")
21472                .deserialize()
21473                .expect("workflow result type");
21474        assert_eq!(workflow_result, expected);
21475
21476        let activity = ActivityTask {
21477            task_id: "typed-contract-activity".to_string(),
21478            workflow_id: None,
21479            run_id: None,
21480            activity_execution_id: None,
21481            observability_context: None,
21482            dispatch_observability_context: None,
21483            observability_links: None,
21484            activity_attempt_id: Some("typed-contract-attempt".to_string()),
21485            attempt_id: None,
21486            activity_type: "typed.contract.activity".to_string(),
21487            payload_codec: DEFAULT_CODEC.to_string(),
21488            arguments: Some(envelope),
21489            attempt_number: 1,
21490            lease_owner: Some("rust-worker".to_string()),
21491        };
21492        let activity_result: TypedContract = worker
21493            .execute_activity_task(activity)
21494            .await
21495            .expect("typed activity task")
21496            .deserialize()
21497            .expect("activity result type");
21498        assert_eq!(activity_result, expected);
21499    }
21500
21501    #[test]
21502    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
21503        let calls = Arc::new(AtomicUsize::new(0));
21504        let observed = Arc::clone(&calls);
21505        let client = Client::new("http://127.0.0.1:8080").expect("client");
21506        let mut worker = Worker::new(client.clone(), "rust-workers");
21507        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
21508            observed.fetch_add(1, Ordering::SeqCst);
21509            async move { Ok(input) }
21510        });
21511        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
21512        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
21513        let original = task.clone();
21514        let error = worker
21515            .execute_workflow_task(task)
21516            .expect_err("incompatible entry must refuse the task, not fail the run");
21517        assert_eq!(calls.load(Ordering::SeqCst), 0);
21518        assert!(error
21519            .to_string()
21520            .contains("workflow_entry_arguments_mismatch:"));
21521        assert!(!error.to_string().contains("private-original-value"));
21522
21523        let mut compatible = Worker::new(client, "rust-workers");
21524        compatible
21525            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
21526        let commands = compatible
21527            .execute_workflow_task(original)
21528            .expect("same recorded input");
21529        assert_eq!(commands[0]["type"], "complete_workflow");
21530        assert_eq!(
21531            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
21532            json!("private-original-value")
21533        );
21534    }
21535
21536    #[test]
21537    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
21538        let factories = Arc::new(AtomicUsize::new(0));
21539        let observed = Arc::clone(&factories);
21540        let client = Client::new("http://127.0.0.1:8080").expect("client");
21541        let mut worker = Worker::new(client, "rust-workers");
21542        worker.register_typed_replayed_workflow(
21543            "entry.replayed",
21544            move || {
21545                observed.fetch_add(1, Ordering::SeqCst);
21546                ()
21547            },
21548            |_ctx, _input: i64, _state| async move {
21549                panic!("body must not start");
21550                #[allow(unreachable_code)]
21551                Ok(0_i64)
21552            },
21553        );
21554        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
21555        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
21556        let error = worker
21557            .execute_workflow_task(task)
21558            .expect_err("entry refusal");
21559        assert_eq!(factories.load(Ordering::SeqCst), 0);
21560        assert!(error
21561            .to_string()
21562            .contains("workflow_entry_arguments_mismatch:"));
21563        assert!(!error.to_string().contains("private-replayed-value"));
21564
21565        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
21566        let Err(error) = replay(
21567            workflow_context(Vec::new()),
21568            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
21569        ) else {
21570            panic!("query replay must refuse before creating application state");
21571        };
21572        assert_eq!(factories.load(Ordering::SeqCst), 0);
21573        assert!(!error.to_string().contains("private-replayed-value"));
21574    }
21575
21576    #[test]
21577    fn typed_entry_deserializes_once_before_entering_application_code() {
21578        static DECODES: AtomicUsize = AtomicUsize::new(0);
21579        struct Counted(i64);
21580        impl<'de> Deserialize<'de> for Counted {
21581            fn deserialize<D: Deserializer<'de>>(
21582                deserializer: D,
21583            ) -> std::result::Result<Self, D::Error> {
21584                DECODES.fetch_add(1, Ordering::SeqCst);
21585                i64::deserialize(deserializer).map(Self)
21586            }
21587        }
21588        DECODES.store(0, Ordering::SeqCst);
21589        let client = Client::new("http://127.0.0.1:8080").expect("client");
21590        let mut worker = Worker::new(client, "rust-workers");
21591        worker.register_typed_workflow(
21592            "entry.once",
21593            |_ctx, input: Counted| async move { Ok(input.0) },
21594        );
21595        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
21596        task.arguments = Some(fixture_envelope(json!([7])));
21597        let commands = worker.execute_workflow_task(task).expect("typed result");
21598        assert_eq!(commands[0]["type"], "complete_workflow");
21599        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
21600    }
21601
21602    #[test]
21603    fn typed_entry_body_input_error_remains_a_business_failure() {
21604        let client = Client::new("http://127.0.0.1:8080").expect("client");
21605        let mut worker = Worker::new(client, "rust-workers");
21606        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
21607            Err::<i64, _>(handler_type_error::<i64>(
21608                HandlerKind::Workflow,
21609                "entry.body",
21610                HandlerValueKind::Input,
21611                "deliberate body error",
21612            ))
21613        });
21614        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
21615        task.arguments = Some(fixture_envelope(json!([7])));
21616        let commands = worker
21617            .execute_workflow_task(task)
21618            .expect("business failure command");
21619        assert_eq!(commands[0]["type"], "fail_workflow");
21620        assert!(commands[0]["message"]
21621            .as_str()
21622            .unwrap()
21623            .contains("deliberate body error"));
21624    }
21625
21626    #[test]
21627    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
21628        let client = Client::new("http://127.0.0.1:8080").expect("client");
21629        let mut worker = Worker::new(client, "rust-workers");
21630        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
21631            Err::<i64, _>(handler_type_error::<i64>(
21632                HandlerKind::Workflow,
21633                "entry.body.refusal",
21634                HandlerValueKind::Input,
21635                "workflow_entry_arguments_mismatch: deliberate body error",
21636            ))
21637        });
21638        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
21639        task.arguments = Some(fixture_envelope(json!([7])));
21640        let commands = worker
21641            .execute_workflow_task(task)
21642            .expect("business failure");
21643        assert_eq!(commands[0]["type"], "fail_workflow");
21644    }
21645
21646    #[tokio::test]
21647    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21648        let client = Client::new("http://127.0.0.1:8080").expect("client");
21649        let mut worker = Worker::new(client, "rust-workers");
21650        worker.register_typed_workflow(
21651            "typed.shape.workflow",
21652            |_ctx, input: TypedContract| async move { Ok(input) },
21653        );
21654        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21655            Ok(f64::NAN)
21656        });
21657
21658        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21659        workflow.arguments = Some(
21660            encode_typed_envelope(
21661                &AvroValue::Array(vec![
21662                    AvroValue::String("first".to_string()),
21663                    AvroValue::String("second".to_string()),
21664                ]),
21665                DEFAULT_CODEC,
21666            )
21667            .expect("malformed typed arguments"),
21668        );
21669        let error = worker
21670            .execute_workflow_task(workflow)
21671            .expect_err("entry shape mismatch refuses the task");
21672        let message = error.to_string();
21673        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21674        assert!(message.contains("typed.shape.workflow"));
21675        assert!(message.contains(type_name::<TypedContract>()));
21676
21677        let activity = ActivityTask {
21678            task_id: "typed-unsupported-activity".to_string(),
21679            workflow_id: None,
21680            run_id: None,
21681            activity_execution_id: None,
21682            observability_context: None,
21683            dispatch_observability_context: None,
21684            observability_links: None,
21685            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21686            attempt_id: None,
21687            activity_type: "typed.unsupported.activity".to_string(),
21688            payload_codec: DEFAULT_CODEC.to_string(),
21689            arguments: Some(
21690                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21691                    .expect("unit arguments"),
21692            ),
21693            attempt_number: 1,
21694            lease_owner: Some("rust-worker".to_string()),
21695        };
21696        let Error::HandlerType {
21697            handler_kind,
21698            handler_name,
21699            value_kind,
21700            rust_type,
21701            message,
21702        } = worker
21703            .execute_activity_task(activity)
21704            .await
21705            .expect_err("non-finite handler output must fail")
21706        else {
21707            panic!("expected contextual handler type failure");
21708        };
21709        assert_eq!(handler_kind, HandlerKind::Activity);
21710        assert_eq!(handler_name, "typed.unsupported.activity");
21711        assert_eq!(value_kind, HandlerValueKind::Result);
21712        assert_eq!(rust_type, type_name::<f64>());
21713        assert!(message.contains("non_finite_float"));
21714    }
21715
21716    #[tokio::test]
21717    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21718        #[derive(Clone, Default)]
21719        struct State {
21720            observed: Option<TypedContract>,
21721        }
21722
21723        let client = Client::new("http://127.0.0.1:8080").expect("client");
21724        let mut worker = Worker::new(client, "rust-workers");
21725        worker.register_typed_replayed_workflow(
21726            "typed.contract.replayed",
21727            State::default,
21728            |ctx, input: TypedContract, state| async move {
21729                let result: TypedContract =
21730                    ctx.activity_typed("typed.contract.activity", input).await?;
21731                state.update(|current| current.observed = Some(result.clone()))?;
21732                Ok(result)
21733            },
21734        );
21735        worker.register_replayed_query::<State, _, _>(
21736            "typed.contract.replayed",
21737            "observed",
21738            |_ctx, state, _args| async move {
21739                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21740            },
21741        );
21742
21743        let expected = typed_contract();
21744        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21745        let workflow_arguments =
21746            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21747                .expect("workflow arguments");
21748        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21749        let task = QueryTask {
21750            query_task_id: "typed-replay-query".to_string(),
21751            observability_context: None,
21752            dispatch_observability_context: None,
21753            observability_links: None,
21754            query_task_attempt: 1,
21755            lease_owner: Some("rust-worker".to_string()),
21756            workflow_id: Some("typed-replay".to_string()),
21757            run_id: Some("typed-replay-run".to_string()),
21758            workflow_type: "typed.contract.replayed".to_string(),
21759            query_name: "observed".to_string(),
21760            payload_codec: DEFAULT_CODEC.to_string(),
21761            workflow_arguments: Some(workflow_arguments),
21762            query_arguments: Some(
21763                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21764                    .expect("query arguments"),
21765            ),
21766            history_events: vec![
21767                history_event(
21768                    "ActivityScheduled",
21769                    json!({
21770                        "sequence": 1,
21771                        "activity_type": "typed.contract.activity"
21772                    }),
21773                ),
21774                history_event(
21775                    "ActivityCompleted",
21776                    json!({
21777                        "sequence": 1,
21778                        "activity_type": "typed.contract.activity",
21779                        "payload_codec": DEFAULT_CODEC,
21780                        "result": result
21781                    }),
21782                ),
21783            ],
21784            history_export: None,
21785            run_status: Some("completed".to_string()),
21786        };
21787
21788        assert_eq!(
21789            worker
21790                .execute_query_task(task)
21791                .await
21792                .expect("typed replay query")
21793                .deserialize::<i64>()
21794                .expect("query result"),
21795            expected.signed
21796        );
21797    }
21798
21799    #[tokio::test]
21800    async fn update_context_preserves_workflow_input_and_committed_signals() {
21801        let client = Client::new("http://127.0.0.1:8080").expect("client");
21802        let mut worker = Worker::new(client, "rust-workers");
21803        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21804        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21805        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21806        let expected_input = workflow_input.clone();
21807        let expected_signals = signal_arguments.clone();
21808        let handler = move |context: QueryContext, arguments: AvroValue| {
21809            let expected_input = expected_input.clone();
21810            let expected_signals = expected_signals.clone();
21811            async move {
21812                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21813                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21814                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21815                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21816                assert_eq!(
21817                    context.signals_avro_value("changed"),
21818                    vec![expected_signals.clone()]
21819                );
21820                assert_eq!(
21821                    context.signals("changed"),
21822                    vec![expected_signals
21823                        .into_iter()
21824                        .map(AvroValue::into_json)
21825                        .collect::<Result<Vec<_>>>()?]
21826                );
21827                assert_eq!(
21828                    context.signal_events()[0].id.as_deref(),
21829                    Some("signal-original")
21830                );
21831                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21832                Ok(arguments)
21833            }
21834        };
21835        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21836        worker.register_update_avro_value("snapshot", "inspect", handler);
21837        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21838        let update_envelope =
21839            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21840        let mut task = workflow_task(
21841            "snapshot",
21842            vec![
21843                history_event(
21844                    "SignalReceived",
21845                    json!({
21846                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21847                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21848                    }),
21849                ),
21850                history_event(
21851                    "UpdateAccepted",
21852                    json!({
21853                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21854                    }),
21855                ),
21856            ],
21857            DEFAULT_CODEC,
21858        );
21859        task.arguments =
21860            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21861        task.workflow_update_id = Some("update-original".into());
21862        task.update_name = Some("inspect".into());
21863        let query = QueryTask {
21864            query_task_id: "query-snapshot".into(),
21865            observability_context: None,
21866            dispatch_observability_context: None,
21867            observability_links: None,
21868            query_task_attempt: 1,
21869            lease_owner: None,
21870            workflow_id: task.workflow_id.clone(),
21871            run_id: task.run_id.clone(),
21872            workflow_type: task.workflow_type.clone(),
21873            query_name: "inspect".into(),
21874            payload_codec: DEFAULT_CODEC.into(),
21875            workflow_arguments: task.arguments.clone(),
21876            query_arguments: Some(update_envelope),
21877            history_events: task.history_events.clone(),
21878            history_export: None,
21879            run_status: Some("running".into()),
21880        };
21881        assert_eq!(
21882            worker
21883                .execute_query_task(query)
21884                .await
21885                .expect("query snapshot"),
21886            update_arguments
21887        );
21888        for _ in 0..2 {
21889            let commands = worker
21890                .execute_workflow_task(task.clone())
21891                .expect("cold update snapshot");
21892            assert_eq!(commands[0]["type"], "complete_update");
21893            assert_eq!(commands[0]["update_id"], "update-original");
21894            assert_eq!(
21895                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21896                    .expect("update result"),
21897                update_arguments
21898            );
21899        }
21900    }
21901
21902    #[test]
21903    fn committed_signal_snapshot_counts_identities_once() {
21904        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21905        let received = history_event(
21906            "SignalReceived",
21907            json!({
21908                "signal_id": "signal-first", "workflow_command_id": "command-first",
21909                "signal_name": "changed", "arguments": arguments.clone(),
21910            }),
21911        );
21912        let applied = history_event(
21913            "SignalApplied",
21914            json!({
21915                "signal_id": "signal-first", "workflow_command_id": "command-first",
21916                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21917            }),
21918        );
21919        let distinct = history_event(
21920            "SignalReceived",
21921            json!({
21922                "signal_id": "signal-second", "workflow_command_id": "command-second",
21923                "signal_name": "changed", "arguments": arguments,
21924            }),
21925        );
21926        let history = vec![received.clone(), applied.clone(), distinct];
21927        let signals =
21928            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21929        assert_eq!(signals.len(), 2);
21930        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21931        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21932        assert_eq!(signals[0].workflow_sequence, Some(1));
21933        assert_eq!(signals[0].arguments, signals[1].arguments);
21934        let mut command_only = received.clone();
21935        command_only
21936            .payload
21937            .as_object_mut()
21938            .expect("payload")
21939            .remove("signal_id");
21940        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21941            .expect("command identity");
21942        assert_eq!(signals.len(), 1);
21943        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21944        let mut conflicting = applied;
21945        conflicting.payload["value"] =
21946            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21947        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21948    }
21949
21950    #[test]
21951    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21952        for arguments in [
21953            vec![],
21954            vec![AvroValue::Array(vec![
21955                AvroValue::Long(1),
21956                AvroValue::Long(2),
21957            ])],
21958            vec![AvroValue::Bytes(vec![0, 255])],
21959            vec![AvroValue::Null],
21960            vec![AvroValue::Boolean(false)],
21961            vec![
21962                AvroValue::Long(1),
21963                AvroValue::Array(vec![AvroValue::Long(2)]),
21964            ],
21965        ] {
21966            let applied = match arguments.as_slice() {
21967                [] => AvroValue::Boolean(true),
21968                [value] => value.clone(),
21969                values => AvroValue::Array(values.to_vec()),
21970            };
21971            for applied in [applied, AvroValue::Array(arguments.clone())] {
21972                let events = vec![
21973                    history_event(
21974                        "SignalReceived",
21975                        json!({
21976                            "signal_id": "original", "signal_name": "changed",
21977                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
21978                        }),
21979                    ),
21980                    history_event(
21981                        "SignalApplied",
21982                        json!({
21983                            "signal_id": "original", "signal_name": "changed",
21984                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
21985                        }),
21986                    ),
21987                ];
21988                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
21989                    .expect("canonical signal snapshot");
21990                assert_eq!(signals.len(), 1);
21991                assert_eq!(signals[0].avro_arguments, arguments);
21992            }
21993        }
21994    }
21995
21996    #[tokio::test]
21997    async fn update_context_rejects_malformed_snapshot_before_handler() {
21998        let client = Client::new("http://127.0.0.1:8080").expect("client");
21999        let mut worker = Worker::new(client, "rust-workers");
22000        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
22001        let calls = Arc::new(AtomicUsize::new(0));
22002        let observed = Arc::clone(&calls);
22003        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
22004            observed.fetch_add(1, Ordering::SeqCst);
22005            async { Ok(Value::Null) }
22006        });
22007        let mut task = workflow_task(
22008            "snapshot",
22009            vec![history_event(
22010                "UpdateAccepted",
22011                json!({
22012                    "update_id": "update-original", "update_name": "inspect",
22013                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
22014                }),
22015            )],
22016            DEFAULT_CODEC,
22017        );
22018        task.workflow_update_id = Some("update-original".into());
22019        task.update_name = Some("inspect".into());
22020        let mut bad_input = task.clone();
22021        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
22022        assert!(worker.execute_workflow_task(bad_input).is_err());
22023        task.history_events.insert(0, history_event("SignalReceived", json!({
22024            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
22025        })));
22026        assert!(worker.execute_workflow_task(task).is_err());
22027        assert_eq!(calls.load(Ordering::SeqCst), 0);
22028    }
22029
22030    #[tokio::test]
22031    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
22032        let client = Client::new("http://127.0.0.1:8080").expect("client");
22033        let mut worker = Worker::new(client, "rust-workers");
22034        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
22035        worker
22036            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
22037        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
22038            Ok(input)
22039        });
22040        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
22041            Ok(input)
22042        });
22043        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
22044            Ok(AvroValue::Array(
22045                ctx.wait_signal_avro_value("changed").await?,
22046            ))
22047        });
22048
22049        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
22050        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
22051
22052        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
22053        workflow.arguments = Some(envelope.clone());
22054        let commands = worker
22055            .execute_workflow_task(workflow)
22056            .expect("typed workflow task");
22057        assert_eq!(commands[0]["type"], "complete_workflow");
22058        assert_eq!(
22059            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22060                .expect("typed workflow result"),
22061            arguments
22062        );
22063
22064        let activity = ActivityTask {
22065            task_id: "activity-typed".to_string(),
22066            workflow_id: None,
22067            run_id: None,
22068            activity_execution_id: None,
22069            observability_context: None,
22070            dispatch_observability_context: None,
22071            observability_links: None,
22072            activity_attempt_id: Some("attempt-typed".to_string()),
22073            attempt_id: None,
22074            activity_type: "typed.activity".to_string(),
22075            payload_codec: DEFAULT_CODEC.to_string(),
22076            arguments: Some(envelope.clone()),
22077            attempt_number: 1,
22078            lease_owner: Some("rust-worker".to_string()),
22079        };
22080        assert_eq!(
22081            worker
22082                .execute_activity_task(activity)
22083                .await
22084                .expect("typed activity result"),
22085            arguments
22086        );
22087
22088        let query = QueryTask {
22089            query_task_id: "query-typed".to_string(),
22090            observability_context: None,
22091            dispatch_observability_context: None,
22092            observability_links: None,
22093            query_task_attempt: 1,
22094            lease_owner: Some("rust-worker".to_string()),
22095            workflow_id: Some("typed-1".to_string()),
22096            run_id: Some("run-typed".to_string()),
22097            workflow_type: "typed.echo".to_string(),
22098            query_name: "inspect".to_string(),
22099            payload_codec: DEFAULT_CODEC.to_string(),
22100            workflow_arguments: Some(
22101                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22102                    .expect("workflow input"),
22103            ),
22104            query_arguments: Some(envelope.clone()),
22105            history_events: Vec::new(),
22106            history_export: None,
22107            run_status: Some("running".to_string()),
22108        };
22109        assert_eq!(
22110            worker
22111                .execute_query_task(query)
22112                .await
22113                .expect("typed query result"),
22114            arguments
22115        );
22116
22117        let mut update = workflow_task(
22118            "typed.echo",
22119            vec![history_event(
22120                "UpdateAccepted",
22121                json!({
22122                    "update_id": "update-typed",
22123                    "update_name": "replace",
22124                    "arguments": envelope.clone(),
22125                }),
22126            )],
22127            DEFAULT_CODEC,
22128        );
22129        update.workflow_update_id = Some("update-typed".to_string());
22130        update.update_name = Some("replace".to_string());
22131        let commands = worker
22132            .execute_workflow_task(update)
22133            .expect("typed update task");
22134        assert_eq!(commands[0]["type"], "complete_update");
22135        assert_eq!(
22136            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22137                .expect("typed update result"),
22138            arguments
22139        );
22140
22141        let mut signal = workflow_task(
22142            "typed.signal",
22143            vec![history_event(
22144                "SignalReceived",
22145                json!({
22146                    "signal_id": "signal-typed",
22147                    "signal_name": "changed",
22148                    "arguments": envelope.clone(),
22149                }),
22150            )],
22151            DEFAULT_CODEC,
22152        );
22153        signal.workflow_signal_id = Some("signal-typed".to_string());
22154        signal.signal_name = Some("changed".to_string());
22155        signal.signal_arguments = Some(envelope);
22156        let commands = worker
22157            .execute_workflow_task(signal)
22158            .expect("typed signal resume");
22159        assert_eq!(
22160            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22161                .expect("typed signal result"),
22162            arguments
22163        );
22164    }
22165
22166    #[tokio::test]
22167    async fn typed_helpers_never_parse_json_inspection_projection() {
22168        let collision_values = projection_collision_probe();
22169        let expected = AvroValue::Array(collision_values.clone());
22170        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
22171
22172        let activity_context = workflow_context_with_codec(
22173            vec![history_event(
22174                "ActivityCompleted",
22175                json!({
22176                    "sequence": 1,
22177                    "activity_type": "collision.activity",
22178                    "payload_codec": DEFAULT_CODEC,
22179                    "result": envelope.clone(),
22180                }),
22181            )],
22182            DEFAULT_CODEC,
22183        );
22184        assert_eq!(
22185            activity_context
22186                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
22187                .await
22188                .expect("typed activity collision result"),
22189            expected
22190        );
22191
22192        let signal_context = workflow_context_with_codec(
22193            vec![
22194                history_event(
22195                    "SignalWaitOpened",
22196                    json!({"sequence": 1, "signal_name": "collision"}),
22197                ),
22198                history_event(
22199                    "SignalApplied",
22200                    json!({
22201                        "sequence": 1,
22202                        "signal_name": "collision",
22203                        "payload_codec": DEFAULT_CODEC,
22204                        "value": envelope.clone(),
22205                    }),
22206                ),
22207            ],
22208            DEFAULT_CODEC,
22209        );
22210        assert_eq!(
22211            signal_context
22212                .wait_signal_avro_value("collision")
22213                .await
22214                .expect("typed signal collision arguments"),
22215            collision_values
22216        );
22217
22218        let child_context = workflow_context_with_codec(
22219            vec![
22220                history_event(
22221                    "ChildWorkflowScheduled",
22222                    json!({
22223                        "sequence": 1,
22224                        "child_workflow_instance_id": "collision-child",
22225                        "child_workflow_run_id": "collision-run",
22226                        "child_workflow_type": "collision.child",
22227                    }),
22228                ),
22229                history_event(
22230                    "ChildRunCompleted",
22231                    json!({
22232                        "sequence": 1,
22233                        "child_workflow_instance_id": "collision-child",
22234                        "child_workflow_run_id": "collision-run",
22235                        "child_workflow_type": "collision.child",
22236                        "payload_codec": DEFAULT_CODEC,
22237                        "result": envelope,
22238                    }),
22239                ),
22240            ],
22241            DEFAULT_CODEC,
22242        );
22243        let child = child_context
22244            .start_child_workflow_avro_value(
22245                "collision.child",
22246                ChildWorkflowOptions::new("collision-workers"),
22247                AvroValue::Array(Vec::new()),
22248            )
22249            .await
22250            .expect("typed child collision result");
22251        assert_eq!(child.result, expected);
22252    }
22253
22254    #[tokio::test]
22255    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
22256        let client = Client::new("http://127.0.0.1:8080").expect("client");
22257        let mut worker = Worker::new(client, "rust-workers");
22258        worker.register_replayed_workflow_avro_value(
22259            "typed.replayed",
22260            || (),
22261            |_ctx, input, _state| async move { Ok(input) },
22262        );
22263        worker.register_replayed_query_avro_value::<(), _, _>(
22264            "typed.replayed",
22265            "inspect",
22266            |ctx, _state, args| async move {
22267                let mut signals = ctx.signals_avro_value("collision");
22268                let signal = signals
22269                    .pop()
22270                    .map(AvroValue::Array)
22271                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
22272                Ok(AvroValue::Array(vec![
22273                    ctx.workflow_input_avro_value().clone(),
22274                    signal,
22275                    args,
22276                ]))
22277            },
22278        );
22279        let arguments = AvroValue::Array(projection_collision_probe());
22280        let signal_arguments =
22281            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
22282        let task = QueryTask {
22283            query_task_id: "query-typed-replay".to_string(),
22284            observability_context: None,
22285            dispatch_observability_context: None,
22286            observability_links: None,
22287            query_task_attempt: 1,
22288            lease_owner: Some("rust-worker".to_string()),
22289            workflow_id: Some("typed-replay".to_string()),
22290            run_id: Some("run-typed-replay".to_string()),
22291            workflow_type: "typed.replayed".to_string(),
22292            query_name: "inspect".to_string(),
22293            payload_codec: DEFAULT_CODEC.to_string(),
22294            workflow_arguments: Some(
22295                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
22296            ),
22297            query_arguments: Some(
22298                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
22299            ),
22300            history_events: vec![history_event(
22301                "SignalReceived",
22302                json!({
22303                    "signal_id": "collision-signal",
22304                    "signal_name": "collision",
22305                    "workflow_sequence": 1,
22306                    "payload_codec": DEFAULT_CODEC,
22307                    "arguments": signal_arguments,
22308                }),
22309            )],
22310            history_export: None,
22311            run_status: Some("completed".to_string()),
22312        };
22313
22314        assert_eq!(
22315            worker
22316                .execute_query_task(task)
22317                .await
22318                .expect("typed replay query"),
22319            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
22320        );
22321    }
22322
22323    #[test]
22324    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
22325        let value = BTreeMap::from([(1_i32, "integer key")]);
22326        let error = PayloadEnvelope::avro(&value)
22327            .expect_err("integer map keys must fail")
22328            .to_string();
22329
22330        assert!(error.contains("invalid_map_key"));
22331    }
22332
22333    #[test]
22334    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
22335        let envelope = PayloadEnvelope {
22336            codec: "json".to_string(),
22337            blob: r#"{"greeting":"hello"}"#.to_string(),
22338        };
22339
22340        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
22341        let diagnostic = error.to_string();
22342        assert!(diagnostic.contains("unsupported_payload_codec"));
22343        assert!(diagnostic.contains("codec=\"avro\""));
22344        assert!(diagnostic.contains("HTTP document transport"));
22345    }
22346
22347    #[test]
22348    fn untagged_json_payload_value_fails_closed() {
22349        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
22350            .expect_err("untagged JSON payload values must fail");
22351        let diagnostic = error.to_string();
22352        assert!(diagnostic.contains("unsupported_payload_codec"));
22353        assert!(diagnostic.contains("untagged durable payload"));
22354        assert!(diagnostic.contains("HTTP document transport"));
22355    }
22356
22357    #[test]
22358    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
22359        let envelope = PayloadEnvelope {
22360            codec: DEFAULT_CODEC.to_string(),
22361            blob: BASE64.encode([0x01]),
22362        };
22363
22364        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
22365        assert!(error.to_string().contains("invalid_payload_framing"));
22366    }
22367
22368    #[tokio::test]
22369    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
22370        let server = MockWorkerServer::start();
22371        let client = Client::builder(server.base_url())
22372            .timeout(Duration::from_secs(2))
22373            .build()
22374            .expect("client");
22375        let invalid_commands = [
22376            json!({
22377                "type": "complete_workflow",
22378                "result": {"codec": "json", "blob": null}
22379            }),
22380            json!({
22381                "type": "schedule_activity",
22382                "arguments": {"codec": "yaml", "blob": "ignored"}
22383            }),
22384            json!({
22385                "type": "start_child_workflow",
22386                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
22387            }),
22388            json!({"type": "continue_as_new", "arguments": []}),
22389            json!({"type": "complete_update"}),
22390            json!({"type": "record_side_effect", "result": null}),
22391            json!({
22392                "type": "start_service_operation",
22393                "payload_codec": DEFAULT_CODEC,
22394                "request_payload": "raw-avro-bytes"
22395            }),
22396        ];
22397
22398        for command in invalid_commands {
22399            let error = client
22400                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
22401                .await
22402                .expect_err("invalid durable payload must fail locally");
22403            let diagnostic = error.to_string();
22404            assert!(
22405                diagnostic.contains("unsupported_payload_codec")
22406                    || diagnostic.contains("invalid_payload_envelope")
22407                    || diagnostic.contains("untagged durable payload"),
22408                "unexpected validation diagnostic: {diagnostic}"
22409            );
22410        }
22411
22412        assert_eq!(
22413            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
22414            0,
22415            "invalid command payloads must not reach HTTP transport"
22416        );
22417    }
22418
22419    #[test]
22420    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
22421        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
22422        let commands = [
22423            json!({"type": "complete_workflow", "result": envelope.clone()}),
22424            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
22425            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
22426            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
22427            json!({"type": "complete_update", "result": envelope.clone()}),
22428            json!({"type": "record_side_effect", "result": envelope.clone()}),
22429            json!({
22430                "type": "start_service_operation",
22431                "payload_codec": DEFAULT_CODEC,
22432                "request_payload": envelope.clone()
22433            }),
22434            json!({
22435                "type": "complete_workflow",
22436                "result": envelope,
22437                "metadata": {
22438                    "codec": "json",
22439                    "payload_codec": "customer-codec",
22440                    "result": {"codec": "yaml", "blob": null}
22441                }
22442            }),
22443        ];
22444
22445        validate_workflow_task_commands(&commands)
22446            .expect("customer metadata must not become a protocol codec declaration");
22447    }
22448
22449    #[test]
22450    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
22451        assert_eq!(
22452            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
22453            AvroValue::Array(Vec::new())
22454        );
22455        assert_eq!(
22456            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
22457            AvroValue::Array(Vec::new())
22458        );
22459
22460        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22461        signal.signal_name = Some("empty-signal".to_string());
22462        signal.signal_arguments = None;
22463        let decoded = decode_resume_signal(&signal)
22464            .expect("valid Avro signal")
22465            .expect("named signal resumes the workflow");
22466        assert!(decoded.arguments.is_empty());
22467    }
22468
22469    #[tokio::test]
22470    async fn malformed_task_level_codecs_become_pre_handler_failures() {
22471        let client = Client::new("http://127.0.0.1:8080").expect("client");
22472        let mut worker = Worker::new(client, "rust-workers");
22473        let handler_calls = Arc::new(AtomicUsize::new(0));
22474
22475        let calls = Arc::clone(&handler_calls);
22476        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22477            calls.fetch_add(1, Ordering::SeqCst);
22478            async move { Ok(Value::Null) }
22479        });
22480        let calls = Arc::clone(&handler_calls);
22481        worker.register_activity("codec.activity", move |_ctx, _args| {
22482            calls.fetch_add(1, Ordering::SeqCst);
22483            async move { Ok(Value::Null) }
22484        });
22485        let calls = Arc::clone(&handler_calls);
22486        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22487            calls.fetch_add(1, Ordering::SeqCst);
22488            async move { Ok(Value::Null) }
22489        });
22490
22491        let mut failures = Vec::new();
22492        for codec_case in [
22493            InvalidTaskPayloadCodec::Missing,
22494            InvalidTaskPayloadCodec::Null,
22495            InvalidTaskPayloadCodec::NonString,
22496        ] {
22497            let mut workflow = json!({
22498                "task_id": format!("workflow-{}", codec_case.label()),
22499                "workflow_type": "codec.workflow"
22500            });
22501            codec_case.apply(&mut workflow);
22502            match serde_json::from_value::<WorkflowTask>(workflow) {
22503                Ok(task) => match worker.execute_workflow_task(task) {
22504                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22505                    outcome => failures.push(format!(
22506                        "workflow {} codec returned {outcome:?}",
22507                        codec_case.label()
22508                    )),
22509                },
22510                Err(error) => failures.push(format!(
22511                    "workflow {} codec failed transport deserialization: {error}",
22512                    codec_case.label()
22513                )),
22514            }
22515
22516            let mut activity = json!({
22517                "task_id": format!("activity-{}", codec_case.label()),
22518                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
22519                "activity_type": "codec.activity",
22520                "attempt_number": 1
22521            });
22522            codec_case.apply(&mut activity);
22523            match serde_json::from_value::<ActivityTask>(activity) {
22524                Ok(task) => match worker.execute_activity_task(task).await {
22525                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22526                    outcome => failures.push(format!(
22527                        "activity {} codec returned {outcome:?}",
22528                        codec_case.label()
22529                    )),
22530                },
22531                Err(error) => failures.push(format!(
22532                    "activity {} codec failed transport deserialization: {error}",
22533                    codec_case.label()
22534                )),
22535            }
22536
22537            let mut query = json!({
22538                "query_task_id": format!("query-{}", codec_case.label()),
22539                "workflow_type": "codec.workflow",
22540                "query_name": "known"
22541            });
22542            codec_case.apply(&mut query);
22543            match serde_json::from_value::<QueryTask>(query) {
22544                Ok(task) => match worker.execute_query_task(task).await {
22545                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
22546                    outcome => failures.push(format!(
22547                        "query {} codec returned {outcome:?}",
22548                        codec_case.label()
22549                    )),
22550                },
22551                Err(error) => failures.push(format!(
22552                    "query {} codec failed transport deserialization: {error}",
22553                    codec_case.label()
22554                )),
22555            }
22556        }
22557
22558        assert!(failures.is_empty(), "{}", failures.join("\n"));
22559        assert_eq!(
22560            handler_calls.load(Ordering::SeqCst),
22561            0,
22562            "invalid task codecs must not invoke a handler"
22563        );
22564    }
22565
22566    #[tokio::test]
22567    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
22568        for codec_case in [
22569            InvalidTaskPayloadCodec::Missing,
22570            InvalidTaskPayloadCodec::Null,
22571            InvalidTaskPayloadCodec::NonString,
22572        ] {
22573            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
22574            let client = Client::builder(server.base_url())
22575                .timeout(Duration::from_secs(2))
22576                .build()
22577                .expect("client");
22578            let mut worker = Worker::new(client, "rust-workers")
22579                .worker_id("codec-worker")
22580                .poll_timeout(Duration::from_millis(10));
22581            let handler_calls = Arc::new(AtomicUsize::new(0));
22582
22583            let calls = Arc::clone(&handler_calls);
22584            worker.register_workflow("codec.workflow", move |_ctx, _args| {
22585                calls.fetch_add(1, Ordering::SeqCst);
22586                async move { Ok(Value::Null) }
22587            });
22588            let calls = Arc::clone(&handler_calls);
22589            worker.register_activity("codec.activity", move |_ctx, _args| {
22590                calls.fetch_add(1, Ordering::SeqCst);
22591                async move { Ok(Value::Null) }
22592            });
22593            let calls = Arc::clone(&handler_calls);
22594            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22595                calls.fetch_add(1, Ordering::SeqCst);
22596                async move { Ok(Value::Null) }
22597            });
22598
22599            assert_eq!(
22600                worker.run_once().await.expect("invalid tasks are settled"),
22601                3,
22602                "all {} codec tasks must be handled",
22603                codec_case.label()
22604            );
22605            assert_eq!(
22606                handler_calls.load(Ordering::SeqCst),
22607                0,
22608                "{} task codecs must fail before every handler",
22609                codec_case.label()
22610            );
22611
22612            for path in [
22613                "/api/worker/workflow-tasks/codec-workflow/fail",
22614                "/api/worker/activity-tasks/codec-activity/fail",
22615                "/api/worker/query-tasks/codec-query/fail",
22616            ] {
22617                let body = server.request_body(path);
22618                assert!(
22619                    body["failure"]["message"]
22620                        .as_str()
22621                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
22622                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
22623                    codec_case.label()
22624                );
22625            }
22626            assert_eq!(
22627                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
22628                    ["reason"],
22629                "query_payload_decode_failed"
22630            );
22631            for path in [
22632                "/api/worker/workflow-tasks/codec-workflow/complete",
22633                "/api/worker/activity-tasks/codec-activity/complete",
22634                "/api/worker/query-tasks/codec-query/complete",
22635            ] {
22636                assert_eq!(
22637                    server.request_count(path),
22638                    0,
22639                    "invalid {} codec task reached {path}",
22640                    codec_case.label()
22641                );
22642            }
22643        }
22644    }
22645
22646    #[tokio::test]
22647    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22648        let client = Client::new("http://127.0.0.1:8080").expect("client");
22649        let mut worker = Worker::new(client, "rust-workers");
22650        let handler_calls = Arc::new(AtomicUsize::new(0));
22651
22652        let calls = Arc::clone(&handler_calls);
22653        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22654            calls.fetch_add(1, Ordering::SeqCst);
22655            async move { Ok(Value::Null) }
22656        });
22657        let calls = Arc::clone(&handler_calls);
22658        worker.register_activity("codec.activity", move |_ctx, _args| {
22659            calls.fetch_add(1, Ordering::SeqCst);
22660            async move { Ok(Value::Null) }
22661        });
22662        let calls = Arc::clone(&handler_calls);
22663        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22664            calls.fetch_add(1, Ordering::SeqCst);
22665            async move { Ok(Value::Null) }
22666        });
22667        let calls = Arc::clone(&handler_calls);
22668        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22669            calls.fetch_add(1, Ordering::SeqCst);
22670            async move { Ok(Value::Null) }
22671        });
22672
22673        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22674        workflow.payload_codec = "json".to_string();
22675        workflow.arguments = None;
22676        let error = worker
22677            .execute_workflow_task(workflow)
22678            .expect_err("task codec must be checked before workflow invocation");
22679        assert!(error.to_string().contains("unsupported_payload_codec"));
22680
22681        let activity = ActivityTask {
22682            task_id: "activity-invalid-codec".to_string(),
22683            workflow_id: None,
22684            run_id: None,
22685            activity_execution_id: None,
22686            observability_context: None,
22687            dispatch_observability_context: None,
22688            observability_links: None,
22689            activity_attempt_id: None,
22690            attempt_id: None,
22691            activity_type: "codec.activity".to_string(),
22692            payload_codec: "unknown".to_string(),
22693            arguments: None,
22694            attempt_number: 1,
22695            lease_owner: None,
22696        };
22697        let error = worker
22698            .execute_activity_task(activity)
22699            .await
22700            .expect_err("task codec must be checked before activity invocation");
22701        assert!(error.to_string().contains("unsupported_payload_codec"));
22702
22703        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22704        update.workflow_update_id = Some("update-invalid-codec".to_string());
22705        update.update_name = Some("known".to_string());
22706        update.history_events.push(history_event(
22707            "UpdateAccepted",
22708            json!({
22709                "update_id": "update-invalid-codec",
22710                "update_name": "known",
22711                "arguments": {"codec": "json", "blob": null}
22712            }),
22713        ));
22714        let error = worker
22715            .execute_workflow_task(update)
22716            .expect_err("nested update codec must be checked before handler lookup");
22717        assert!(error.to_string().contains("unsupported_payload_codec"));
22718
22719        let query: QueryTask = serde_json::from_value(json!({
22720            "query_task_id": "query-invalid-codec",
22721            "workflow_type": "codec.workflow",
22722            "query_name": "known",
22723            "payload_codec": DEFAULT_CODEC,
22724            "workflow_arguments": null,
22725            "query_arguments": null,
22726            "history_export": {
22727                "payloads": {"codec": DEFAULT_CODEC},
22728                "signals": [{
22729                    "name": "empty",
22730                    "payload_codec": "json",
22731                    "arguments": null
22732                }]
22733            }
22734        }))
22735        .expect("query task");
22736        let failure = worker
22737            .execute_query_task(query)
22738            .await
22739            .expect_err("exported signal codec must be checked before query invocation");
22740        assert_eq!(failure.reason, "query_payload_decode_failed");
22741        assert!(failure.message.contains("unsupported_payload_codec"));
22742
22743        let exported_history: QueryTask = serde_json::from_value(json!({
22744            "query_task_id": "query-invalid-history-codec",
22745            "workflow_type": "codec.workflow",
22746            "query_name": "known",
22747            "payload_codec": DEFAULT_CODEC,
22748            "history_export": {
22749                "payloads": {"codec": DEFAULT_CODEC},
22750                "history_events": [{
22751                    "type": "ActivityCompleted",
22752                    "payload": {"payload_codec": "unknown", "result": null}
22753                }]
22754            }
22755        }))
22756        .expect("query task");
22757        let failure = worker
22758            .execute_query_task(exported_history)
22759            .await
22760            .expect_err("exported history codec must be checked before query invocation");
22761        assert_eq!(failure.reason, "query_payload_decode_failed");
22762        assert!(failure.message.contains("unsupported_payload_codec"));
22763        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22764
22765        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22766        unknown_workflow.arguments = None;
22767        unknown_workflow.history_events.push(history_event(
22768            "SignalReceived",
22769            json!({
22770                "signal_name": "empty",
22771                "payload_codec": "json",
22772                "arguments": null
22773            }),
22774        ));
22775        let error = worker
22776            .execute_workflow_task(unknown_workflow)
22777            .expect_err("history codec must precede unknown workflow outcome");
22778        assert!(error.to_string().contains("unsupported_payload_codec"));
22779
22780        let unknown_activity = ActivityTask {
22781            task_id: "activity-unknown".to_string(),
22782            workflow_id: None,
22783            run_id: None,
22784            activity_execution_id: None,
22785            observability_context: None,
22786            dispatch_observability_context: None,
22787            observability_links: None,
22788            activity_attempt_id: None,
22789            attempt_id: None,
22790            activity_type: "missing".to_string(),
22791            payload_codec: "json".to_string(),
22792            arguments: None,
22793            attempt_number: 1,
22794            lease_owner: None,
22795        };
22796        let error = worker
22797            .execute_activity_task(unknown_activity)
22798            .await
22799            .expect_err("codec must precede unknown activity outcome");
22800        assert!(error.to_string().contains("unsupported_payload_codec"));
22801
22802        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22803        unknown_update.payload_codec = "json".to_string();
22804        unknown_update.arguments = None;
22805        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22806        unknown_update.update_name = Some("missing".to_string());
22807        let error = worker
22808            .execute_workflow_task(unknown_update)
22809            .expect_err("codec must precede fail_update shortcut");
22810        assert!(error.to_string().contains("unsupported_payload_codec"));
22811
22812        let unknown_query: QueryTask = serde_json::from_value(json!({
22813            "query_task_id": "query-unknown",
22814            "workflow_type": "missing",
22815            "query_name": "missing",
22816            "payload_codec": "json",
22817            "workflow_arguments": null,
22818            "query_arguments": null
22819        }))
22820        .expect("query task");
22821        let failure = worker
22822            .execute_query_task(unknown_query)
22823            .await
22824            .expect_err("codec must precede unknown query outcome");
22825        assert_eq!(failure.reason, "query_payload_decode_failed");
22826        assert!(failure.message.contains("unsupported_payload_codec"));
22827    }
22828
22829    #[tokio::test]
22830    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22831        let client = Client::new("http://127.0.0.1:8080").expect("client");
22832        let worker = Worker::new(client, "rust-workers");
22833
22834        for event_type in ["SignalReceived", "SignalApplied"] {
22835            for (payload_field, codec) in [
22836                ("value", "json"),
22837                ("input", "unknown"),
22838                ("arguments", "json"),
22839            ] {
22840                let payload = json!({
22841                    "signal_name": "empty",
22842                    payload_field: {"codec": codec, "blob": null}
22843                });
22844                let workflow = workflow_task(
22845                    "missing",
22846                    vec![history_event(event_type, payload.clone())],
22847                    DEFAULT_CODEC,
22848                );
22849                let error = worker
22850                    .execute_workflow_task(workflow)
22851                    .expect_err("signal payload codec must precede unknown workflow outcome");
22852                assert!(
22853                    error.to_string().contains("unsupported_payload_codec"),
22854                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22855                );
22856
22857                let query: QueryTask = serde_json::from_value(json!({
22858                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22859                    "workflow_type": "missing",
22860                    "query_name": "missing",
22861                    "payload_codec": DEFAULT_CODEC,
22862                    "workflow_arguments": null,
22863                    "query_arguments": null,
22864                    "history_events": [{
22865                        "event_type": event_type,
22866                        "payload": payload
22867                    }]
22868                }))
22869                .expect("query task");
22870                let failure = worker
22871                    .execute_query_task(query)
22872                    .await
22873                    .expect_err("signal payload codec must precede unknown query outcome");
22874                assert_eq!(
22875                    failure.reason, "query_payload_decode_failed",
22876                    "{event_type}.{payload_field} returned an unrelated query outcome"
22877                );
22878                assert!(
22879                    failure.message.contains("unsupported_payload_codec"),
22880                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22881                    failure.message
22882                );
22883            }
22884        }
22885    }
22886
22887    #[test]
22888    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22889        let ctx = WorkflowContext {
22890            cancellation_scope_id: "root".into(),
22891            state: Arc::new(Mutex::new(
22892                WorkflowState::new_with_identity(
22893                    Vec::new(),
22894                    Some("wf-parent".to_string()),
22895                    Some("run-parent".to_string()),
22896                    "rust-workers".to_string(),
22897                    DEFAULT_CODEC.to_string(),
22898                    None,
22899                )
22900                .expect("workflow state"),
22901            )),
22902        };
22903
22904        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22905        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22906        assert!(matches!(
22907            call.as_mut().poll(&mut task_context),
22908            Poll::Pending
22909        ));
22910
22911        let commands = ctx.take_commands().expect("commands");
22912        assert_eq!(commands[0]["type"], "schedule_activity");
22913        assert_eq!(commands[0]["activity_type"], "hello.activity");
22914    }
22915
22916    #[test]
22917    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22918        let ctx = workflow_context(Vec::new());
22919        let options = ActivityOptions::new()
22920            .task_queue("payments")
22921            .retry_policy(
22922                ActivityRetryPolicy::new(4)
22923                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22924                    .non_retryable_error_type("ValidationError"),
22925            )
22926            .start_to_close_timeout(Duration::from_secs(120))
22927            .schedule_to_start_timeout(Duration::from_secs(10))
22928            .schedule_to_close_timeout(Duration::from_secs(300))
22929            .heartbeat_timeout(Duration::from_secs(15));
22930        let mut call = Box::pin(ctx.activity_with_options(
22931            "charge-card",
22932            options,
22933            json!([{"order_id": "o-1"}]),
22934        ));
22935        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22936
22937        assert!(matches!(
22938            call.as_mut().poll(&mut task_context),
22939            Poll::Pending
22940        ));
22941        assert!(matches!(
22942            call.as_mut().poll(&mut task_context),
22943            Poll::Pending
22944        ));
22945
22946        let commands = ctx.take_commands().expect("activity command");
22947        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22948        assert_eq!(commands[0]["queue"], "payments");
22949        assert_eq!(
22950            commands[0]["retry_policy"],
22951            json!({
22952                "max_attempts": 4,
22953                "backoff_seconds": [1, 3, 9],
22954                "non_retryable_error_types": ["ValidationError"],
22955            })
22956        );
22957        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22958        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22959        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22960        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22961    }
22962
22963    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22964        vec![
22965            history_event(
22966                "ActivityScheduled",
22967                json!({"sequence":1,"activity_type":"render",
22968                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22969            ),
22970            history_event(
22971                "ActivityCompleted",
22972                json!({"sequence":1,"activity_type":"render",
22973                "payload_codec":DEFAULT_CODEC,
22974                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
22975            ),
22976        ]
22977    }
22978
22979    #[test]
22980    fn worker_session_activity_routes_to_session_queue_once() {
22981        let ctx = workflow_context(Vec::new());
22982        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22983        let mut call = Box::pin(
22984            ctx.activity("render", json!([]))
22985                .in_worker_session(session.clone()),
22986        );
22987        let mut cx = TaskContext::from_waker(noop_waker_ref());
22988        assert!(call.as_mut().poll(&mut cx).is_pending());
22989        assert!(call.as_mut().poll(&mut cx).is_pending());
22990        let commands = ctx.take_commands().unwrap();
22991        assert_eq!(commands.len(), 1);
22992        assert_eq!(commands[0]["queue"], "gpu-workers");
22993        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
22994    }
22995
22996    #[tokio::test]
22997    async fn worker_session_cold_replay_uses_recorded_avro_result() {
22998        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22999        for _replacement in 0..2 {
23000            let ctx = workflow_context(completed_worker_session_history(&session));
23001            let result: i64 = ctx
23002                .activity("render", json!([]))
23003                .in_worker_session(session.clone())
23004                .typed()
23005                .await
23006                .unwrap();
23007            assert_eq!(result, 42);
23008            assert!(ctx.take_commands().unwrap().is_empty());
23009        }
23010    }
23011
23012    #[test]
23013    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
23014        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23015        for changed in [
23016            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
23017            Some(original.clone().ttl_seconds(60)),
23018            Some(original.clone().requirements(["gpu:l4"])),
23019            None,
23020        ] {
23021            let ctx = workflow_context(completed_worker_session_history(&original));
23022            let mut call = ctx.activity_with_options(
23023                "render",
23024                ActivityOptions::new().task_queue("gpu-workers"),
23025                json!([]),
23026            );
23027            if let Some(changed) = changed {
23028                call = call.in_worker_session(changed);
23029            }
23030            let mut call = Box::pin(call);
23031            let mut cx = TaskContext::from_waker(noop_waker_ref());
23032            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23033                call.as_mut().poll(&mut cx)
23034            else {
23035                panic!("changed session must fail replay");
23036            };
23037            assert_eq!(failure.reason, "activity_worker_session_mismatch");
23038            assert!(ctx.take_commands().unwrap().is_empty());
23039        }
23040    }
23041
23042    #[test]
23043    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
23044        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23045        let ctx = workflow_context(Vec::new());
23046        let mut local = Box::pin(
23047            ctx.local_activity("render", json!([]))
23048                .in_worker_session(session.clone()),
23049        );
23050        let mut cx = TaskContext::from_waker(noop_waker_ref());
23051        assert!(matches!(
23052            local.as_mut().poll(&mut cx),
23053            Poll::Ready(Err(Error::WorkerLoop(_)))
23054        ));
23055        assert!(ctx.take_commands().unwrap().is_empty());
23056        let mut remote = Box::pin(
23057            ctx.activity_with_options(
23058                "render",
23059                ActivityOptions::new().task_queue("other"),
23060                json!([]),
23061            )
23062            .in_worker_session(session),
23063        );
23064        assert!(matches!(
23065            remote.as_mut().poll(&mut cx),
23066            Poll::Ready(Err(Error::WorkerLoop(_)))
23067        ));
23068        assert!(ctx.take_commands().unwrap().is_empty());
23069    }
23070
23071    #[test]
23072    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
23073        let ctx = workflow_context(Vec::new());
23074        let options = ActivityOptions::new().retry_policy(
23075            ActivityRetryPolicy::new(3)
23076                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
23077        );
23078        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23079        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23080
23081        assert!(matches!(
23082            call.as_mut().poll(&mut task_context),
23083            Poll::Pending
23084        ));
23085        assert_eq!(
23086            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
23087            json!([1, 2])
23088        );
23089    }
23090
23091    #[test]
23092    fn activity_options_preserve_unused_explicit_backoff_entries() {
23093        for max_attempts in [1, 2, 10] {
23094            let ctx = workflow_context(Vec::new());
23095            let options =
23096                ActivityOptions::new()
23097                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
23098                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
23099                    ));
23100            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23101            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23102            assert!(matches!(
23103                call.as_mut().poll(&mut task_context),
23104                Poll::Pending
23105            ));
23106            let commands = ctx.take_commands().expect("command");
23107            assert_eq!(commands.len(), 1);
23108            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
23109            assert_eq!(
23110                commands[0]["retry_policy"]["backoff_seconds"],
23111                json!([1, 2, 5, 10, 15, 30, 60, 120])
23112            );
23113        }
23114        let default_options = ActivityOptions::new().validate().expect("default options");
23115        let default_policy = current_activity_retry_snapshot(&default_options);
23116        assert_eq!(
23117            default_policy.max_attempts,
23118            RecordedSnapshotValue::Known(Some(1))
23119        );
23120        assert_eq!(
23121            default_policy.backoff_seconds,
23122            RecordedSnapshotValue::Known(Vec::new())
23123        );
23124    }
23125
23126    #[test]
23127    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
23128        let fixture: Value = serde_json::from_str(include_str!(
23129            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
23130        ))
23131        .expect("published PHP fixture");
23132        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
23133            .expect("unchanged published history");
23134        let matching = ActivityOptions::new().task_queue("default").retry_policy(
23135            ActivityRetryPolicy::new(1)
23136                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
23137        );
23138        let mut changed_tail = matching.clone();
23139        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23140            [1, 2, 5, 10, 15, 30, 60, 121]
23141                .map(Duration::from_secs)
23142                .to_vec(),
23143        ));
23144        let mut changed_first = matching.clone();
23145        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23146            [2, 2, 5, 10, 15, 30, 60, 120]
23147                .map(Duration::from_secs)
23148                .to_vec(),
23149        ));
23150        let mut changed_attempts = matching.clone();
23151        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
23152        let mut changed_types = matching.clone();
23153        changed_types
23154            .retry_policy
23155            .as_mut()
23156            .unwrap()
23157            .non_retryable_error_types = vec!["ChangedError".into()];
23158        let mut changed_start = matching.clone();
23159        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
23160        let mut changed_schedule_start = matching.clone();
23161        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
23162        let mut changed_schedule_close = matching.clone();
23163        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
23164        let mut changed_heartbeat = matching;
23165        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
23166        let unchanged_defaults = ActivityOptions::new().task_queue("default");
23167        for options in [
23168            changed_tail,
23169            changed_first,
23170            changed_attempts,
23171            changed_types,
23172            changed_start,
23173            changed_schedule_start,
23174            changed_schedule_close,
23175            changed_heartbeat,
23176            unchanged_defaults,
23177        ] {
23178            let ctx = workflow_context(history.clone());
23179            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
23180            assert!(!ctx.patched("frozen-zero").unwrap());
23181            ctx.deprecate_patch("frozen-zero").unwrap();
23182            let mut call =
23183                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
23184            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23185            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23186                call.as_mut().poll(&mut task_context)
23187            else {
23188                panic!("changed explicit policy must fail replay")
23189            };
23190            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
23191            assert_eq!(failure.sequence, Some(2));
23192            assert!(ctx.take_commands().unwrap().is_empty());
23193        }
23194    }
23195
23196    #[test]
23197    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
23198        let cases = [
23199            (
23200                ActivityOptions::new().task_queue("  "),
23201                ActivityOptionsErrorKind::EmptyTaskQueue,
23202            ),
23203            (
23204                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
23205                ActivityOptionsErrorKind::EmptyRetryPolicy,
23206            ),
23207            (
23208                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
23209                ActivityOptionsErrorKind::InvalidMaxAttempts,
23210            ),
23211            (
23212                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
23213                    max_attempts: None,
23214                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
23215                    non_retryable_error_types: Vec::new(),
23216                }),
23217                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
23218            ),
23219            (
23220                ActivityOptions::new().retry_policy(
23221                    ActivityRetryPolicy::new(2).exponential_backoff(
23222                        Duration::from_secs(1),
23223                        0,
23224                        None,
23225                    ),
23226                ),
23227                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
23228            ),
23229            (
23230                ActivityOptions::new()
23231                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
23232                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
23233            ),
23234            (
23235                ActivityOptions::new().retry_policy(
23236                    ActivityRetryPolicy::new(10_002).exponential_backoff(
23237                        Duration::from_secs(1),
23238                        1,
23239                        None,
23240                    ),
23241                ),
23242                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
23243            ),
23244            (
23245                ActivityOptions::new().retry_policy(
23246                    ActivityRetryPolicy::new(2)
23247                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
23248                ),
23249                ActivityOptionsErrorKind::BackoffOverflow,
23250            ),
23251        ];
23252
23253        for (options, expected_kind) in cases {
23254            let ctx = workflow_context(Vec::new());
23255            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23256            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23257            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
23258                call.as_mut().poll(&mut task_context)
23259            else {
23260                panic!("expected typed activity validation error");
23261            };
23262            assert_eq!(error.kind, expected_kind);
23263            assert!(ctx.take_commands().expect("commands").is_empty());
23264        }
23265    }
23266
23267    #[test]
23268    fn activity_options_validate_positive_and_ordered_timeouts() {
23269        let zero_timeout_cases = [
23270            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
23271            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
23272            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
23273            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
23274        ];
23275        for options in zero_timeout_cases {
23276            assert_eq!(
23277                options.validate().expect_err("zero timeout").kind,
23278                ActivityOptionsErrorKind::TimeoutNotPositive
23279            );
23280        }
23281
23282        let ordering_cases = [
23283            ActivityOptions::new()
23284                .heartbeat_timeout(Duration::from_secs(11))
23285                .start_to_close_timeout(Duration::from_secs(10)),
23286            ActivityOptions::new()
23287                .start_to_close_timeout(Duration::from_secs(31))
23288                .schedule_to_close_timeout(Duration::from_secs(30)),
23289            ActivityOptions::new()
23290                .schedule_to_start_timeout(Duration::from_secs(31))
23291                .schedule_to_close_timeout(Duration::from_secs(30)),
23292        ];
23293        for options in ordering_cases {
23294            assert_eq!(
23295                options.validate().expect_err("timeout order").kind,
23296                ActivityOptionsErrorKind::TimeoutOrder
23297            );
23298        }
23299
23300        assert_eq!(
23301            ActivityOptions::new()
23302                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
23303                .validate()
23304                .expect_err("protocol integer overflow")
23305                .kind,
23306            ActivityOptionsErrorKind::TimeoutOverflow
23307        );
23308    }
23309
23310    #[test]
23311    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
23312        let ctx = workflow_context(completed_retry_activity_history());
23313        let mut call =
23314            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23315        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23316
23317        assert!(matches!(
23318            call.as_mut().poll(&mut task_context),
23319            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23320        ));
23321        assert!(ctx.take_commands().expect("commands").is_empty());
23322        ctx.ensure_history_consumed().expect("history consumed");
23323    }
23324
23325    #[test]
23326    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
23327        let mut options = retry_activity_options();
23328        options
23329            .retry_policy
23330            .as_mut()
23331            .expect("retry policy")
23332            .non_retryable_error_types
23333            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
23334
23335        let new_ctx = workflow_context(Vec::new());
23336        let mut new_call =
23337            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
23338        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23339        assert!(matches!(
23340            new_call.as_mut().poll(&mut task_context),
23341            Poll::Pending
23342        ));
23343        let commands = new_ctx.take_commands().expect("commands");
23344        assert_eq!(commands.len(), 1);
23345        assert_eq!(
23346            commands[0]["retry_policy"]["non_retryable_error_types"],
23347            json!(["PermanentError"])
23348        );
23349
23350        let replay_ctx = workflow_context(completed_retry_activity_history());
23351        let mut replay_call =
23352            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
23353        assert!(matches!(
23354            replay_call.as_mut().poll(&mut task_context),
23355            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23356        ));
23357        assert!(replay_ctx.take_commands().expect("commands").is_empty());
23358        replay_ctx
23359            .ensure_history_consumed()
23360            .expect("history consumed");
23361    }
23362
23363    #[test]
23364    fn replayed_intermediate_retry_remains_pending_across_restarts() {
23365        let history = completed_retry_activity_history()
23366            .into_iter()
23367            .take(3)
23368            .collect::<Vec<_>>();
23369
23370        for _restart in 0..2 {
23371            let ctx = workflow_context(history.clone());
23372            let mut call =
23373                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23374            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23375            assert!(matches!(
23376                call.as_mut().poll(&mut task_context),
23377                Poll::Pending
23378            ));
23379            assert!(ctx.take_commands().expect("commands").is_empty());
23380        }
23381    }
23382
23383    #[test]
23384    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
23385        let mut changed_queue = retry_activity_options();
23386        changed_queue.task_queue = Some("different-queue".to_string());
23387
23388        let mut changed_max_attempts = retry_activity_options();
23389        let retry_policy = changed_max_attempts
23390            .retry_policy
23391            .as_mut()
23392            .expect("retry policy");
23393        retry_policy.max_attempts = Some(4);
23394
23395        let mut changed_backoff = retry_activity_options();
23396        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
23397        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
23398            Duration::from_secs(3),
23399            Duration::from_secs(4),
23400        ]));
23401
23402        let mut changed_non_retryable_types = retry_activity_options();
23403        let retry_policy = changed_non_retryable_types
23404            .retry_policy
23405            .as_mut()
23406            .expect("retry policy");
23407        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
23408
23409        let mut changed_start_to_close = retry_activity_options();
23410        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
23411        let mut changed_schedule_to_start = retry_activity_options();
23412        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
23413        let mut changed_schedule_to_close = retry_activity_options();
23414        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
23415        let mut changed_heartbeat = retry_activity_options();
23416        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
23417
23418        let cases = [
23419            (changed_queue, "activity_task_queue_mismatch"),
23420            (changed_max_attempts, "activity_retry_policy_mismatch"),
23421            (changed_backoff, "activity_retry_policy_mismatch"),
23422            (
23423                changed_non_retryable_types,
23424                "activity_retry_policy_mismatch",
23425            ),
23426            (changed_start_to_close, "activity_retry_policy_mismatch"),
23427            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
23428            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
23429            (changed_heartbeat, "activity_retry_policy_mismatch"),
23430        ];
23431
23432        for (options, expected_reason) in cases {
23433            let ctx = workflow_context(completed_retry_activity_history());
23434            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
23435            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23436            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23437                call.as_mut().poll(&mut task_context)
23438            else {
23439                panic!("changed activity options must fail replay");
23440            };
23441            assert_eq!(failure.reason, expected_reason);
23442            assert_eq!(failure.sequence, Some(1));
23443            assert!(ctx.take_commands().expect("commands").is_empty());
23444        }
23445    }
23446
23447    #[test]
23448    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
23449        let cases = [
23450            (
23451                "execution_mode",
23452                json!("local"),
23453                "activity_execution_mode_mismatch",
23454            ),
23455            (
23456                "snapshot_version",
23457                json!(2),
23458                "activity_retry_policy_mismatch",
23459            ),
23460        ];
23461
23462        for (field, value, expected_reason) in cases {
23463            let mut history = completed_retry_activity_history();
23464            let activity = history[0].payload["activity"]
23465                .as_object_mut()
23466                .expect("activity snapshot");
23467            if field == "execution_mode" {
23468                activity.insert(field.to_string(), value);
23469            } else {
23470                activity["retry_policy"]
23471                    .as_object_mut()
23472                    .expect("retry snapshot")
23473                    .insert(field.to_string(), value);
23474            }
23475
23476            let ctx = workflow_context(history);
23477            let mut call =
23478                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23479            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23480            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23481                call.as_mut().poll(&mut task_context)
23482            else {
23483                panic!("changed {field} must fail replay");
23484            };
23485            assert_eq!(failure.reason, expected_reason);
23486            assert_eq!(failure.sequence, Some(1));
23487            assert!(ctx.take_commands().expect("commands").is_empty());
23488        }
23489    }
23490
23491    #[test]
23492    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
23493        for (nested, field, value, terminal_only) in [
23494            (false, "execution_mode", json!("local"), false),
23495            (false, "local_activity", json!(true), false),
23496            (true, "local_activity", json!(true), false),
23497            (false, "local_activity", json!(true), true),
23498        ] {
23499            let mut history = completed_retry_activity_history();
23500            history[0]
23501                .payload
23502                .as_object_mut()
23503                .unwrap()
23504                .remove("activity");
23505            let event = if terminal_only {
23506                history.last_mut().unwrap()
23507            } else {
23508                &mut history[0]
23509            };
23510            if nested {
23511                event.payload["activity"] = json!({(field): value});
23512            } else {
23513                event.payload[field] = value;
23514            }
23515            let ctx = workflow_context(history);
23516            let mut call =
23517                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23518            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23519            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23520                call.as_mut().poll(&mut task_context)
23521            else {
23522                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
23523            };
23524            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
23525            assert_eq!(failure.sequence, Some(1));
23526            assert!(ctx.take_commands().expect("commands").is_empty());
23527        }
23528    }
23529
23530    #[test]
23531    fn activity_history_rejects_conflicting_local_execution_markers() {
23532        let mut history = completed_retry_activity_history();
23533        history.last_mut().unwrap().payload["local_activity"] = json!(true);
23534        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
23535            .expect_err("remote schedule cannot become a local completion");
23536        assert!(
23537            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
23538            if reason == "activity_execution_mode_conflict")
23539        );
23540    }
23541
23542    #[test]
23543    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
23544        let mut history = completed_retry_activity_history();
23545        let activity = history[0].payload["activity"]
23546            .as_object_mut()
23547            .expect("activity snapshot");
23548        activity.remove("execution_mode");
23549        activity.remove("retry_policy");
23550
23551        let mut current = retry_activity_options();
23552        current.start_to_close_timeout = Some(Duration::from_secs(45));
23553        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
23554        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
23555        current.heartbeat_timeout = Some(Duration::from_secs(12));
23556
23557        let ctx = workflow_context(history);
23558        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
23559        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23560        assert!(matches!(
23561            call.as_mut().poll(&mut task_context),
23562            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23563        ));
23564        assert!(ctx.take_commands().expect("commands").is_empty());
23565        ctx.ensure_history_consumed().expect("history consumed");
23566    }
23567
23568    #[test]
23569    fn terminal_activity_failed_after_start_returns_typed_failure() {
23570        let history = vec![
23571            history_event(
23572                "ActivityScheduled",
23573                json!({
23574                    "sequence": 1,
23575                    "activity_type": "flaky",
23576                    "activity_execution_id": "act-terminal",
23577                    "activity": {
23578                        "id": "act-terminal",
23579                        "sequence": 1,
23580                        "type": "flaky",
23581                        "queue": "critical-activities",
23582                        "retry_policy": {
23583                            "snapshot_version": 1,
23584                            "max_attempts": 3,
23585                            "backoff_seconds": [2, 4],
23586                            "non_retryable_error_types": ["PermanentError"]
23587                        }
23588                    }
23589                }),
23590            ),
23591            history_event(
23592                "ActivityStarted",
23593                json!({
23594                    "sequence": 1,
23595                    "activity_type": "flaky",
23596                    "activity_execution_id": "act-terminal",
23597                    "activity_attempt_id": "attempt-1",
23598                    "attempt_number": 1
23599                }),
23600            ),
23601            history_event(
23602                "ActivityFailed",
23603                json!({
23604                    "sequence": 1,
23605                    "activity_type": "flaky",
23606                    "activity_execution_id": "act-terminal",
23607                    "activity_attempt_id": "attempt-1",
23608                    "attempt_number": 1,
23609                    "failure_id": "failure-terminal",
23610                    "failure_category": "activity",
23611                    "exception_type": "PermanentError",
23612                    "message": "cannot retry",
23613                    "non_retryable": true
23614                }),
23615            ),
23616        ];
23617        let ctx = workflow_context(history);
23618        let mut call =
23619            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23620        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23621
23622        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23623            call.as_mut().poll(&mut task_context)
23624        else {
23625            panic!("terminal ActivityFailed must settle the activity future");
23626        };
23627        assert_eq!(failure.kind, ActivityFailureKind::Failed);
23628        assert_eq!(
23629            failure.activity_execution_id.as_deref(),
23630            Some("act-terminal")
23631        );
23632        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
23633        assert!(failure.non_retryable);
23634        assert!(ctx.take_commands().expect("commands").is_empty());
23635        ctx.ensure_history_consumed().expect("history consumed");
23636    }
23637
23638    #[test]
23639    fn activity_terminal_events_return_machine_readable_failures() {
23640        let cases = [
23641            (
23642                "ActivityFailed",
23643                json!({
23644                    "sequence": 1,
23645                    "activity_type": "charge-card",
23646                    "activity_execution_id": "act-1",
23647                    "activity_attempt_id": "attempt-2",
23648                    "attempt_number": 2,
23649                    "failure_id": "failure-1",
23650                    "failure_category": "activity",
23651                    "exception_type": "PaymentDeclined",
23652                    "exception_class": "payments.PaymentDeclined",
23653                    "message": "card declined",
23654                    "non_retryable": true
23655                }),
23656                ActivityFailureKind::Failed,
23657                "activity",
23658            ),
23659            (
23660                "ActivityCancelled",
23661                json!({
23662                    "sequence": 1,
23663                    "activity_type": "charge-card",
23664                    "activity_execution_id": "act-1",
23665                    "activity_attempt_id": "attempt-1"
23666                }),
23667                ActivityFailureKind::Cancelled,
23668                "cancelled",
23669            ),
23670        ];
23671
23672        for (event_type, payload, expected_kind, expected_reason) in cases {
23673            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23674            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23675            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23676            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23677                call.as_mut().poll(&mut task_context)
23678            else {
23679                panic!("expected terminal activity failure");
23680            };
23681            assert_eq!(failure.kind, expected_kind);
23682            assert_eq!(failure.reason, expected_reason);
23683            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23684            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23685        }
23686    }
23687
23688    #[test]
23689    fn every_activity_timeout_class_is_typed() {
23690        for timeout_kind in [
23691            "start_to_close",
23692            "schedule_to_start",
23693            "schedule_to_close",
23694            "heartbeat",
23695        ] {
23696            let ctx = workflow_context(vec![history_event(
23697                "ActivityTimedOut",
23698                json!({
23699                    "sequence": 1,
23700                    "activity_type": "slow",
23701                    "activity_execution_id": "act-timeout",
23702                    "activity_attempt_id": "attempt-timeout",
23703                    "failure_category": "timeout",
23704                    "timeout_kind": timeout_kind,
23705                    "message": "deadline expired"
23706                }),
23707            )]);
23708            let mut call = Box::pin(ctx.activity("slow", json!([])));
23709            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23710            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23711                call.as_mut().poll(&mut task_context)
23712            else {
23713                panic!("expected timeout failure");
23714            };
23715            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23716            assert_eq!(failure.reason, timeout_kind);
23717            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23718            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23719        }
23720    }
23721
23722    #[test]
23723    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23724        let ctx = workflow_context(Vec::new());
23725        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23726        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23727
23728        assert!(matches!(
23729            sleep.as_mut().poll(&mut task_context),
23730            Poll::Pending
23731        ));
23732        assert!(matches!(
23733            sleep.as_mut().poll(&mut task_context),
23734            Poll::Pending
23735        ));
23736
23737        let commands = ctx.take_commands().expect("timer command");
23738        assert_eq!(
23739            commands,
23740            vec![json!({
23741                "type": "start_timer",
23742                "delay_seconds": 2,
23743            })]
23744        );
23745    }
23746
23747    #[test]
23748    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23749        let history = vec![
23750            history_event(
23751                "TimerScheduled",
23752                json!({
23753                    "sequence": 1,
23754                    "timer_id": "timer-1",
23755                    "delay_seconds": 5,
23756                    "fire_at": "2026-07-11T12:00:05Z",
23757                }),
23758            ),
23759            history_event(
23760                "TimerFired",
23761                json!({
23762                    "sequence": 1,
23763                    "timer_id": "timer-1",
23764                    "delay_seconds": 5,
23765                    "fire_at": "2026-07-11T12:00:05Z",
23766                    "fired_at": "2026-07-11T12:00:05Z",
23767                }),
23768            ),
23769        ];
23770
23771        for _restart in 0..2 {
23772            let ctx = workflow_context(history.clone());
23773            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23774            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23775            assert!(matches!(
23776                sleep.as_mut().poll(&mut task_context),
23777                Poll::Ready(Ok(()))
23778            ));
23779            assert!(ctx.take_commands().expect("commands").is_empty());
23780            ctx.ensure_history_consumed().expect("history consumed");
23781        }
23782    }
23783
23784    #[test]
23785    fn workflow_sleep_rejects_changed_delay_during_replay() {
23786        let ctx = workflow_context(vec![
23787            history_event(
23788                "TimerScheduled",
23789                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23790            ),
23791            history_event(
23792                "TimerFired",
23793                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23794            ),
23795        ]);
23796        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23797        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23798
23799        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23800            sleep.as_mut().poll(&mut task_context)
23801        else {
23802            panic!("changed timer delay must be rejected");
23803        };
23804        assert_eq!(failure.reason, "timer_delay_mismatch");
23805        assert_eq!(failure.sequence, Some(1));
23806    }
23807
23808    #[test]
23809    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23810        let ctx = workflow_context(Vec::new());
23811        let mut wait = Box::pin(
23812            ctx.wait_condition(
23813                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23814                    .timeout(Duration::from_millis(60_001)),
23815                || Ok(false),
23816            ),
23817        );
23818        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23819
23820        assert!(matches!(
23821            wait.as_mut().poll(&mut task_context),
23822            Poll::Pending
23823        ));
23824        assert!(matches!(
23825            wait.as_mut().poll(&mut task_context),
23826            Poll::Pending
23827        ));
23828        assert_eq!(
23829            ctx.take_commands().expect("condition command"),
23830            vec![json!({
23831                "type": "open_condition_wait",
23832                "condition_wait_occurrence_id": "rust:condition-wait:0",
23833                "condition_key": "approval.ready",
23834                "condition_definition_fingerprint": "sha256:approval-v1",
23835                "timeout_seconds": 61,
23836            })]
23837        );
23838    }
23839
23840    #[test]
23841    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23842        let ctx = workflow_context(Vec::new());
23843        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23844        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23845        assert!(matches!(
23846            satisfied.as_mut().poll(&mut task_context),
23847            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23848        ));
23849
23850        let mut timed_out = Box::pin(wait_condition!(
23851            ctx,
23852            "no-wait",
23853            timeout: Duration::ZERO,
23854            || Ok(false),
23855        ));
23856        assert!(matches!(
23857            timed_out.as_mut().poll(&mut task_context),
23858            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23859        ));
23860        assert!(ctx.take_commands().expect("commands").is_empty());
23861    }
23862
23863    #[test]
23864    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23865        let signal_history = vec![
23866            history_event(
23867                "ConditionWaitOpened",
23868                json!({
23869                    "sequence": 4,
23870                    "condition_wait_id": "condition:4",
23871                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23872                    "condition_key": "approval",
23873                    "condition_definition_fingerprint": "sha256:approval-v1",
23874                    "timeout_seconds": 30,
23875                }),
23876            ),
23877            history_event(
23878                "SignalReceived",
23879                json!({
23880                    "workflow_sequence": 4,
23881                    "signal_name": "approve",
23882                    "arguments": fixture_envelope(json!(["Ada"])),
23883                }),
23884            ),
23885        ];
23886        for _worker_before_or_after_restart in 0..2 {
23887            let ctx = workflow_context(signal_history.clone());
23888            let predicate_ctx = ctx.clone();
23889            let mut wait = Box::pin(
23890                ctx.wait_condition(
23891                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23892                        .timeout(Duration::from_secs(30)),
23893                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23894                ),
23895            );
23896            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23897            assert!(matches!(
23898                wait.as_mut().poll(&mut task_context),
23899                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23900            ));
23901            assert!(ctx.take_commands().expect("commands").is_empty());
23902            ctx.ensure_history_consumed().expect("condition consumed");
23903        }
23904
23905        let update_history = vec![
23906            history_event(
23907                "ConditionWaitOpened",
23908                json!({
23909                    "sequence": 7,
23910                    "condition_wait_id": "condition:7",
23911                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23912                    "condition_key": "update-approval",
23913                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23914                }),
23915            ),
23916            history_event(
23917                "UpdateApplied",
23918                json!({
23919                    "sequence": 7,
23920                    "update_id": "update-1",
23921                    "update_name": "approve",
23922                    "arguments": fixture_envelope(json!([true])),
23923                }),
23924            ),
23925        ];
23926        let ctx = workflow_context(update_history);
23927        let predicate_ctx = ctx.clone();
23928        let mut wait = Box::pin(ctx.wait_condition(
23929            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23930            move || {
23931                Ok(predicate_ctx
23932                    .updates("approve")?
23933                    .first()
23934                    .and_then(|arguments| arguments.first())
23935                    .and_then(Value::as_bool)
23936                    == Some(true))
23937            },
23938        ));
23939        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23940        assert!(matches!(
23941            wait.as_mut().poll(&mut task_context),
23942            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23943        ));
23944        assert!(ctx.take_commands().expect("commands").is_empty());
23945        ctx.ensure_history_consumed().expect("condition consumed");
23946    }
23947
23948    #[test]
23949    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23950        let open_history = vec![
23951            history_event(
23952                "ConditionWaitOpened",
23953                json!({
23954                    "sequence": 3,
23955                    "condition_wait_id": "condition:3",
23956                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23957                    "condition_key": "two-votes",
23958                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23959                    "timeout_seconds": 120,
23960                }),
23961            ),
23962            history_event(
23963                "SignalReceived",
23964                json!({
23965                    "workflow_sequence": 3,
23966                    "signal_name": "vote",
23967                    "arguments": fixture_envelope(json!(["first"])),
23968                }),
23969            ),
23970        ];
23971        for _worker_before_or_after_restart in 0..2 {
23972            let ctx = workflow_context(open_history.clone());
23973            let predicate_ctx = ctx.clone();
23974            let mut wait = Box::pin(
23975                ctx.wait_condition(
23976                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23977                        .timeout(Duration::from_secs(120)),
23978                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23979                ),
23980            );
23981            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23982            assert!(matches!(
23983                wait.as_mut().poll(&mut task_context),
23984                Poll::Pending
23985            ));
23986            assert_eq!(
23987                ctx.take_commands().expect("reopened condition"),
23988                vec![json!({
23989                    "type": "open_condition_wait",
23990                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23991                    "condition_key": "two-votes",
23992                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23993                    "timeout_seconds": 120,
23994                })]
23995            );
23996        }
23997
23998        let satisfied_ctx = workflow_context(vec![
23999            history_event(
24000                "ConditionWaitOpened",
24001                json!({
24002                    "sequence": 5,
24003                    "condition_wait_id": "condition:5",
24004                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24005                    "condition_key": "approval",
24006                    "condition_definition_fingerprint": "sha256:approval-v1",
24007                }),
24008            ),
24009            history_event(
24010                "ConditionWaitSatisfied",
24011                json!({
24012                    "sequence": 5,
24013                    "condition_wait_id": "condition:5",
24014                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24015                    "condition_key": "approval",
24016                    "condition_definition_fingerprint": "sha256:approval-v1",
24017                }),
24018            ),
24019        ]);
24020        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
24021            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
24022            || Ok(false),
24023        ));
24024        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24025        assert!(matches!(
24026            satisfied.as_mut().poll(&mut task_context),
24027            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24028        ));
24029
24030        let timed_out_ctx = workflow_context(vec![
24031            history_event(
24032                "ConditionWaitOpened",
24033                json!({
24034                    "sequence": 8,
24035                    "condition_wait_id": "condition:8",
24036                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24037                    "condition_key": "approval-timeout",
24038                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
24039                    "timeout_seconds": 5,
24040                }),
24041            ),
24042            history_event(
24043                "TimerScheduled",
24044                json!({
24045                    "sequence": 9,
24046                    "timer_id": "condition-timer:9",
24047                    "timer_kind": "condition_timeout",
24048                    "condition_wait_id": "condition:8",
24049                    "delay_seconds": 5,
24050                }),
24051            ),
24052            history_event(
24053                "TimerFired",
24054                json!({
24055                    "sequence": 9,
24056                    "timer_id": "condition-timer:9",
24057                    "timer_kind": "condition_timeout",
24058                    "condition_wait_id": "condition:8",
24059                    "delay_seconds": 5,
24060                }),
24061            ),
24062        ]);
24063        let mut timed_out = Box::pin(
24064            timed_out_ctx.wait_condition(
24065                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
24066                    .timeout(Duration::from_secs(5)),
24067                || Ok(true),
24068            ),
24069        );
24070        assert!(matches!(
24071            timed_out.as_mut().poll(&mut task_context),
24072            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24073        ));
24074    }
24075
24076    #[test]
24077    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
24078        let ctx = workflow_context(reopened_selection_condition_history());
24079        {
24080            let state = ctx.state.lock().unwrap();
24081            assert!(matches!(
24082                selection_member_recorded_command(&state, 2),
24083                Some(RecordedCommand::ConditionWait {
24084                    sequence: 3,
24085                    result: None,
24086                    ..
24087                })
24088            ));
24089        }
24090        let mut selected = Box::pin(ctx.select_keyed(vec![
24091            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24092            (
24093                "votes",
24094                ParallelOperation::condition(
24095                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24096                    || Ok(true),
24097                ),
24098            ),
24099        ]));
24100        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24101        assert!(selected.as_mut().poll(&mut task_context).is_pending());
24102        assert!(
24103            ctx.take_commands().unwrap().is_empty(),
24104            "true predicate must not reopen the recorded wait"
24105        );
24106        ctx.ensure_history_consumed()
24107            .expect("physical reopens are consumed while canonical selection is pending");
24108    }
24109
24110    #[test]
24111    fn reopened_selection_condition_replays_its_latest_physical_winner() {
24112        for (terminal_type, acknowledge_timeout) in [
24113            ("ConditionWaitSatisfied", false),
24114            ("ConditionWaitTimedOut", false),
24115            ("TimerFired", false),
24116            ("TimerFired", true),
24117        ] {
24118            let mut history = reopened_selection_condition_history();
24119            let original_identity = history[1].payload["condition_wait_id"].clone();
24120            let uses_timer = terminal_type == "TimerFired";
24121            let mut resolution_payload = history[3].payload.clone();
24122            if uses_timer {
24123                for event in &mut history[1..] {
24124                    event.payload["timeout_seconds"] = json!(3);
24125                }
24126                resolution_payload = history[3].payload.clone();
24127                resolution_payload["timer_kind"] = json!("condition_timeout");
24128                resolution_payload["timer_id"] = json!("condition-timeout-3");
24129                resolution_payload["delay_seconds"] = json!(3);
24130                history.push(history_event("TimerScheduled", resolution_payload.clone()));
24131            }
24132            let mut resolution = history_event(terminal_type, resolution_payload.clone());
24133            resolution
24134                .raw
24135                .insert("id".into(), json!("latest-condition-resolution"));
24136            history.push(resolution);
24137            history.push(history_event(
24138                "SelectionResolved",
24139                json!({
24140                    "selection_group_id": "select-calls:1:2",
24141                    "selection_group_base_sequence": 1,
24142                    "selection_group_size": 2,
24143                    "member_key": "votes",
24144                    "member_index": 1,
24145                    "member_base_sequence": 2,
24146                    "member_size": 1,
24147                    "operation_kind": "condition",
24148                    "operation_identity": original_identity,
24149                    "outcome": "completed",
24150                    "resolution_event_id": "latest-condition-resolution",
24151                    "resolution_event_type": terminal_type,
24152                }),
24153            ));
24154            if acknowledge_timeout {
24155                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
24156            }
24157            let ctx = workflow_context(history);
24158            let mut selected = Box::pin(ctx.select_keyed(vec![
24159                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24160                (
24161                    "votes",
24162                    ParallelOperation::condition(
24163                        if uses_timer {
24164                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24165                                .timeout(Duration::from_secs(3))
24166                        } else {
24167                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24168                        },
24169                        || Ok(true),
24170                    ),
24171                ),
24172            ]));
24173            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24174            match selected.as_mut().poll(&mut task_context) {
24175                Poll::Ready(Ok(result)) => {
24176                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
24177                    let expected = if terminal_type == "ConditionWaitSatisfied" {
24178                        ConditionWaitResult::Satisfied
24179                    } else {
24180                        ConditionWaitResult::TimedOut
24181                    };
24182                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
24183                }
24184                other => panic!("latest physical winner must replay: {other:?}"),
24185            }
24186            assert!(ctx.take_commands().unwrap().is_empty());
24187            ctx.ensure_history_consumed()
24188                .expect("winner history consumed");
24189        }
24190    }
24191
24192    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
24193        let fixture: Value = serde_json::from_str(include_str!(
24194            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24195        ))
24196        .expect("grouped condition fixture");
24197        fixture["history"]
24198            .as_array()
24199            .unwrap()
24200            .iter()
24201            .map(|event| {
24202                let mut payload = event["payload"].clone();
24203                let index = payload["parallel_group_index"].as_u64().unwrap();
24204                payload["parallel_group_id"] = json!("select-calls:1:2");
24205                payload["parallel_group_mode"] = json!("select");
24206                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
24207                payload["selection_member_index"] = json!(index);
24208                payload["selection_member_base_sequence"] = json!(index + 1);
24209                payload["selection_member_size"] = json!(1);
24210                payload["selection_member_kind"] =
24211                    json!(if index == 0 { "timer" } else { "condition" });
24212                history_event(event["event_type"].as_str().unwrap(), payload)
24213            })
24214            .collect()
24215    }
24216
24217    #[test]
24218    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
24219        let fixture: Value = serde_json::from_str(include_str!(
24220            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24221        ))
24222        .expect("grouped condition fixture");
24223        let original = fixture["history"].as_array().expect("fixture history");
24224        let decode = |events: &[Value]| {
24225            let history = events
24226                .iter()
24227                .map(|event| {
24228                    history_event(
24229                        event["event_type"].as_str().unwrap(),
24230                        event["payload"].clone(),
24231                    )
24232                })
24233                .collect::<Vec<_>>();
24234            recorded_commands(
24235                &history,
24236                DEFAULT_CODEC,
24237                WorkflowIdentity {
24238                    workflow_id: None,
24239                    run_id: None,
24240                },
24241            )
24242        };
24243        assert!(decode(original).is_ok());
24244        for field in [
24245            "condition_wait_occurrence_id",
24246            "condition_key",
24247            "condition_definition_fingerprint",
24248            "timeout_seconds",
24249            "parallel_group_id",
24250            "parallel_group_size",
24251            "parallel_group_index",
24252        ] {
24253            let mut changed = original.clone();
24254            changed[3]["payload"][field] = match field {
24255                "timeout_seconds" | "parallel_group_size" => json!(30),
24256                "parallel_group_index" => json!(0),
24257                _ => json!("changed"),
24258            };
24259            assert!(
24260                decode(&changed).is_err(),
24261                "reopen must reject changed {field}"
24262            );
24263        }
24264        let mut unsettled = original.clone();
24265        unsettled.remove(2);
24266        assert!(
24267            decode(&unsettled).is_err(),
24268            "physical predecessor must be resolved"
24269        );
24270        let mut timed_out = original.clone();
24271        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
24272        assert!(decode(&timed_out).is_err(), "timeout is terminal");
24273        let mut late_resolution = original.clone();
24274        late_resolution.swap(2, 3);
24275        assert!(
24276            decode(&late_resolution).is_err(),
24277            "later history cannot authorize a reopen"
24278        );
24279    }
24280
24281    #[test]
24282    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
24283        let history = vec![
24284            history_event(
24285                "ConditionWaitOpened",
24286                json!({
24287                    "sequence": 3,
24288                    "condition_wait_id": "condition:3",
24289                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24290                    "condition_key": "two-votes",
24291                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24292                }),
24293            ),
24294            history_event(
24295                "SignalReceived",
24296                json!({
24297                    "workflow_sequence": 3,
24298                    "signal_name": "vote",
24299                    "arguments": fixture_envelope(json!(["first"])),
24300                }),
24301            ),
24302            history_event(
24303                "ConditionWaitSatisfied",
24304                json!({
24305                    "sequence": 3,
24306                    "condition_wait_id": "condition:3",
24307                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24308                    "condition_key": "two-votes",
24309                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24310                }),
24311            ),
24312            history_event(
24313                "ConditionWaitOpened",
24314                json!({
24315                    "sequence": 5,
24316                    "condition_wait_id": "condition:5",
24317                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24318                    "condition_key": "two-votes",
24319                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24320                }),
24321            ),
24322            history_event(
24323                "SignalReceived",
24324                json!({
24325                    "workflow_sequence": 5,
24326                    "signal_name": "vote",
24327                    "arguments": fixture_envelope(json!(["second"])),
24328                }),
24329            ),
24330            history_event(
24331                "ConditionWaitSatisfied",
24332                json!({
24333                    "sequence": 5,
24334                    "condition_wait_id": "condition:5",
24335                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24336                    "condition_key": "two-votes",
24337                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24338                }),
24339            ),
24340        ];
24341        for _cold_worker_or_restart in 0..2 {
24342            let ctx = workflow_context(history.clone());
24343            let predicate_ctx = ctx.clone();
24344            let mut wait = Box::pin(ctx.wait_condition(
24345                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24346                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24347            ));
24348            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24349
24350            assert!(matches!(
24351                wait.as_mut().poll(&mut task_context),
24352                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24353            ));
24354            assert!(ctx.take_commands().expect("commands").is_empty());
24355            ctx.ensure_history_consumed()
24356                .expect("every physical wait-open is consumed");
24357        }
24358    }
24359
24360    #[test]
24361    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
24362        let history = vec![
24363            history_event(
24364                "ConditionWaitOpened",
24365                json!({
24366                    "sequence": 3,
24367                    "condition_wait_id": "condition:3",
24368                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24369                    "condition_key": "approved",
24370                    "condition_definition_fingerprint": "sha256:approved-v1",
24371                }),
24372            ),
24373            history_event(
24374                "UpdateApplied",
24375                json!({
24376                    "sequence": 3,
24377                    "update_id": "update-1",
24378                    "update_name": "approve",
24379                    "arguments": fixture_envelope(json!([false])),
24380                }),
24381            ),
24382            history_event(
24383                "ConditionWaitOpened",
24384                json!({
24385                    "sequence": 5,
24386                    "condition_wait_id": "condition:5",
24387                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24388                    "condition_key": "approved",
24389                    "condition_definition_fingerprint": "sha256:approved-v1",
24390                }),
24391            ),
24392            history_event(
24393                "UpdateApplied",
24394                json!({
24395                    "sequence": 5,
24396                    "update_id": "update-2",
24397                    "update_name": "approve",
24398                    "arguments": fixture_envelope(json!([true])),
24399                }),
24400            ),
24401        ];
24402
24403        for _cold_worker_or_restart in 0..2 {
24404            let ctx = workflow_context(history.clone());
24405            let predicate_ctx = ctx.clone();
24406            let mut wait = Box::pin(ctx.wait_condition(
24407                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
24408                move || {
24409                    Ok(predicate_ctx
24410                        .updates("approve")?
24411                        .last()
24412                        .and_then(|arguments| arguments.first())
24413                        .and_then(Value::as_bool)
24414                        == Some(true))
24415                },
24416            ));
24417            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24418
24419            assert!(matches!(
24420                wait.as_mut().poll(&mut task_context),
24421                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24422            ));
24423            assert!(ctx.take_commands().expect("commands").is_empty());
24424            ctx.ensure_history_consumed()
24425                .expect("every update-driven reopen is consumed");
24426        }
24427    }
24428
24429    #[test]
24430    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
24431        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
24432            ("shared", "sha256:first", "shared", "sha256:second"),
24433            ("first", "sha256:shared", "second", "sha256:shared"),
24434            ("shared", "sha256:shared", "shared", "sha256:shared"),
24435            ("first", "sha256:first", "second", "sha256:second"),
24436        ] {
24437            let history = vec![
24438                history_event(
24439                    "ConditionWaitOpened",
24440                    json!({
24441                        "sequence": 3,
24442                        "condition_wait_id": "condition:3",
24443                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24444                        "condition_key": first_key,
24445                        "condition_definition_fingerprint": first_fingerprint,
24446                    }),
24447                ),
24448                history_event(
24449                    "ConditionWaitSatisfied",
24450                    json!({
24451                        "sequence": 3,
24452                        "condition_wait_id": "condition:3",
24453                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24454                        "condition_key": first_key,
24455                        "condition_definition_fingerprint": first_fingerprint,
24456                    }),
24457                ),
24458                history_event(
24459                    "ConditionWaitOpened",
24460                    json!({
24461                        "sequence": 4,
24462                        "condition_wait_id": "condition:4",
24463                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24464                        "condition_key": second_key,
24465                        "condition_definition_fingerprint": second_fingerprint,
24466                    }),
24467                ),
24468                history_event(
24469                    "ConditionWaitSatisfied",
24470                    json!({
24471                        "sequence": 4,
24472                        "condition_wait_id": "condition:4",
24473                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24474                        "condition_key": second_key,
24475                        "condition_definition_fingerprint": second_fingerprint,
24476                    }),
24477                ),
24478            ];
24479            for _cold_worker_or_restart in 0..2 {
24480                let ctx = workflow_context(history.clone());
24481                let mut task_context = TaskContext::from_waker(noop_waker_ref());
24482                let mut first = Box::pin(ctx.wait_condition(
24483                    ConditionWaitOptions::new(first_key, first_fingerprint),
24484                    || Ok(false),
24485                ));
24486                assert!(matches!(
24487                    first.as_mut().poll(&mut task_context),
24488                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24489                ));
24490
24491                let mut second = Box::pin(ctx.wait_condition(
24492                    ConditionWaitOptions::new(second_key, second_fingerprint),
24493                    || Ok(false),
24494                ));
24495                assert!(matches!(
24496                    second.as_mut().poll(&mut task_context),
24497                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24498                ));
24499                assert!(ctx.take_commands().expect("commands").is_empty());
24500                ctx.ensure_history_consumed()
24501                    .expect("each authored wait consumes one occurrence");
24502            }
24503        }
24504    }
24505
24506    #[test]
24507    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
24508        fn worker() -> Worker {
24509            let client = Client::new("http://127.0.0.1:8080").expect("client");
24510            let mut worker = Worker::new(client, "rust-workers");
24511            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
24512                let mut outcomes = Vec::new();
24513                for _ in 0..2 {
24514                    outcomes.push(
24515                        ctx.wait_condition(
24516                            ConditionWaitOptions::new("shared", "sha256:shared"),
24517                            || Ok(false),
24518                        )
24519                        .await?,
24520                    );
24521                }
24522                Ok(json!(outcomes))
24523            });
24524            worker
24525        }
24526
24527        let task = workflow_task(
24528            "rust.condition-loop",
24529            vec![
24530                history_event(
24531                    "ConditionWaitOpened",
24532                    json!({
24533                        "sequence": 1,
24534                        "condition_wait_id": "condition:1",
24535                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24536                        "condition_key": "shared",
24537                        "condition_definition_fingerprint": "sha256:shared",
24538                    }),
24539                ),
24540                history_event(
24541                    "ConditionWaitSatisfied",
24542                    json!({
24543                        "sequence": 1,
24544                        "condition_wait_id": "condition:1",
24545                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24546                        "condition_key": "shared",
24547                        "condition_definition_fingerprint": "sha256:shared",
24548                    }),
24549                ),
24550                history_event(
24551                    "ConditionWaitOpened",
24552                    json!({
24553                        "sequence": 2,
24554                        "condition_wait_id": "condition:2",
24555                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24556                        "condition_key": "shared",
24557                        "condition_definition_fingerprint": "sha256:shared",
24558                    }),
24559                ),
24560                history_event(
24561                    "ConditionWaitSatisfied",
24562                    json!({
24563                        "sequence": 2,
24564                        "condition_wait_id": "condition:2",
24565                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24566                        "condition_key": "shared",
24567                        "condition_definition_fingerprint": "sha256:shared",
24568                    }),
24569                ),
24570            ],
24571            DEFAULT_CODEC,
24572        );
24573
24574        for _cold_worker_or_restart in 0..2 {
24575            let commands = worker()
24576                .execute_workflow_task(task.clone())
24577                .expect("adjacent loop waits replay deterministically");
24578            assert_eq!(commands.len(), 1);
24579            assert_eq!(commands[0]["type"], "complete_workflow");
24580            assert_eq!(
24581                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24582                json!(["satisfied", "satisfied"])
24583            );
24584        }
24585    }
24586
24587    #[test]
24588    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
24589        let history = vec![history_event(
24590            "ConditionWaitOpened",
24591            json!({
24592                "sequence": 12,
24593                "condition_wait_id": "condition:12",
24594                "condition_wait_occurrence_id": "rust:condition-wait:0",
24595                "condition_key": "approval",
24596                "condition_definition_fingerprint": "sha256:approval-v1",
24597                "timeout_seconds": 30,
24598            }),
24599        )];
24600        for (options, expected_reason) in [
24601            (
24602                ConditionWaitOptions::new("changed", "sha256:approval-v1")
24603                    .timeout(Duration::from_secs(30)),
24604                "condition_wait_key_mismatch",
24605            ),
24606            (
24607                ConditionWaitOptions::new("approval", "sha256:approval-v2")
24608                    .timeout(Duration::from_secs(30)),
24609                "condition_wait_predicate_mismatch",
24610            ),
24611            (
24612                ConditionWaitOptions::new("approval", "sha256:approval-v1")
24613                    .timeout(Duration::from_secs(29)),
24614                "condition_wait_timeout_mismatch",
24615            ),
24616        ] {
24617            let ctx = workflow_context(history.clone());
24618            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
24619            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24620            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24621                wait.as_mut().poll(&mut task_context)
24622            else {
24623                panic!("changed condition definition must fail replay");
24624            };
24625            assert_eq!(failure.reason, expected_reason);
24626            assert_eq!(failure.sequence, Some(12));
24627        }
24628    }
24629
24630    #[test]
24631    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
24632        let error = WorkflowState::new(
24633            vec![history_event(
24634                "ConditionWaitOpened",
24635                json!({
24636                    "sequence": 12,
24637                    "condition_wait_id": "condition:12",
24638                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24639                    "condition_key": "approval",
24640                }),
24641            )],
24642            "rust-workers".to_string(),
24643            DEFAULT_CODEC.to_string(),
24644            None,
24645        )
24646        .expect_err("condition history without a predicate fingerprint must fail");
24647
24648        assert!(matches!(
24649            error,
24650            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24651                if reason == "condition_wait_predicate_fingerprint_missing"
24652        ));
24653    }
24654
24655    #[test]
24656    fn condition_wait_history_requires_authored_occurrence_identity() {
24657        let error = WorkflowState::new(
24658            vec![history_event(
24659                "ConditionWaitOpened",
24660                json!({
24661                    "sequence": 12,
24662                    "condition_wait_id": "condition:12",
24663                    "condition_key": "approval",
24664                    "condition_definition_fingerprint": "sha256:approval-v1",
24665                }),
24666            )],
24667            "rust-workers".to_string(),
24668            DEFAULT_CODEC.to_string(),
24669            None,
24670        )
24671        .expect_err("condition history without occurrence identity must fail");
24672
24673        assert!(matches!(
24674            error,
24675            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24676                if reason == "condition_wait_occurrence_id_missing"
24677        ));
24678    }
24679
24680    #[test]
24681    fn typed_search_attribute_updates_validate_emit_and_replay() {
24682        let update = SearchAttributeUpdate::new()
24683            .keyword("OrderStatus", " waiting ")
24684            .expect("keyword")
24685            .int("Attempt", 3)
24686            .expect("int")
24687            .bool("Escalated", false)
24688            .expect("bool")
24689            .keyword_list("Regions", ["us-east", "eu-west"])
24690            .expect("list")
24691            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24692            .expect("datetime")
24693            .delete("LegacyStatus")
24694            .expect("delete");
24695        let ctx = workflow_context(Vec::new());
24696        ctx.upsert_search_attributes(update.clone())
24697            .expect("typed update");
24698        assert_eq!(
24699            ctx.take_commands().expect("search-attribute command"),
24700            vec![json!({
24701                "type": "upsert_search_attributes",
24702                "attributes": {
24703                    "Attempt": 3,
24704                    "Escalated": false,
24705                    "LegacyStatus": null,
24706                    "OrderStatus": "waiting",
24707                    "Regions": ["us-east", "eu-west"],
24708                    "UpdatedAt": "2026-08-22T04:00:00Z",
24709                },
24710                "attribute_types": {
24711                    "Attempt": "int",
24712                    "Escalated": "bool",
24713                    "OrderStatus": "keyword",
24714                    "Regions": "keyword_list",
24715                    "UpdatedAt": "datetime",
24716                },
24717            })]
24718        );
24719
24720        let replay = workflow_context(vec![history_event(
24721            "SearchAttributesUpserted",
24722            json!({
24723                "sequence": 6,
24724                "attributes": {
24725                    "Attempt": 3,
24726                    "Escalated": false,
24727                    "LegacyStatus": null,
24728                    "OrderStatus": "waiting",
24729                    "Regions": ["us-east", "eu-west"],
24730                    "UpdatedAt": "2026-08-22T04:00:00Z",
24731                },
24732                "attribute_types": {
24733                    "Attempt": "int",
24734                    "Escalated": "bool",
24735                    "OrderStatus": "keyword",
24736                    "Regions": "keyword_list",
24737                    "UpdatedAt": "datetime",
24738                },
24739                "merged": {},
24740            }),
24741        )]);
24742        replay
24743            .upsert_search_attributes(update)
24744            .expect("matching update replays");
24745        assert!(replay.take_commands().expect("commands").is_empty());
24746        replay.ensure_history_consumed().expect("history consumed");
24747
24748        let type_drift = workflow_context(vec![history_event(
24749            "SearchAttributesUpserted",
24750            json!({
24751                "sequence": 7,
24752                "attributes": {"OrderStatus": "waiting"},
24753                "attribute_types": {"OrderStatus": "keyword"},
24754                "merged": {"OrderStatus": "waiting"},
24755            }),
24756        )]);
24757        let error = type_drift
24758            .upsert_search_attributes(
24759                SearchAttributeUpdate::new()
24760                    .string("OrderStatus", "waiting")
24761                    .expect("string update"),
24762            )
24763            .expect_err("same JSON value with a changed type must fail replay");
24764        assert!(matches!(
24765            error,
24766            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24767                if reason == "search_attribute_type_mismatch"
24768        ));
24769
24770        let malformed_types = WorkflowState::new(
24771            vec![history_event(
24772                "SearchAttributesUpserted",
24773                json!({
24774                    "sequence": 8,
24775                    "attributes": {"OrderStatus": "waiting"},
24776                    "attribute_types": {"OrderStatus": "unsupported"},
24777                    "merged": {"OrderStatus": "waiting"},
24778                }),
24779            )],
24780            "rust-workers".to_string(),
24781            DEFAULT_CODEC.to_string(),
24782            None,
24783        )
24784        .expect_err("unsupported search-attribute type metadata must fail");
24785        assert!(matches!(
24786            malformed_types,
24787            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24788                if reason == "search_attribute_types_malformed"
24789        ));
24790
24791        assert!(matches!(
24792            SearchAttributeUpdate::new().keyword("bad key", "value"),
24793            Err(SearchAttributeUpdateError::InvalidKey(_))
24794        ));
24795        assert!(matches!(
24796            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24797            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24798        ));
24799        assert!(matches!(
24800            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24801            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24802        ));
24803        assert!(matches!(
24804            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24805            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24806        ));
24807        assert!(matches!(
24808            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24809            Err(Error::InvalidSearchAttributeUpdate(
24810                SearchAttributeUpdateError::Empty
24811            ))
24812        ));
24813    }
24814
24815    #[test]
24816    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24817        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24818        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24819
24820        assert!(SearchAttributeUpdate::new()
24821            .string("AsciiDescription", ascii)
24822            .is_ok());
24823        assert!(SearchAttributeUpdate::new()
24824            .string("Utf8Description", utf8)
24825            .is_ok());
24826        assert!(matches!(
24827            SearchAttributeUpdate::new().string(
24828                "TooLongDescription",
24829                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24830            ),
24831            Err(SearchAttributeUpdateError::ValueTooLong {
24832                kind: "string",
24833                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24834                ..
24835            })
24836        ));
24837    }
24838
24839    #[test]
24840    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24841        let lone_fire = WorkflowState::new(
24842            vec![history_event(
24843                "TimerFired",
24844                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24845            )],
24846            "rust-workers".to_string(),
24847            DEFAULT_CODEC.to_string(),
24848            None,
24849        )
24850        .expect_err("TimerFired requires TimerScheduled");
24851        assert!(matches!(
24852            lone_fire,
24853            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24854                if reason == "timer_schedule_missing_or_duplicate"
24855        ));
24856
24857        let wrong_identity = WorkflowState::new(
24858            vec![
24859                history_event(
24860                    "TimerScheduled",
24861                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24862                ),
24863                history_event(
24864                    "TimerFired",
24865                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24866                ),
24867            ],
24868            "rust-workers".to_string(),
24869            DEFAULT_CODEC.to_string(),
24870            None,
24871        )
24872        .expect_err("fire must match scheduled timer identity");
24873        assert!(matches!(
24874            wrong_identity,
24875            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24876                if reason == "timer_identity_mismatch"
24877        ));
24878
24879        let duplicate_fire = WorkflowState::new(
24880            vec![
24881                history_event(
24882                    "TimerScheduled",
24883                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24884                ),
24885                history_event(
24886                    "TimerFired",
24887                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24888                ),
24889                history_event(
24890                    "TimerFired",
24891                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24892                ),
24893            ],
24894            "rust-workers".to_string(),
24895            DEFAULT_CODEC.to_string(),
24896            None,
24897        )
24898        .expect_err("a durable timer cannot fire twice");
24899        assert!(matches!(
24900            duplicate_fire,
24901            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24902                if reason == "duplicate_timer_fire"
24903        ));
24904
24905        let wrong_fired_delay = WorkflowState::new(
24906            vec![
24907                history_event(
24908                    "TimerScheduled",
24909                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24910                ),
24911                history_event(
24912                    "TimerFired",
24913                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24914                ),
24915            ],
24916            "rust-workers".to_string(),
24917            DEFAULT_CODEC.to_string(),
24918            None,
24919        )
24920        .expect_err("timer schedule and fire delays must agree");
24921        assert!(matches!(
24922            wrong_fired_delay,
24923            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24924                if reason == "timer_history_delay_mismatch"
24925        ));
24926    }
24927
24928    #[test]
24929    fn replay_rejects_activity_moved_before_recorded_timer() {
24930        let ctx = workflow_context(vec![
24931            history_event(
24932                "TimerScheduled",
24933                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24934            ),
24935            history_event(
24936                "TimerFired",
24937                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24938            ),
24939            history_event(
24940                "ActivityCompleted",
24941                json!({
24942                    "sequence": 2,
24943                    "activity_type": "after-timer",
24944                    "payload_codec": DEFAULT_CODEC,
24945                    "result": fixture_envelope(json!("done")),
24946                }),
24947            ),
24948        ]);
24949        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24950        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24951
24952        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24953            activity.as_mut().poll(&mut task_context)
24954        else {
24955            panic!("reordered durable command must be rejected");
24956        };
24957        assert_eq!(failure.reason, "recorded_command_mismatch");
24958        assert_eq!(failure.sequence, Some(1));
24959        assert_eq!(failure.expected.as_deref(), Some("timer"));
24960        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24961    }
24962
24963    #[test]
24964    fn workflow_context_emits_a_typed_named_signal_wait() {
24965        let ctx = workflow_context(Vec::new());
24966        let mut signal = Box::pin(ctx.wait_signal("finish"));
24967        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24968
24969        assert!(matches!(
24970            signal.as_mut().poll(&mut task_context),
24971            Poll::Pending
24972        ));
24973        assert_eq!(
24974            ctx.take_commands().expect("signal-wait command"),
24975            vec![json!({
24976                "type": "open_signal_wait",
24977                "signal_name": "finish",
24978            })]
24979        );
24980    }
24981
24982    #[test]
24983    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
24984        let ctx = workflow_context(Vec::new());
24985        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
24986        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24987
24988        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
24989        else {
24990            panic!("runtime-reserved signal should be rejected");
24991        };
24992        assert!(message.contains("reserved by the workflow runtime"));
24993        assert!(ctx.take_commands().expect("commands").is_empty());
24994    }
24995
24996    #[tokio::test]
24997    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
24998        let client = Client::builder("http://127.0.0.1:9")
24999            .build()
25000            .expect("client");
25001        let error = client
25002            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
25003            .await
25004            .expect_err("runtime-reserved signal should be rejected before transport");
25005
25006        assert!(
25007            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
25008        );
25009    }
25010
25011    #[test]
25012    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
25013        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25014            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25015                value.to_string(),
25016            )]))
25017            .expect("message payload");
25018            json!({
25019                "schema": MESSAGE_STREAM_SCHEMA,
25020                "stream_name": "orders",
25021                "message_id": message_id,
25022                "position": position,
25023                "payload_envelope": payload,
25024            })
25025        }
25026
25027        fn opened(sequence: u64) -> HistoryEvent {
25028            history_event(
25029                "SignalWaitOpened",
25030                json!({
25031                    "sequence": sequence,
25032                    "signal_name": MESSAGE_STREAM_SIGNAL,
25033                }),
25034            )
25035        }
25036
25037        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25038            history_event(
25039                "SignalApplied",
25040                json!({
25041                    "sequence": sequence,
25042                    "signal_name": MESSAGE_STREAM_SIGNAL,
25043                    "value": fixture_envelope(json!([delivery])),
25044                }),
25045            )
25046        }
25047
25048        fn received(delivery: Value) -> HistoryEvent {
25049            history_event(
25050                "SignalReceived",
25051                json!({
25052                    "signal_name": MESSAGE_STREAM_SIGNAL,
25053                    "arguments": fixture_envelope(json!([delivery])),
25054                    "payload_codec": DEFAULT_CODEC,
25055                }),
25056            )
25057        }
25058
25059        let client = Client::new("http://127.0.0.1:8080").expect("client");
25060        let mut worker = Worker::new(client, "rust-workers");
25061        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
25062            let messages = ctx.message_stream("orders")?.receive(2).await?;
25063            Ok(json!(messages
25064                .into_iter()
25065                .map(|message| message.message_id)
25066                .collect::<Vec<_>>()))
25067        });
25068
25069        let first = delivery("message-1", 1, "one");
25070        let second = delivery("message-2", 2, "two");
25071        let batch = worker
25072            .execute_workflow_task_decision(workflow_task(
25073                "rust.message-stream-batch",
25074                vec![
25075                    opened(1),
25076                    received(first.clone()),
25077                    applied(1, first.clone()),
25078                    received(first.clone()),
25079                    received(second),
25080                ],
25081                DEFAULT_CODEC,
25082            ))
25083            .expect("worker task consumes the available batch");
25084
25085        assert_eq!(batch.commands.len(), 1);
25086        assert_eq!(batch.commands[0]["type"], "complete_workflow");
25087        assert_eq!(
25088            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
25089                .expect("workflow result"),
25090            json!(["message-1", "message-2"])
25091        );
25092        assert_eq!(
25093            batch.message_stream_cursors,
25094            vec![json!({"stream_name": "orders", "through_position": 2})]
25095        );
25096        assert!(batch.message_stream_waits.is_empty());
25097
25098        let partial = worker
25099            .execute_workflow_task_decision(workflow_task(
25100                "rust.message-stream-batch",
25101                vec![opened(1), received(first.clone()), applied(1, first)],
25102                DEFAULT_CODEC,
25103            ))
25104            .expect("worker task returns without waiting for a missing second item");
25105        assert_eq!(partial.commands.len(), 1);
25106        assert_eq!(partial.commands[0]["type"], "complete_workflow");
25107        assert_eq!(
25108            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
25109                .expect("workflow result"),
25110            json!(["message-1"])
25111        );
25112        assert_eq!(
25113            partial.message_stream_cursors,
25114            vec![json!({"stream_name": "orders", "through_position": 1})]
25115        );
25116        assert!(partial.message_stream_waits.is_empty());
25117    }
25118
25119    #[test]
25120    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
25121        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25122            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25123                value.to_string(),
25124            )]))
25125            .expect("message payload");
25126            json!({
25127                "schema": MESSAGE_STREAM_SCHEMA,
25128                "stream_name": "orders",
25129                "message_id": message_id,
25130                "position": position,
25131                "payload_envelope": payload,
25132            })
25133        }
25134
25135        fn opened(sequence: u64) -> HistoryEvent {
25136            history_event(
25137                "SignalWaitOpened",
25138                json!({
25139                    "sequence": sequence,
25140                    "signal_name": MESSAGE_STREAM_SIGNAL,
25141                }),
25142            )
25143        }
25144
25145        fn received(delivery: Value) -> HistoryEvent {
25146            history_event(
25147                "SignalReceived",
25148                json!({
25149                    "signal_name": MESSAGE_STREAM_SIGNAL,
25150                    "arguments": fixture_envelope(json!([delivery])),
25151                    "payload_codec": DEFAULT_CODEC,
25152                }),
25153            )
25154        }
25155
25156        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25157            history_event(
25158                "SignalApplied",
25159                json!({
25160                    "sequence": sequence,
25161                    "signal_name": MESSAGE_STREAM_SIGNAL,
25162                    "value": fixture_envelope(json!([delivery])),
25163                }),
25164            )
25165        }
25166
25167        let client = Client::new("http://127.0.0.1:8080").expect("client");
25168        let mut worker = Worker::new(client, "rust-workers");
25169        worker.register_workflow(
25170            "rust.message-stream-partial-batches",
25171            |ctx, _input| async move {
25172                let stream = ctx.message_stream("orders")?;
25173                let first = stream.receive(10).await?;
25174                let second = stream.receive(10).await?;
25175                Ok(json!([
25176                    first
25177                        .into_iter()
25178                        .map(|message| message.message_id)
25179                        .collect::<Vec<_>>(),
25180                    second
25181                        .into_iter()
25182                        .map(|message| message.message_id)
25183                        .collect::<Vec<_>>(),
25184                ]))
25185            },
25186        );
25187
25188        let first = delivery("message-1", 1, "one");
25189        let second = delivery("message-2", 2, "two");
25190        let decision = worker
25191            .execute_workflow_task_decision(workflow_task(
25192                "rust.message-stream-partial-batches",
25193                vec![
25194                    opened(1),
25195                    received(first.clone()),
25196                    applied(1, first),
25197                    opened(2),
25198                    received(second.clone()),
25199                    applied(2, second),
25200                ],
25201                DEFAULT_CODEC,
25202            ))
25203            .expect("cold replay preserves both authored receive boundaries");
25204
25205        assert_eq!(decision.commands.len(), 1);
25206        assert_eq!(decision.commands[0]["type"], "complete_workflow");
25207        assert_eq!(
25208            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
25209                .expect("workflow result"),
25210            json!([["message-1"], ["message-2"]])
25211        );
25212        assert_eq!(
25213            decision.message_stream_cursors,
25214            vec![json!({"stream_name": "orders", "through_position": 2})]
25215        );
25216        assert!(decision.message_stream_waits.is_empty());
25217    }
25218
25219    #[test]
25220    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
25221        let ctx = workflow_context(Vec::new());
25222        let stream = ctx.message_stream("orders").expect("message stream");
25223        let mut receive = Box::pin(stream.receive(10));
25224        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25225
25226        assert!(matches!(
25227            receive.as_mut().poll(&mut task_context),
25228            Poll::Pending
25229        ));
25230        assert_eq!(
25231            ctx.take_commands().expect("message-stream wait command"),
25232            vec![json!({
25233                "type": "open_signal_wait",
25234                "signal_name": MESSAGE_STREAM_SIGNAL,
25235            })]
25236        );
25237        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25238        assert!(cursors.is_empty());
25239        assert_eq!(
25240            waits,
25241            vec![json!({"stream_name": "orders", "after_position": 0})]
25242        );
25243    }
25244
25245    #[test]
25246    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
25247        let ctx = workflow_context(vec![history_event(
25248            "SignalReceived",
25249            json!({
25250                "signal_name": MESSAGE_STREAM_SIGNAL,
25251                "arguments": fixture_envelope(json!([{
25252                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
25253                    "stream_name": "orders",
25254                    "through_position": 2,
25255                }])),
25256                "payload_codec": DEFAULT_CODEC,
25257            }),
25258        )]);
25259        let stream = ctx.message_stream("orders").expect("message stream");
25260        let mut receive = Box::pin(stream.receive(10));
25261        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25262
25263        assert!(matches!(
25264            receive.as_mut().poll(&mut task_context),
25265            Poll::Pending
25266        ));
25267        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25268        assert_eq!(
25269            cursors,
25270            vec![json!({"stream_name": "orders", "through_position": 2})]
25271        );
25272        assert_eq!(
25273            waits,
25274            vec![json!({"stream_name": "orders", "after_position": 2})]
25275        );
25276    }
25277
25278    #[test]
25279    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
25280        let mut empty_map = BTreeMap::new();
25281        let mut nested = BTreeMap::new();
25282        nested.insert(
25283            "value".to_string(),
25284            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
25285        );
25286        let values = vec![
25287            AvroValue::Bytes(vec![0, 255]),
25288            AvroValue::Long(1),
25289            AvroValue::Double(1.0),
25290            AvroValue::Array(Vec::new()),
25291            AvroValue::Map(std::mem::take(&mut empty_map)),
25292            AvroValue::Map(nested),
25293        ];
25294        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
25295        let transport = vec![json!({
25296            "schema": MESSAGE_STREAM_SCHEMA,
25297            "stream_name": "orders",
25298            "message_id": "message-1",
25299            "position": 1,
25300            "payload_envelope": payload,
25301        })];
25302
25303        for _ in 0..2 {
25304            let Some(MessageStreamDelivery::Message(message)) =
25305                decode_message_stream_delivery(transport.clone()).expect("delivery")
25306            else {
25307                panic!("message delivery expected");
25308            };
25309            assert_eq!(message.arguments, values);
25310            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
25311            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
25312        }
25313    }
25314
25315    #[test]
25316    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
25317        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25318            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25319                value.to_string(),
25320            )]))
25321            .expect("message payload");
25322            json!({
25323                "schema": MESSAGE_STREAM_SCHEMA,
25324                "stream_name": "orders",
25325                "message_id": message_id,
25326                "position": position,
25327                "payload_envelope": payload,
25328            })
25329        }
25330
25331        fn opened(sequence: u64) -> HistoryEvent {
25332            history_event(
25333                "SignalWaitOpened",
25334                json!({
25335                    "sequence": sequence,
25336                    "signal_name": MESSAGE_STREAM_SIGNAL,
25337                }),
25338            )
25339        }
25340
25341        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25342            history_event(
25343                "SignalApplied",
25344                json!({
25345                    "sequence": sequence,
25346                    "signal_name": MESSAGE_STREAM_SIGNAL,
25347                    "value": fixture_envelope(json!([delivery])),
25348                }),
25349            )
25350        }
25351
25352        fn worker() -> Worker {
25353            let client = Client::new("http://127.0.0.1:8080").expect("client");
25354            let mut worker = Worker::new(client, "rust-workers");
25355            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
25356                let stream = ctx.message_stream("orders")?;
25357                let first = stream.receive_one().await?;
25358                let second = stream.receive_one().await?;
25359                Ok(json!([first.message_id, second.message_id]))
25360            });
25361            worker
25362        }
25363
25364        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
25365            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
25366            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
25367            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
25368            task
25369        }
25370
25371        let waiting = worker()
25372            .execute_workflow_task_decision(workflow_task(
25373                "rust.message-stream",
25374                Vec::new(),
25375                DEFAULT_CODEC,
25376            ))
25377            .expect("first worker opens the stream wait");
25378        assert_eq!(
25379            waiting.commands,
25380            vec![json!({
25381                "type": "open_signal_wait",
25382                "signal_name": MESSAGE_STREAM_SIGNAL,
25383            })]
25384        );
25385        assert!(waiting.message_stream_cursors.is_empty());
25386        assert_eq!(
25387            waiting.message_stream_waits,
25388            vec![json!({"stream_name": "orders", "after_position": 0})]
25389        );
25390
25391        let first_delivery = delivery("message-1", 1, "one");
25392        let first_arrival = worker()
25393            .execute_workflow_task_decision(task_with_resume(
25394                vec![opened(1)],
25395                first_delivery.clone(),
25396            ))
25397            .expect("replacement worker consumes the first arrival");
25398        assert_eq!(
25399            first_arrival.commands,
25400            vec![json!({
25401                "type": "open_signal_wait",
25402                "signal_name": MESSAGE_STREAM_SIGNAL,
25403            })]
25404        );
25405        assert_eq!(
25406            first_arrival.message_stream_cursors,
25407            vec![json!({"stream_name": "orders", "through_position": 1})]
25408        );
25409        assert_eq!(
25410            first_arrival.message_stream_waits,
25411            vec![json!({"stream_name": "orders", "after_position": 1})]
25412        );
25413
25414        let second_delivery = delivery("message-2", 2, "two");
25415        let first_applied = applied(1, first_delivery);
25416        let completed = worker()
25417            .execute_workflow_task_decision(task_with_resume(
25418                vec![opened(1), first_applied.clone(), opened(2)],
25419                second_delivery.clone(),
25420            ))
25421            .expect("next replacement worker consumes the second arrival");
25422        assert_eq!(completed.commands.len(), 1);
25423        assert_eq!(completed.commands[0]["type"], "complete_workflow");
25424        assert_eq!(
25425            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
25426                .expect("workflow result"),
25427            json!(["message-1", "message-2"])
25428        );
25429        assert_eq!(
25430            completed.message_stream_cursors,
25431            vec![json!({"stream_name": "orders", "through_position": 2})]
25432        );
25433        assert!(completed.message_stream_waits.is_empty());
25434
25435        let replay_history = vec![
25436            opened(1),
25437            first_applied,
25438            opened(2),
25439            applied(2, second_delivery),
25440        ];
25441        for _cold_worker_or_restart in 0..2 {
25442            let replayed = worker()
25443                .execute_workflow_task_decision(workflow_task(
25444                    "rust.message-stream",
25445                    replay_history.clone(),
25446                    DEFAULT_CODEC,
25447                ))
25448                .expect("cold worker replays each logical message exactly once");
25449            assert_eq!(replayed.commands.len(), 1);
25450            assert_eq!(
25451                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
25452                    .expect("replayed workflow result"),
25453                json!(["message-1", "message-2"])
25454            );
25455            assert_eq!(
25456                replayed.message_stream_cursors,
25457                vec![json!({"stream_name": "orders", "through_position": 2})]
25458            );
25459            assert!(replayed.message_stream_waits.is_empty());
25460        }
25461    }
25462
25463    #[test]
25464    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
25465        assert!(!worker_protocol_supports_message_streams("1.14"));
25466        assert!(worker_protocol_supports_message_streams("1.15"));
25467        assert!(worker_protocol_supports_message_streams("1.16"));
25468        assert!(worker_protocol_supports_message_streams(
25469            WORKER_PROTOCOL_VERSION
25470        ));
25471        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
25472    }
25473
25474    #[test]
25475    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
25476        let ctx = workflow_context(vec![
25477            history_event(
25478                "ConditionWaitOpened",
25479                json!({
25480                    "sequence": 1,
25481                    "condition_wait_id": "condition:1",
25482                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25483                    "condition_key": "signal:finish",
25484                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25485                }),
25486            ),
25487            history_event(
25488                "ConditionWaitSatisfied",
25489                json!({
25490                    "sequence": 1,
25491                    "condition_wait_id": "condition:1",
25492                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25493                    "condition_key": "signal:finish",
25494                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25495                }),
25496            ),
25497            history_event(
25498                "SignalReceived",
25499                json!({"signal_name": "finish", "arguments": []}),
25500            ),
25501        ]);
25502        let mut signal = Box::pin(ctx.wait_signal("finish"));
25503        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25504
25505        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25506            signal.as_mut().poll(&mut task_context)
25507        else {
25508            panic!("condition history must not resolve as a typed signal wait");
25509        };
25510        assert_eq!(failure.reason, "recorded_command_mismatch");
25511        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
25512    }
25513
25514    #[test]
25515    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
25516        let signal_then_timer = vec![
25517            history_event(
25518                "SignalWaitOpened",
25519                json!({"sequence": 1, "signal_name": "go"}),
25520            ),
25521            history_event(
25522                "SignalApplied",
25523                json!({
25524                    "sequence": 1,
25525                    "signal_name": "go",
25526                    "value": fixture_envelope(json!(["now"])),
25527                }),
25528            ),
25529            history_event(
25530                "TimerScheduled",
25531                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25532            ),
25533            history_event(
25534                "TimerFired",
25535                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25536            ),
25537        ];
25538
25539        let ctx = workflow_context(signal_then_timer.clone());
25540        let mut signal = Box::pin(ctx.wait_signal("go"));
25541        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25542        assert!(matches!(
25543            signal.as_mut().poll(&mut task_context),
25544            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
25545        ));
25546        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
25547        assert!(matches!(
25548            timer.as_mut().poll(&mut task_context),
25549            Poll::Ready(Ok(()))
25550        ));
25551        ctx.ensure_history_consumed()
25552            .expect("signal and timer history consumed in order");
25553
25554        let reordered = workflow_context(signal_then_timer);
25555        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
25556        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25557            timer_first.as_mut().poll(&mut task_context)
25558        else {
25559            panic!("timer cannot consume signal-wait-first history");
25560        };
25561        assert_eq!(failure.reason, "recorded_command_mismatch");
25562        assert_eq!(failure.sequence, Some(1));
25563        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
25564
25565        let timer_then_signal = vec![
25566            history_event(
25567                "TimerScheduled",
25568                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25569            ),
25570            history_event(
25571                "TimerFired",
25572                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25573            ),
25574            history_event(
25575                "SignalWaitOpened",
25576                json!({"sequence": 2, "signal_name": "go"}),
25577            ),
25578            history_event(
25579                "SignalApplied",
25580                json!({
25581                    "sequence": 2,
25582                    "signal_name": "go",
25583                    "value": fixture_envelope(json!([])),
25584                }),
25585            ),
25586        ];
25587        let reordered = workflow_context(timer_then_signal);
25588        let mut signal_first = Box::pin(reordered.wait_signal("go"));
25589        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25590            signal_first.as_mut().poll(&mut task_context)
25591        else {
25592            panic!("signal wait cannot consume timer-first history");
25593        };
25594        assert_eq!(failure.reason, "recorded_command_mismatch");
25595        assert_eq!(failure.sequence, Some(1));
25596        assert_eq!(failure.expected.as_deref(), Some("timer"));
25597    }
25598
25599    #[test]
25600    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
25601        let duplicate_timer = WorkflowState::new(
25602            vec![
25603                history_event(
25604                    "TimerScheduled",
25605                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25606                ),
25607                history_event(
25608                    "TimerScheduled",
25609                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
25610                ),
25611            ],
25612            "rust-workers".to_string(),
25613            DEFAULT_CODEC.to_string(),
25614            None,
25615        )
25616        .expect_err("one workflow sequence cannot schedule two timers");
25617        assert!(matches!(
25618            duplicate_timer,
25619            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25620                if reason == "timer_schedule_missing_or_duplicate"
25621        ));
25622
25623        let colliding_kinds = WorkflowState::new(
25624            vec![
25625                history_event(
25626                    "TimerScheduled",
25627                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25628                ),
25629                history_event(
25630                    "ActivityCompleted",
25631                    json!({"sequence": 1, "activity_type": "same-sequence"}),
25632                ),
25633            ],
25634            "rust-workers".to_string(),
25635            DEFAULT_CODEC.to_string(),
25636            None,
25637        )
25638        .expect_err("one workflow sequence cannot identify two command kinds");
25639        assert!(matches!(
25640            colliding_kinds,
25641            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25642                if reason == "durable_command_sequence_collision"
25643        ));
25644
25645        let duplicate_signal_wait = WorkflowState::new(
25646            vec![
25647                history_event(
25648                    "SignalWaitOpened",
25649                    json!({"sequence": 1, "signal_name": "go"}),
25650                ),
25651                history_event(
25652                    "SignalWaitOpened",
25653                    json!({"sequence": 1, "signal_name": "go"}),
25654                ),
25655            ],
25656            "rust-workers".to_string(),
25657            DEFAULT_CODEC.to_string(),
25658            None,
25659        )
25660        .expect_err("one workflow sequence cannot open two signal waits");
25661        assert!(matches!(
25662            duplicate_signal_wait,
25663            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25664                if reason == "signal_wait_open_missing_or_duplicate"
25665        ));
25666    }
25667
25668    #[test]
25669    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25670        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25671            .expect("side-effect result");
25672        let ctx = workflow_context(vec![history_event(
25673            "SideEffectRecorded",
25674            json!({"sequence": 99, "result": result}),
25675        )]);
25676
25677        let replayed: Value = ctx
25678            .side_effect(|| panic!("recorded side effect must not run"))
25679            .expect("positive global workflow sequence is valid");
25680        assert_eq!(replayed, json!({"captured": true}));
25681        ctx.ensure_history_consumed().expect("history consumed");
25682    }
25683
25684    #[test]
25685    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25686        let result =
25687            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25688        let zero = WorkflowState::new(
25689            vec![history_event(
25690                "SideEffectRecorded",
25691                json!({"sequence": 0, "result": result.clone()}),
25692            )],
25693            "rust-workers".to_string(),
25694            DEFAULT_CODEC.to_string(),
25695            None,
25696        )
25697        .expect_err("durable command sequences must be positive");
25698        assert!(matches!(
25699            zero,
25700            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25701                if reason == "durable_command_sequence_invalid"
25702        ));
25703
25704        let descending = WorkflowState::new(
25705            vec![
25706                history_event(
25707                    "SideEffectRecorded",
25708                    json!({"sequence": 3, "result": result}),
25709                ),
25710                history_event(
25711                    "VersionMarkerRecorded",
25712                    json!({
25713                        "sequence": 2,
25714                        "change_id": "descending-marker",
25715                        "version": 1,
25716                        "min_supported": 1,
25717                        "max_supported": 1,
25718                    }),
25719                ),
25720            ],
25721            "rust-workers".to_string(),
25722            DEFAULT_CODEC.to_string(),
25723            None,
25724        )
25725        .expect_err("new durable commands must remain strictly ordered");
25726        let Error::NonDeterministicReplay(failure) = descending else {
25727            panic!("expected typed replay failure");
25728        };
25729        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25730        assert_eq!(failure.sequence, Some(2));
25731        assert_eq!(
25732            failure.expected.as_deref(),
25733            Some("workflow sequence greater than 3")
25734        );
25735        assert_eq!(failure.actual.as_deref(), Some("2"));
25736    }
25737
25738    #[test]
25739    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25740        fn worker() -> Worker {
25741            let client = Client::new("http://127.0.0.1:8080").expect("client");
25742            let mut worker = Worker::new(client, "rust-workers");
25743            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25744                ctx.wait_signal("finish").await?;
25745                let marker: String =
25746                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25747                assert_eq!(marker, "after-finish");
25748                Ok(json!("finished"))
25749            });
25750            worker
25751        }
25752
25753        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25754            .expect("side-effect result");
25755        let task = workflow_task(
25756            "rust.finish-after-gaps",
25757            vec![
25758                history_event(
25759                    "SignalWaitOpened",
25760                    json!({"sequence": 1, "signal_name": "finish"}),
25761                ),
25762                history_event(
25763                    "SignalReceived",
25764                    json!({
25765                        "signal_id": "increment-3",
25766                        "signal_name": "increment",
25767                        "workflow_sequence": 2,
25768                        "payload_codec": DEFAULT_CODEC,
25769                        "arguments": fixture_envelope(json!([3])),
25770                    }),
25771                ),
25772                history_event(
25773                    "SignalReceived",
25774                    json!({
25775                        "signal_id": "increment-5",
25776                        "signal_name": "increment",
25777                        "workflow_sequence": 3,
25778                        "payload_codec": DEFAULT_CODEC,
25779                        "arguments": fixture_envelope(json!([5])),
25780                    }),
25781                ),
25782                history_event(
25783                    "SignalReceived",
25784                    json!({
25785                        "signal_id": "finish",
25786                        "signal_name": "finish",
25787                        "workflow_sequence": 4,
25788                        "payload_codec": DEFAULT_CODEC,
25789                        "arguments": fixture_envelope(json!([])),
25790                    }),
25791                ),
25792                history_event(
25793                    "SignalApplied",
25794                    json!({
25795                        "sequence": 1,
25796                        "signal_id": "finish",
25797                        "signal_name": "finish",
25798                        "payload_codec": DEFAULT_CODEC,
25799                        "value": fixture_envelope(json!([])),
25800                    }),
25801                ),
25802                history_event(
25803                    "SideEffectRecorded",
25804                    json!({"sequence": 5, "result": marker}),
25805                ),
25806            ],
25807            DEFAULT_CODEC,
25808        );
25809
25810        for _original_or_cold_worker in 0..2 {
25811            let commands = worker()
25812                .execute_workflow_task(task.clone())
25813                .expect("signal gaps preserve deterministic replay");
25814            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25815            assert_eq!(commands[0]["type"], "complete_workflow");
25816            assert_eq!(
25817                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25818                json!("finished")
25819            );
25820        }
25821    }
25822
25823    #[test]
25824    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25825        let ctx = workflow_context(Vec::new());
25826        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25827        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25828        assert!(matches!(
25829            sleep.as_mut().poll(&mut task_context),
25830            Poll::Ready(Err(Error::TimerDurationOverflow))
25831        ));
25832        assert!(ctx.take_commands().expect("commands").is_empty());
25833    }
25834
25835    #[test]
25836    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25837        let entries = AvroValue::Map(BTreeMap::from([
25838            ("text".to_string(), AvroValue::String("same".to_string())),
25839            (
25840                "nested".to_string(),
25841                AvroValue::Map(BTreeMap::from([
25842                    ("beta".to_string(), AvroValue::Long(2)),
25843                    ("alpha".to_string(), AvroValue::Long(1)),
25844                ])),
25845            ),
25846            ("long".to_string(), AvroValue::Long(7)),
25847            ("double".to_string(), AvroValue::Double(7.0)),
25848            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25849        ]));
25850        let ctx = workflow_context(Vec::new());
25851        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25852        let commands = ctx.take_commands().expect("commands");
25853
25854        assert_eq!(commands.len(), 1);
25855        assert_eq!(commands[0]["type"], "upsert_memo");
25856        let server_entries = json!({
25857            "codec": "avro",
25858            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25859        });
25860        assert_eq!(
25861            commands[0]["entries"]
25862                .as_object()
25863                .expect("entries envelope")
25864                .keys()
25865                .collect::<Vec<_>>(),
25866            vec!["blob", "codec"]
25867        );
25868        assert_eq!(commands[0]["entries"], server_entries);
25869        let wire_entries =
25870            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25871        assert_eq!(wire_entries, entries);
25872
25873        let history = vec![history_event(
25874            "MemoUpserted",
25875            json!({
25876                "sequence": 1,
25877                "entries": server_entries.clone(),
25878                "merged": server_entries,
25879            }),
25880        )];
25881        let replay = workflow_context(history.clone());
25882        replay
25883            .upsert_memo(entries.clone())
25884            .expect("matching replay identity");
25885        assert!(replay.take_commands().expect("replay commands").is_empty());
25886
25887        let changed_types = AvroValue::Map(BTreeMap::from([
25888            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25889            (
25890                "nested".to_string(),
25891                AvroValue::Map(BTreeMap::from([
25892                    ("alpha".to_string(), AvroValue::Long(1)),
25893                    ("beta".to_string(), AvroValue::Long(2)),
25894                ])),
25895            ),
25896            ("long".to_string(), AvroValue::Double(7.0)),
25897            ("double".to_string(), AvroValue::Long(7)),
25898            ("binary".to_string(), AvroValue::String("same".to_string())),
25899        ]));
25900        let error = workflow_context(history)
25901            .upsert_memo(changed_types)
25902            .expect_err("memo replay identity must preserve Avro value types");
25903        assert!(matches!(
25904            error,
25905            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25906        ));
25907    }
25908
25909    #[test]
25910    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25911        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25912            .expect("memo envelope");
25913        let replay = workflow_context(vec![history_event(
25914            "MemoUpserted",
25915            json!({
25916                "sequence": 1,
25917                "entries": original.clone(),
25918                "merged": original
25919            }),
25920        )]);
25921        let error = replay
25922            .upsert_memo(json!({"stage": "changed"}))
25923            .expect_err("changed memo update must fail replay");
25924        assert!(matches!(
25925            error,
25926            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25927        ));
25928
25929        let invalid = workflow_context(Vec::new())
25930            .upsert_memo(
25931                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25932            )
25933            .expect_err("oversized key");
25934        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25935    }
25936
25937    #[test]
25938    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25939        let negative_zero = AvroValue::Map(BTreeMap::from([(
25940            "reading".to_string(),
25941            AvroValue::Double(-0.0),
25942        )]));
25943        let negative_zero_envelope =
25944            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25945        let history = vec![history_event(
25946            "MemoUpserted",
25947            json!({
25948                "sequence": 1,
25949                "entries": negative_zero_envelope.clone(),
25950                "merged": negative_zero_envelope,
25951            }),
25952        )];
25953
25954        workflow_context(history.clone())
25955            .upsert_memo(negative_zero)
25956            .expect("matching negative-zero history identity");
25957
25958        let error = workflow_context(history)
25959            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25960                "reading".to_string(),
25961                AvroValue::Double(0.0),
25962            )])))
25963            .expect_err("positive zero must not consume negative-zero memo history");
25964        assert!(matches!(
25965            error,
25966            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25967        ));
25968    }
25969
25970    #[test]
25971    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
25972        let supported = json!({
25973            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
25974            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
25975        });
25976        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
25977        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
25978            "workflow_memo_updates": {"supported": false},
25979            "supported_workflow_task_commands": ["upsert_memo"]
25980        }))));
25981        assert!(commands_use_workflow_memo_updates(&[json!({
25982            "type": "upsert_memo",
25983            "entries": {"stage": "processing"}
25984        })]));
25985    }
25986
25987    #[test]
25988    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
25989        let client = Client::new("http://127.0.0.1:8080").expect("client");
25990        let mut worker = Worker::new(client, "rust-workers");
25991        worker.register_workflow("rust.timer", |ctx, _input| async move {
25992            ctx.sleep(Duration::from_secs(5)).await?;
25993            ctx.activity("after-timer", json!([])).await
25994        });
25995
25996        let task = |history_events| WorkflowTask {
25997            task_id: "wft-rust-timer-1".to_string(),
25998            observability_context: None,
25999            dispatch_observability_context: None,
26000            observability_links: None,
26001            workflow_command_id: None,
26002            workflow_id: Some("wf-rust-timer".to_string()),
26003            run_id: Some("run-rust-timer".to_string()),
26004            workflow_type: "rust.timer".to_string(),
26005            cancel_requested: false,
26006            payload_codec: DEFAULT_CODEC.to_string(),
26007            arguments: Some(
26008                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26009            ),
26010            history_events,
26011            total_history_events: None,
26012            history_size_bytes: None,
26013            continue_as_new_recommended: None,
26014            history_budget_pressure: None,
26015            next_history_page_token: None,
26016            workflow_task_attempt: 1,
26017            workflow_signal_id: None,
26018            signal_name: None,
26019            signal_arguments: None,
26020            workflow_update_id: None,
26021            update_name: None,
26022            lease_owner: Some("rust-worker".to_string()),
26023        };
26024
26025        let initial = worker
26026            .execute_workflow_task(task(Vec::new()))
26027            .expect("initial timer task");
26028        assert_eq!(
26029            initial,
26030            vec![json!({"type": "start_timer", "delay_seconds": 5})]
26031        );
26032
26033        let activity_result =
26034            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
26035        let replayed = worker
26036            .execute_workflow_task(task(vec![
26037                history_event(
26038                    "TimerScheduled",
26039                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26040                ),
26041                history_event(
26042                    "TimerFired",
26043                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26044                ),
26045                history_event(
26046                    "ActivityCompleted",
26047                    json!({
26048                        "sequence": 2,
26049                        "activity_type": "after-timer",
26050                        "payload_codec": DEFAULT_CODEC,
26051                        "result": activity_result,
26052                    }),
26053                ),
26054            ]))
26055            .expect("replayed workflow task");
26056        assert_eq!(replayed.len(), 1);
26057        assert_eq!(replayed[0]["type"], "complete_workflow");
26058        assert_eq!(
26059            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
26060            json!("done")
26061        );
26062    }
26063
26064    #[test]
26065    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
26066        let client = Client::new("http://127.0.0.1:8080").expect("client");
26067        let mut worker = Worker::new(client, "rust-workers");
26068        worker.register_workflow("rust.continue", |ctx, _input| async move {
26069            ctx.continue_as_new_with_options(
26070                ContinueAsNewOptions::new()
26071                    .workflow_type("rust.next")
26072                    .task_queue("next-workers"),
26073                json!([2, {"cursor": "next"}]),
26074            )
26075        });
26076
26077        let commands = worker
26078            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
26079            .expect("continue-as-new command");
26080
26081        assert_eq!(commands.len(), 1);
26082        assert_eq!(commands[0]["type"], "continue_as_new");
26083        assert_eq!(commands[0]["workflow_type"], "rust.next");
26084        assert_eq!(commands[0]["queue"], "next-workers");
26085        assert_eq!(
26086            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
26087                .expect("continue-as-new arguments"),
26088            json!([2, {"cursor": "next"}])
26089        );
26090    }
26091
26092    #[test]
26093    fn continue_as_new_preserves_typed_arguments() {
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_avro_value("rust.typed-continue", |ctx, _input| async move {
26097            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
26098            unreachable!("continue-as-new returns a control-flow error")
26099        });
26100
26101        let commands = worker
26102            .execute_workflow_task(workflow_task(
26103                "rust.typed-continue",
26104                Vec::new(),
26105                DEFAULT_CODEC,
26106            ))
26107            .expect("typed continue-as-new command");
26108
26109        assert_eq!(commands[0]["type"], "continue_as_new");
26110        assert_eq!(
26111            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
26112                .expect("typed continue arguments"),
26113            AvroValue::Array(vec![typed_fidelity_probe()])
26114        );
26115    }
26116
26117    #[test]
26118    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
26119        let client = Client::new("http://127.0.0.1:8080").expect("client");
26120        let mut worker = Worker::new(client, "rust-workers");
26121        worker.register_workflow("rust.continue", |ctx, _input| async move {
26122            ctx.continue_as_new(json!([2]))
26123        });
26124        let task = workflow_task(
26125            "rust.continue",
26126            vec![history_event(
26127                "WorkflowContinuedAsNew",
26128                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
26129            )],
26130            DEFAULT_CODEC,
26131        );
26132
26133        for _worker_restart_or_redelivery in 0..2 {
26134            let commands = worker
26135                .execute_workflow_task(task.clone())
26136                .expect("recorded transition replays");
26137            assert!(
26138                commands.is_empty(),
26139                "replay must not emit another successor"
26140            );
26141        }
26142    }
26143
26144    #[test]
26145    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
26146        let ctx = workflow_context(Vec::new());
26147        let error = ctx
26148            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
26149            .expect_err("blank queue must be rejected");
26150
26151        let Error::InvalidContinueAsNewOptions(error) = error else {
26152            panic!("expected typed continue-as-new validation error");
26153        };
26154        assert_eq!(error.field, "task_queue");
26155        assert!(ctx.take_commands().expect("commands").is_empty());
26156    }
26157
26158    #[test]
26159    fn workflow_context_exposes_server_history_budget() {
26160        let client = Client::new("http://127.0.0.1:8080").expect("client");
26161        let mut worker = Worker::new(client, "rust-workers");
26162        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
26163            let budget = ctx.history_budget()?;
26164            Ok(json!({
26165                "events": budget.event_count,
26166                "bytes": budget.size_bytes,
26167                "recommended": budget.continue_as_new_recommended,
26168                "pressure": budget.pressure,
26169            }))
26170        });
26171        let task: WorkflowTask = serde_json::from_value(json!({
26172            "task_id": "task-history-budget",
26173            "workflow_type": "rust.history-budget",
26174            "payload_codec": DEFAULT_CODEC,
26175            "history_events": [],
26176            "total_history_events": 480,
26177            "history_size_bytes": 1_048_576,
26178            "continue_as_new_recommended": true,
26179            "history_budget_pressure": "continue_as_new_recommended",
26180        }))
26181        .expect("published workflow task");
26182
26183        let commands = worker
26184            .execute_workflow_task(task)
26185            .expect("history-budget workflow");
26186        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
26187        assert_eq!(result["events"], 480);
26188        assert_eq!(result["bytes"], 1_048_576);
26189        assert_eq!(result["recommended"], true);
26190        assert_eq!(result["pressure"], "continue_as_new_recommended");
26191    }
26192
26193    #[test]
26194    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
26195        let client = Client::new("http://127.0.0.1:8080").expect("client");
26196        let mut worker = Worker::new(client, "rust-workers");
26197        worker.register_workflow("rust.failing", |_ctx, _input| async move {
26198            Err(Error::Codec("rust_conformance_failure".to_string()))
26199        });
26200        let task = WorkflowTask {
26201            task_id: "wft-rust-failing-1".to_string(),
26202            observability_context: None,
26203            dispatch_observability_context: None,
26204            observability_links: None,
26205            workflow_command_id: None,
26206            workflow_id: Some("wf-rust-failing".to_string()),
26207            run_id: Some("run-rust-failing".to_string()),
26208            workflow_type: "rust.failing".to_string(),
26209            cancel_requested: false,
26210            payload_codec: DEFAULT_CODEC.to_string(),
26211            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26212            history_events: Vec::new(),
26213            total_history_events: Some(0),
26214            history_size_bytes: None,
26215            continue_as_new_recommended: None,
26216            history_budget_pressure: None,
26217            next_history_page_token: None,
26218            workflow_task_attempt: 1,
26219            workflow_signal_id: None,
26220            signal_name: None,
26221            signal_arguments: None,
26222            workflow_update_id: None,
26223            update_name: None,
26224            lease_owner: Some("rust-worker".to_string()),
26225        };
26226
26227        let commands = worker
26228            .execute_workflow_task(task)
26229            .expect("handler failure becomes a workflow command");
26230
26231        assert_eq!(commands.len(), 1);
26232        assert_eq!(commands[0]["type"], "fail_workflow");
26233        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
26234        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
26235        assert_eq!(commands[0]["non_retryable"], false);
26236        assert_eq!(
26237            commands[0]["message"],
26238            "codec error: rust_conformance_failure"
26239        );
26240        assert_eq!(
26241            commands[0]["exception"]["message"],
26242            "codec error: rust_conformance_failure"
26243        );
26244    }
26245
26246    #[test]
26247    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
26248        let client = Client::new("http://127.0.0.1:8080").expect("client");
26249        let mut worker = Worker::new(client, "rust-workers");
26250        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
26251            let _: String = ctx.side_effect(|| "captured".to_string())?;
26252            Err(Error::WorkerLoop("application failure".to_string()))
26253        });
26254
26255        let commands = worker
26256            .execute_workflow_task(workflow_task(
26257                "rust.failing-after-side-effect",
26258                Vec::new(),
26259                DEFAULT_CODEC,
26260            ))
26261            .expect("ordinary failure remains a workflow decision");
26262
26263        assert_eq!(commands.len(), 2);
26264        assert_eq!(commands[0]["type"], "record_side_effect");
26265        assert_eq!(commands[1]["type"], "fail_workflow");
26266    }
26267
26268    #[test]
26269    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
26270        let client = Client::new("http://127.0.0.1:8080").expect("client");
26271        let mut worker = Worker::new(client, "rust-workers");
26272        worker.register_workflow("rust.redrive", |ctx, _input| async move {
26273            ctx.activity("greet", json!([])).await?;
26274            Ok(Value::Null)
26275        });
26276        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
26277            match ctx.activity("greet", json!([])).await {
26278                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
26279                result => result,
26280            }
26281        });
26282
26283        let failed = history_event(
26284            "ActivityFailed",
26285            json!({
26286                "sequence": 1,
26287                "activity_type": "greet",
26288                "activity_execution_id": "activity-1",
26289                "message": "failed"
26290            }),
26291        );
26292        let commands = worker
26293            .execute_workflow_task(workflow_task(
26294                "rust.redrive",
26295                vec![failed.clone()],
26296                DEFAULT_CODEC,
26297            ))
26298            .expect("recorded failure becomes a workflow command");
26299        assert_eq!(commands[0]["type"], "fail_workflow");
26300        assert_eq!(commands[0]["failed_step_sequence"], 1);
26301        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
26302
26303        let translated = worker
26304            .execute_workflow_task(workflow_task(
26305                "rust.redrive-translated",
26306                vec![failed],
26307                DEFAULT_CODEC,
26308            ))
26309            .expect("translated failure becomes a workflow command");
26310        assert_eq!(translated[0]["type"], "fail_workflow");
26311        assert!(translated[0].get("failed_step_sequence").is_none());
26312        assert!(translated[0].get("failed_activity_execution_id").is_none());
26313
26314        let without_identity = worker
26315            .execute_workflow_task(workflow_task(
26316                "rust.redrive",
26317                vec![history_event(
26318                    "ActivityFailed",
26319                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
26320                )],
26321                DEFAULT_CODEC,
26322            ))
26323            .expect("incomplete identity still fails the workflow");
26324        assert!(without_identity[0].get("failed_step_sequence").is_none());
26325
26326        let timed_out = worker
26327            .execute_workflow_task(workflow_task(
26328                "rust.redrive",
26329                vec![history_event(
26330                    "ActivityTimedOut",
26331                    json!({
26332                        "sequence": 1,
26333                        "activity_type": "greet",
26334                        "activity_execution_id": "activity-timeout",
26335                    }),
26336                )],
26337                DEFAULT_CODEC,
26338            ))
26339            .expect("timeout still fails the workflow");
26340        assert!(timed_out[0].get("failed_step_sequence").is_none());
26341    }
26342
26343    #[test]
26344    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
26345        let client = Client::new("http://127.0.0.1:8080").expect("client");
26346        let mut worker = Worker::new(client, "rust-workers");
26347        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
26348            let first = ctx.activity("first", json!([])).await?;
26349            let second = ctx.activity("second", json!([first.clone()])).await?;
26350            Ok(json!({"first": first, "second": second}))
26351        });
26352        let first = history_event(
26353            "ActivityCompleted",
26354            json!({
26355                "sequence": 1,
26356                "activity_type": "first",
26357                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
26358                "payload_codec": DEFAULT_CODEC,
26359                "reused_from_run_id": "failed-run",
26360                "reused_activity_execution_id": "original-first",
26361            }),
26362        );
26363
26364        let retry = worker
26365            .execute_workflow_task(workflow_task(
26366                "rust.redrive-successor",
26367                vec![first.clone()],
26368                DEFAULT_CODEC,
26369            ))
26370            .expect("reused result replays before failed step");
26371        assert_eq!(retry.len(), 1);
26372        assert_eq!(retry[0]["type"], "schedule_activity");
26373        assert_eq!(retry[0]["activity_type"], "second");
26374        assert_eq!(
26375            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
26376            json!(["recorded"]),
26377        );
26378
26379        let second = history_event(
26380            "ActivityCompleted",
26381            json!({
26382                "sequence": 2,
26383                "activity_type": "second",
26384                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
26385                "payload_codec": DEFAULT_CODEC,
26386            }),
26387        );
26388        let completed = worker
26389            .execute_workflow_task(workflow_task(
26390                "rust.redrive-successor",
26391                vec![first, second],
26392                DEFAULT_CODEC,
26393            ))
26394            .expect("retried step completes the successor");
26395        assert_eq!(completed.len(), 1);
26396        assert_eq!(completed[0]["type"], "complete_workflow");
26397        assert_eq!(
26398            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
26399            json!({"first": "recorded", "second": "retried"}),
26400        );
26401    }
26402
26403    #[test]
26404    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
26405        let client = Client::new("http://127.0.0.1:8080").expect("client");
26406        let mut worker = Worker::new(client, "rust-workers");
26407        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
26408            Err(Error::WorkerLoop("application failure".to_string()))
26409        });
26410        let result =
26411            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
26412
26413        let error = worker
26414            .execute_workflow_task(workflow_task(
26415                "rust.removed-side-effect",
26416                vec![history_event(
26417                    "SideEffectRecorded",
26418                    json!({"sequence": 1, "result": result}),
26419                )],
26420                DEFAULT_CODEC,
26421            ))
26422            .expect_err("removed committed history must not become fail_workflow");
26423
26424        let Error::NonDeterministicReplay(failure) = error else {
26425            panic!("expected typed replay failure");
26426        };
26427        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26428        assert_eq!(failure.sequence, Some(1));
26429        assert_eq!(failure.expected.as_deref(), Some("side effect"));
26430    }
26431
26432    #[test]
26433    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
26434        let client = Client::new("http://127.0.0.1:8080").expect("client");
26435        let mut worker = Worker::new(client, "rust-workers");
26436        worker.register_workflow(
26437            "rust.side-effect-before-marker-error",
26438            |ctx, _input| async move {
26439                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
26440                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
26441                ctx.get_version("restart-safe", 2, 2)?;
26442                Ok(Value::Null)
26443            },
26444        );
26445
26446        let error = worker
26447            .execute_workflow_task(workflow_task(
26448                "rust.side-effect-before-marker-error",
26449                vec![history_event(
26450                    "VersionMarkerRecorded",
26451                    json!({
26452                        "sequence": 1,
26453                        "change_id": "restart-safe",
26454                        "version": 1,
26455                        "min_supported": 1,
26456                        "max_supported": 1,
26457                    }),
26458                )],
26459                DEFAULT_CODEC,
26460            ))
26461            .expect_err("replay error must return no queued workflow commands");
26462
26463        let Error::NonDeterministicReplay(failure) = error else {
26464            panic!("expected typed replay failure");
26465        };
26466        assert_eq!(failure.reason, "version_marker_incompatible_range");
26467        assert_eq!(failure.sequence, Some(1));
26468    }
26469
26470    #[test]
26471    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
26472        let client = Client::new("http://127.0.0.1:8080").expect("client");
26473        let mut worker = Worker::new(client, "rust-workers");
26474        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
26475            ctx.sleep(Duration::from_secs(5)).await?;
26476            Ok(json!({"status": "timer fired"}))
26477        });
26478
26479        let task = WorkflowTask {
26480            task_id: "wft-rust-timer-pending".to_string(),
26481            observability_context: None,
26482            dispatch_observability_context: None,
26483            observability_links: None,
26484            workflow_command_id: None,
26485            workflow_id: Some("wf-rust-timer".to_string()),
26486            run_id: Some("run-rust-timer".to_string()),
26487            workflow_type: "rust.timer.pending".to_string(),
26488            cancel_requested: false,
26489            payload_codec: DEFAULT_CODEC.to_string(),
26490            arguments: Some(
26491                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26492            ),
26493            history_events: vec![history_event(
26494                "TimerScheduled",
26495                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26496            )],
26497            total_history_events: Some(1),
26498            history_size_bytes: None,
26499            continue_as_new_recommended: None,
26500            history_budget_pressure: None,
26501            next_history_page_token: None,
26502            workflow_task_attempt: 1,
26503            workflow_signal_id: None,
26504            signal_name: None,
26505            signal_arguments: None,
26506            workflow_update_id: None,
26507            update_name: None,
26508            lease_owner: Some("rust-worker".to_string()),
26509        };
26510
26511        for _redelivery_or_restart in 0..2 {
26512            let commands = worker
26513                .execute_workflow_task(task.clone())
26514                .expect("recorded timer remains pending");
26515            assert!(
26516                commands.is_empty(),
26517                "recorded timer must not be rescheduled"
26518            );
26519        }
26520    }
26521
26522    #[test]
26523    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
26524        let client = Client::new("http://127.0.0.1:8080").expect("client");
26525        let mut worker = Worker::new(client, "rust-workers");
26526        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
26527            Ok(json!({"status": "completed"}))
26528        });
26529        let task = WorkflowTask {
26530            task_id: "wft-rust-timer-removed".to_string(),
26531            observability_context: None,
26532            dispatch_observability_context: None,
26533            observability_links: None,
26534            workflow_command_id: None,
26535            workflow_id: Some("wf-rust-timer".to_string()),
26536            run_id: Some("run-rust-timer".to_string()),
26537            workflow_type: "rust.timer.removed".to_string(),
26538            cancel_requested: false,
26539            payload_codec: DEFAULT_CODEC.to_string(),
26540            arguments: Some(
26541                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26542            ),
26543            history_events: vec![
26544                history_event(
26545                    "TimerScheduled",
26546                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26547                ),
26548                history_event(
26549                    "TimerFired",
26550                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26551                ),
26552            ],
26553            total_history_events: Some(2),
26554            history_size_bytes: None,
26555            continue_as_new_recommended: None,
26556            history_budget_pressure: None,
26557            next_history_page_token: None,
26558            workflow_task_attempt: 1,
26559            workflow_signal_id: None,
26560            signal_name: None,
26561            signal_arguments: None,
26562            workflow_update_id: None,
26563            update_name: None,
26564            lease_owner: Some("rust-worker".to_string()),
26565        };
26566
26567        let Error::NonDeterministicReplay(failure) = worker
26568            .execute_workflow_task(task)
26569            .expect_err("removed timer must fail replay")
26570        else {
26571            panic!("expected typed replay failure");
26572        };
26573        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26574        assert_eq!(failure.sequence, Some(1));
26575    }
26576
26577    #[test]
26578    fn workflow_context_emits_explicit_child_workflow_contract() {
26579        let ctx = WorkflowContext {
26580            cancellation_scope_id: "root".into(),
26581            state: Arc::new(Mutex::new(
26582                WorkflowState::new_with_identity(
26583                    Vec::new(),
26584                    Some("wf-parent".to_string()),
26585                    Some("run-parent".to_string()),
26586                    "parent-workers".to_string(),
26587                    DEFAULT_CODEC.to_string(),
26588                    None,
26589                )
26590                .expect("workflow state"),
26591            )),
26592        };
26593        let options = ChildWorkflowOptions::new("python-workers")
26594            .parent_close_policy(ParentClosePolicy::RequestCancel)
26595            .retry_policy(ChildWorkflowRetryPolicy {
26596                max_attempts: Some(3),
26597                backoff_seconds: vec![1, 5],
26598                non_retryable_error_types: vec!["ValidationError".to_string()],
26599            })
26600            .execution_timeout_seconds(600)
26601            .run_timeout_seconds(120);
26602        let mut call = Box::pin(ctx.start_child_workflow(
26603            "python.fulfil-order",
26604            options,
26605            json!([{"order_id": "order-42"}]),
26606        ));
26607        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26608
26609        assert!(matches!(
26610            call.as_mut().poll(&mut task_context),
26611            Poll::Pending
26612        ));
26613        let commands = ctx.take_commands().expect("commands");
26614        assert_eq!(commands.len(), 1);
26615        let command = &commands[0];
26616        assert_eq!(command["type"], "start_child_workflow");
26617        assert_eq!(command["workflow_type"], "python.fulfil-order");
26618        assert_eq!(command["queue"], "python-workers");
26619        assert_eq!(command["parent_close_policy"], "request_cancel");
26620        assert_eq!(command["retry_policy"]["max_attempts"], 3);
26621        assert_eq!(command["execution_timeout_seconds"], 600);
26622        assert_eq!(command["run_timeout_seconds"], 120);
26623        assert_eq!(
26624            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
26625            json!([{"order_id": "order-42"}])
26626        );
26627    }
26628
26629    fn child_parent_worker() -> Worker {
26630        let client = Client::new("http://127.0.0.1:8080").expect("client");
26631        let mut worker = Worker::new(client, "rust-parent-workers");
26632        worker.register_workflow("rust.parent", |ctx, _input| async move {
26633            let child = ctx
26634                .start_child_workflow(
26635                    "python.child",
26636                    ChildWorkflowOptions::new("python-child-workers")
26637                        .parent_close_policy(ParentClosePolicy::Terminate),
26638                    json!([{"codec_probe": [1, true, "rust"]}]),
26639                )
26640                .await?;
26641            Ok(json!({
26642                "parent_workflow_id": child.parent.workflow_id,
26643                "parent_run_id": child.parent.run_id,
26644                "child_workflow_id": child.child.workflow_id,
26645                "child_run_id": child.child.run_id,
26646                "child_workflow_type": child.child_workflow_type,
26647                "result": child.result,
26648            }))
26649        });
26650        worker
26651    }
26652
26653    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26654        WorkflowTask {
26655            task_id: "wft-child-parent".to_string(),
26656            observability_context: None,
26657            dispatch_observability_context: None,
26658            observability_links: None,
26659            workflow_command_id: None,
26660            workflow_id: Some("wf-parent".to_string()),
26661            run_id: Some("run-parent".to_string()),
26662            workflow_type: "rust.parent".to_string(),
26663            cancel_requested: false,
26664            payload_codec: DEFAULT_CODEC.to_string(),
26665            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26666            history_events: vec![
26667                HistoryEvent {
26668                    event_type: "ChildWorkflowScheduled".to_string(),
26669                    payload: json!({
26670                        "sequence": 1,
26671                        "child_call_id": "call-child",
26672                        "child_workflow_instance_id": "wf-child",
26673                        "child_workflow_run_id": "run-child",
26674                        "child_workflow_type": "python.child",
26675                        "parent_close_policy": "terminate",
26676                    }),
26677                    raw: HashMap::new(),
26678                },
26679                HistoryEvent {
26680                    event_type: event_type.to_string(),
26681                    payload,
26682                    raw: HashMap::new(),
26683                },
26684            ],
26685            total_history_events: Some(2),
26686            history_size_bytes: None,
26687            continue_as_new_recommended: None,
26688            history_budget_pressure: None,
26689            next_history_page_token: None,
26690            workflow_task_attempt: 1,
26691            workflow_signal_id: None,
26692            signal_name: None,
26693            signal_arguments: None,
26694            workflow_update_id: None,
26695            update_name: None,
26696            lease_owner: Some("rust-worker".to_string()),
26697        }
26698    }
26699
26700    #[test]
26701    fn committed_child_result_replays_without_starting_a_duplicate() {
26702        let worker = child_parent_worker();
26703        let task = child_parent_task(
26704            "ChildRunCompleted",
26705            json!({
26706                "sequence": 1,
26707                "child_call_id": "call-child",
26708                "child_workflow_instance_id": "wf-child",
26709                "child_workflow_run_id": "run-child",
26710                "child_workflow_type": "python.child",
26711                "payload_codec": DEFAULT_CODEC,
26712                "result": fixture_envelope(json!({"from":"python","ok":true})),
26713            }),
26714        );
26715
26716        for _restart in 0..2 {
26717            let commands = worker
26718                .execute_workflow_task(task.clone())
26719                .expect("replayed parent task");
26720            assert_eq!(commands.len(), 1);
26721            assert_eq!(commands[0]["type"], "complete_workflow");
26722            assert!(!commands
26723                .iter()
26724                .any(|command| command["type"] == "start_child_workflow"));
26725            let output =
26726                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26727            assert_eq!(output["parent_workflow_id"], "wf-parent");
26728            assert_eq!(output["parent_run_id"], "run-parent");
26729            assert_eq!(output["child_workflow_id"], "wf-child");
26730            assert_eq!(output["child_run_id"], "run-child");
26731            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26732        }
26733    }
26734
26735    #[test]
26736    fn typed_child_arguments_and_results_survive_replay() {
26737        let client = Client::new("http://127.0.0.1:8080").expect("client");
26738        let mut worker = Worker::new(client, "rust-parent-workers");
26739        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26740            let child = ctx
26741                .start_child_workflow_avro_value(
26742                    "python.typed-child",
26743                    ChildWorkflowOptions::new("python-workers"),
26744                    AvroValue::Array(vec![typed_fidelity_probe()]),
26745                )
26746                .await?;
26747            Ok(child.result)
26748        });
26749
26750        let initial = worker
26751            .execute_workflow_task(workflow_task(
26752                "rust.typed-parent",
26753                Vec::new(),
26754                DEFAULT_CODEC,
26755            ))
26756            .expect("typed child start");
26757        assert_eq!(initial[0]["type"], "start_child_workflow");
26758        assert_eq!(
26759            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26760                .expect("typed child arguments"),
26761            AvroValue::Array(vec![typed_fidelity_probe()])
26762        );
26763
26764        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26765            .expect("typed child result");
26766        let task = workflow_task(
26767            "rust.typed-parent",
26768            vec![
26769                history_event(
26770                    "ChildWorkflowScheduled",
26771                    json!({
26772                        "sequence": 1,
26773                        "child_call_id": "call-typed",
26774                        "child_workflow_instance_id": "wf-child",
26775                        "child_workflow_run_id": "run-child",
26776                        "child_workflow_type": "python.typed-child",
26777                    }),
26778                ),
26779                history_event(
26780                    "ChildRunCompleted",
26781                    json!({
26782                        "sequence": 1,
26783                        "child_call_id": "call-typed",
26784                        "child_workflow_instance_id": "wf-child",
26785                        "child_workflow_run_id": "run-child",
26786                        "child_workflow_type": "python.typed-child",
26787                        "payload_codec": DEFAULT_CODEC,
26788                        "result": result,
26789                    }),
26790                ),
26791            ],
26792            DEFAULT_CODEC,
26793        );
26794
26795        let commands = worker
26796            .execute_workflow_task(task)
26797            .expect("typed child replay");
26798        assert_eq!(commands[0]["type"], "complete_workflow");
26799        assert_eq!(
26800            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26801                .expect("typed parent result"),
26802            typed_fidelity_probe()
26803        );
26804    }
26805
26806    #[test]
26807    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26808        let worker = child_parent_worker();
26809        let mut task = child_parent_task("unused", Value::Null);
26810        task.history_events.truncate(1);
26811        task.total_history_events = Some(1);
26812
26813        for _redelivery_or_restart in 0..2 {
26814            let commands = worker
26815                .execute_workflow_task(task.clone())
26816                .expect("recorded child remains pending");
26817            assert!(
26818                commands.is_empty(),
26819                "recorded pending child must not be started again"
26820            );
26821        }
26822    }
26823
26824    #[test]
26825    fn child_cancellation_becomes_stable_parent_failure_command() {
26826        let worker = child_parent_worker();
26827        let task = child_parent_task(
26828            "ChildRunCancelled",
26829            json!({
26830                "sequence": 1,
26831                "child_workflow_instance_id": "wf-child",
26832                "child_workflow_run_id": "run-child",
26833                "child_workflow_type": "python.child",
26834                "failure_id": "failure-child",
26835                "failure_category": "cancelled",
26836                "message": "cancelled by parent-close policy",
26837            }),
26838        );
26839
26840        let commands = worker
26841            .execute_workflow_task(task)
26842            .expect("parent settlement");
26843        assert_eq!(commands.len(), 1);
26844        assert_eq!(commands[0]["type"], "fail_workflow");
26845        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26846        assert_eq!(
26847            commands[0]["exception"]["properties"]["reason"],
26848            "cancelled"
26849        );
26850        assert_eq!(
26851            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26852            "run-child"
26853        );
26854    }
26855
26856    #[test]
26857    fn workflow_can_handle_typed_child_failure() {
26858        let client = Client::new("http://127.0.0.1:8080").expect("client");
26859        let mut worker = Worker::new(client, "rust-parent-workers");
26860        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26861            match ctx
26862                .start_child_workflow(
26863                    "python.child",
26864                    ChildWorkflowOptions::new("python-child-workers"),
26865                    json!([]),
26866                )
26867                .await
26868            {
26869                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26870                    "reason": failure.reason,
26871                    "failure_id": failure.failure_id,
26872                    "exception_class": failure.exception_class,
26873                    "child_run_id": failure.child_workflow_run_id,
26874                })),
26875                Err(error) => Err(error),
26876                Ok(_) => Err(Error::WorkerLoop(
26877                    "child unexpectedly succeeded".to_string(),
26878                )),
26879            }
26880        });
26881        let mut task = child_parent_task(
26882            "ChildRunFailed",
26883            json!({
26884                "sequence": 1,
26885                "child_workflow_instance_id": "wf-child",
26886                "child_workflow_run_id": "run-child",
26887                "child_workflow_type": "python.child",
26888                "failure_id": "failure-child",
26889                "failure_category": "child_workflow",
26890                "message": "payment rejected",
26891                "exception": {
26892                    "type": "PaymentRejected",
26893                    "class": "payments.PaymentRejected",
26894                    "message": "payment rejected"
26895                }
26896            }),
26897        );
26898        task.workflow_type = "rust.handled-parent".to_string();
26899        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26900
26901        let commands = worker.execute_workflow_task(task).expect("handled failure");
26902        assert_eq!(commands[0]["type"], "complete_workflow");
26903        let output =
26904            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26905        assert_eq!(output["reason"], "child_workflow");
26906        assert_eq!(output["failure_id"], "failure-child");
26907        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26908        assert_eq!(output["child_run_id"], "run-child");
26909    }
26910
26911    #[test]
26912    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26913        let client = Client::new("http://127.0.0.1:8080").expect("client");
26914        let mut worker = Worker::new(client, "rust-workers");
26915
26916        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26917            let signal = ctx.wait_signal("start").await?;
26918            let name = signal
26919                .first()
26920                .and_then(|value| value.as_str())
26921                .unwrap_or("world");
26922            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26923            Ok(json!({
26924                "greeting": greeting,
26925                "language": "rust"
26926            }))
26927        });
26928
26929        let signal_arguments =
26930            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26931        let task = WorkflowTask {
26932            task_id: "wft-rust-signal-1".to_string(),
26933            observability_context: None,
26934            dispatch_observability_context: None,
26935            observability_links: None,
26936            workflow_command_id: None,
26937            workflow_id: Some("wf-rust-hello".to_string()),
26938            run_id: Some("run-rust-hello".to_string()),
26939            workflow_type: "rust.hello_workflow".to_string(),
26940            cancel_requested: false,
26941            payload_codec: DEFAULT_CODEC.to_string(),
26942            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26943            history_events: vec![HistoryEvent {
26944                event_type: "SignalReceived".to_string(),
26945                payload: json!({
26946                    "signal_id": "sig-rust-1",
26947                    "signal_name": "start"
26948                }),
26949                raw: HashMap::new(),
26950            }],
26951            total_history_events: Some(1),
26952            history_size_bytes: None,
26953            continue_as_new_recommended: None,
26954            history_budget_pressure: None,
26955            next_history_page_token: None,
26956            workflow_task_attempt: 1,
26957            workflow_signal_id: Some("sig-rust-1".to_string()),
26958            signal_name: Some("start".to_string()),
26959            signal_arguments: Some(signal_arguments),
26960            workflow_update_id: None,
26961            update_name: None,
26962            lease_owner: Some("rust-worker".to_string()),
26963        };
26964
26965        let commands = worker.execute_workflow_task(task).expect("workflow task");
26966
26967        assert_eq!(commands.len(), 1);
26968        assert_eq!(commands[0]["type"], "schedule_activity");
26969        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26970        assert_eq!(
26971            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
26972            json!(["Rust"])
26973        );
26974    }
26975
26976    #[test]
26977    fn workflow_task_appends_paginated_history_events() {
26978        let mut task = WorkflowTask {
26979            task_id: "wft-rust-pages-1".to_string(),
26980            observability_context: None,
26981            dispatch_observability_context: None,
26982            observability_links: None,
26983            workflow_command_id: None,
26984            workflow_id: Some("wf-rust-pages".to_string()),
26985            run_id: Some("run-rust-pages".to_string()),
26986            workflow_type: "rust.hello_workflow".to_string(),
26987            cancel_requested: false,
26988            payload_codec: DEFAULT_CODEC.to_string(),
26989            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26990            history_events: vec![HistoryEvent {
26991                event_type: "WorkflowStarted".to_string(),
26992                payload: json!({}),
26993                raw: HashMap::new(),
26994            }],
26995            total_history_events: Some(3),
26996            history_size_bytes: None,
26997            continue_as_new_recommended: None,
26998            history_budget_pressure: None,
26999            next_history_page_token: Some("MQ==".to_string()),
27000            workflow_task_attempt: 1,
27001            workflow_signal_id: None,
27002            signal_name: None,
27003            signal_arguments: None,
27004            workflow_update_id: None,
27005            update_name: None,
27006            lease_owner: Some("rust-worker".to_string()),
27007        };
27008
27009        task.append_history_page(WorkflowTaskHistoryPage {
27010            history_events: vec![
27011                HistoryEvent {
27012                    event_type: "SignalReceived".to_string(),
27013                    payload: json!({
27014                        "signal_id": "sig-rust-1",
27015                        "signal_name": "start",
27016                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
27017                            .expect("signal arguments")
27018                    }),
27019                    raw: HashMap::new(),
27020                },
27021                HistoryEvent {
27022                    event_type: "MarkerRecorded".to_string(),
27023                    payload: json!({"sequence": 3}),
27024                    raw: HashMap::new(),
27025                },
27026            ],
27027            total_history_events: Some(3),
27028            next_history_page_token: None,
27029        });
27030
27031        assert_eq!(task.history_events.len(), 3);
27032        assert_eq!(task.total_history_events, Some(3));
27033        assert_eq!(task.next_history_page_token, None);
27034
27035        let signal = task
27036            .history_events
27037            .iter()
27038            .find(|event| event.event_type == "SignalReceived")
27039            .expect("signal event");
27040        assert_eq!(
27041            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
27042            vec![AvroValue::String("Rust".to_string())]
27043        );
27044    }
27045
27046    #[tokio::test]
27047    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
27048        let client = Client::new("http://127.0.0.1:8080").expect("client");
27049        let mut worker = Worker::new(client, "rust-workers");
27050        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27051        worker.register_query("counter", "current", |ctx, _args| async move {
27052            let mut count = 0_i64;
27053            for signal in ctx.signal_events() {
27054                let value = signal
27055                    .arguments
27056                    .first()
27057                    .and_then(Value::as_i64)
27058                    .unwrap_or_default();
27059                match signal.name.as_str() {
27060                    "increment" => count += value,
27061                    "set" => count = value,
27062                    _ => {}
27063                }
27064            }
27065            Ok(json!(count))
27066        });
27067
27068        let task = QueryTask {
27069            query_task_id: "query-rust-counter".to_string(),
27070            observability_context: None,
27071            dispatch_observability_context: None,
27072            observability_links: None,
27073            query_task_attempt: 1,
27074            lease_owner: Some("rust-worker".to_string()),
27075            workflow_id: Some("counter-1".to_string()),
27076            run_id: Some("run-counter-1".to_string()),
27077            workflow_type: "counter".to_string(),
27078            query_name: "current".to_string(),
27079            payload_codec: DEFAULT_CODEC.to_string(),
27080            workflow_arguments: Some(
27081                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27082            ),
27083            query_arguments: Some(
27084                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
27085            ),
27086            history_events: vec![
27087                HistoryEvent {
27088                    event_type: "SignalReceived".to_string(),
27089                    payload: json!({
27090                        "signal_id": "php-signal-1",
27091                        "signal_name": "increment",
27092                        "workflow_sequence": 1,
27093                        "payload_codec": DEFAULT_CODEC,
27094                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
27095                    }),
27096                    raw: HashMap::new(),
27097                },
27098                HistoryEvent {
27099                    event_type: "SignalReceived".to_string(),
27100                    payload: json!({
27101                        "signal_id": "python-signal-2",
27102                        "signal_name": "increment",
27103                        "workflow_sequence": 2,
27104                        "payload_codec": DEFAULT_CODEC,
27105                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
27106                    }),
27107                    raw: HashMap::new(),
27108                },
27109                HistoryEvent {
27110                    event_type: "SignalReceived".to_string(),
27111                    payload: json!({
27112                        "signal_id": "rust-signal-3",
27113                        "signal_name": "set",
27114                        "workflow_sequence": 3,
27115                        "payload_codec": DEFAULT_CODEC,
27116                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
27117                    }),
27118                    raw: HashMap::new(),
27119                },
27120            ],
27121            history_export: None,
27122            run_status: Some("completed".to_string()),
27123        };
27124
27125        let result = worker.execute_query_task(task).await.expect("query result");
27126        assert_eq!(result.into_json().expect("query projection"), json!(0));
27127    }
27128
27129    #[tokio::test]
27130    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
27131        let worker = replay_counter_worker();
27132        let running_history = json!([
27133            {
27134                "type": "ActivityCompleted",
27135                "payload": {
27136                    "sequence": 1,
27137                    "activity_type": "load-counter",
27138                    "payload_codec": DEFAULT_CODEC,
27139                    "result": fixture_envelope(json!("loaded"))
27140                }
27141            },
27142            {
27143                "type": "SignalWaitOpened",
27144                "payload": {
27145                    "sequence": 3,
27146                    "signal_name": "increment"
27147                }
27148            },
27149            {
27150                "type": "SignalReceived",
27151                "payload": {
27152                    "signal_id": "signal-3",
27153                    "signal_name": "increment",
27154                    "workflow_sequence": 2,
27155                    "payload_codec": DEFAULT_CODEC,
27156                    "arguments": fixture_envelope(json!([3]))
27157                }
27158            },
27159            {
27160                "type": "SignalApplied",
27161                "payload": {
27162                    "sequence": 3,
27163                    "signal_id": "signal-3",
27164                    "signal_name": "increment",
27165                    "payload_codec": DEFAULT_CODEC,
27166                    "value": fixture_envelope(json!([3]))
27167                }
27168            }
27169        ]);
27170
27171        let running = worker
27172            .execute_query_task(replay_counter_query(
27173                "current",
27174                running_history.clone(),
27175                "running",
27176            ))
27177            .await
27178            .expect("running replay query");
27179        assert_eq!(
27180            running.clone().into_json().expect("query projection"),
27181            json!({"loaded": "loaded", "count": 3, "finished": false})
27182        );
27183
27184        let detached = worker
27185            .execute_query_task(replay_counter_query(
27186                "detached-mutation",
27187                running_history.clone(),
27188                "running",
27189            ))
27190            .await
27191            .expect("query mutates only its detached state clone");
27192        assert_eq!(detached.into_json().expect("query projection"), json!(999));
27193        let failed = worker
27194            .execute_query_task(replay_counter_query(
27195                "failed-mutation",
27196                running_history.clone(),
27197                "running",
27198            ))
27199            .await
27200            .expect_err("failed query");
27201        assert_eq!(failed.reason, "query_rejected");
27202        let unchanged = worker
27203            .execute_query_task(replay_counter_query("current", running_history, "running"))
27204            .await
27205            .expect("later query reconstructs unchanged state");
27206        assert_eq!(unchanged, running);
27207
27208        let restarted_worker = replay_counter_worker();
27209        let empty_arguments = fixture_envelope(json!([]));
27210        let loaded_result = fixture_envelope(json!("loaded"));
27211        let signal_three = fixture_blob(json!([3]));
27212        let signal_five = fixture_blob(json!([5]));
27213        let restarted_task: QueryTask = serde_json::from_value(json!({
27214            "query_task_id": "query-after-restart",
27215            "workflow_id": "counter-1",
27216            "run_id": "run-counter-1",
27217            "workflow_type": "replay-counter",
27218            "query_name": "current",
27219            "payload_codec": DEFAULT_CODEC,
27220            "workflow_arguments": empty_arguments.clone(),
27221            "query_arguments": empty_arguments,
27222            "history_events": [],
27223            "history_export": {
27224                "payloads": {"codec": DEFAULT_CODEC},
27225                "history_events": [
27226                    {
27227                        "type": "ActivityCompleted",
27228                        "payload": {
27229                            "sequence": 1,
27230                            "activity_type": "load-counter",
27231                            "payload_codec": DEFAULT_CODEC,
27232                            "result": null
27233                        }
27234                    },
27235                    {
27236                        "type": "SignalWaitOpened",
27237                        "payload": {
27238                            "sequence": 3,
27239                            "signal_name": "increment"
27240                        }
27241                    },
27242                    {
27243                        "type": "SignalReceived",
27244                        "payload": {
27245                            "signal_id": "signal-3",
27246                            "signal_name": "increment",
27247                            "workflow_sequence": 2
27248                        }
27249                    },
27250                    {
27251                        "type": "SignalApplied",
27252                        "payload": {
27253                            "sequence": 3,
27254                            "signal_id": "signal-3",
27255                            "signal_name": "increment"
27256                        }
27257                    },
27258                    {
27259                        "type": "SignalWaitOpened",
27260                        "payload": {
27261                            "sequence": 5,
27262                            "signal_name": "increment"
27263                        }
27264                    },
27265                    {
27266                        "type": "SignalReceived",
27267                        "payload": {
27268                            "signal_id": "signal-5",
27269                            "signal_name": "increment",
27270                            "workflow_sequence": 4
27271                        }
27272                    },
27273                    {
27274                        "type": "SignalApplied",
27275                        "payload": {
27276                            "sequence": 5,
27277                            "signal_id": "signal-5",
27278                            "signal_name": "increment"
27279                        }
27280                    }
27281                ],
27282                "activities": [{
27283                    "sequence": 1,
27284                    "activity_type": "load-counter",
27285                    "payload_codec": DEFAULT_CODEC,
27286                    "result": loaded_result
27287                }],
27288                "signals": [
27289                    {
27290                        "id": "signal-3",
27291                        "name": "increment",
27292                        "workflow_sequence": 2,
27293                        "payload_codec": DEFAULT_CODEC,
27294                        "arguments": signal_three
27295                    },
27296                    {
27297                        "id": "signal-5",
27298                        "name": "increment",
27299                        "workflow_sequence": 4,
27300                        "payload_codec": DEFAULT_CODEC,
27301                        "arguments": signal_five
27302                    }
27303                ]
27304            },
27305            "run_status": "completed"
27306        }))
27307        .expect("cold replay query task");
27308        let completed = restarted_worker
27309            .execute_query_task(restarted_task)
27310            .await
27311            .expect("completed cold replay query");
27312        assert_eq!(
27313            completed.into_json().expect("query projection"),
27314            json!({"loaded": "loaded", "count": 8, "finished": true})
27315        );
27316    }
27317
27318    #[tokio::test]
27319    async fn replayed_query_replay_failures_are_machine_readable() {
27320        let worker = replay_counter_worker();
27321        let task = replay_counter_query(
27322            "current",
27323            json!([{
27324                "type": "ActivityCompleted",
27325                "payload": {
27326                    "sequence": 1,
27327                    "payload_codec": DEFAULT_CODEC,
27328                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
27329                }
27330            }]),
27331            "running",
27332        );
27333        let failure = worker
27334            .execute_query_task(task)
27335            .await
27336            .expect_err("invalid replay history payload");
27337        assert_eq!(failure.reason, "query_payload_decode_failed");
27338        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
27339        assert!(failure.message.contains("invalid_payload_framing"));
27340    }
27341
27342    #[tokio::test]
27343    async fn query_task_restores_compact_history_from_export() {
27344        let client = Client::new("http://127.0.0.1:8080").expect("client");
27345        let mut worker = Worker::new(client, "rust-workers");
27346        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27347        worker.register_query("counter", "current", |ctx, _args| async move {
27348            Ok(json!(ctx.signals("increment")[0][0]))
27349        });
27350        let empty_arguments = fixture_envelope(json!([]));
27351        let exported_signal = fixture_blob(json!([9]));
27352        let task: QueryTask = serde_json::from_value(json!({
27353            "query_task_id": "query-export",
27354            "workflow_type": "counter",
27355            "query_name": "current",
27356            "payload_codec": DEFAULT_CODEC,
27357            "workflow_arguments": empty_arguments.clone(),
27358            "query_arguments": empty_arguments,
27359            "history_events": [],
27360            "history_export": {
27361                "payloads": {"codec": DEFAULT_CODEC},
27362                "history_events": [{
27363                    "type": "SignalReceived",
27364                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
27365                }],
27366                "signals": [{
27367                    "id": "signal-export",
27368                    "name": "increment",
27369                    "status": "applied",
27370                    "workflow_sequence": 1,
27371                    "payload_codec": DEFAULT_CODEC,
27372                    "arguments": exported_signal
27373                }]
27374            }
27375        }))
27376        .expect("query task");
27377
27378        let result = worker.execute_query_task(task).await.expect("query result");
27379        assert_eq!(result.into_json().expect("query projection"), json!(9));
27380    }
27381
27382    #[tokio::test]
27383    async fn query_task_failures_have_stable_reasons() {
27384        let client = Client::new("http://127.0.0.1:8080").expect("client");
27385        let mut worker = Worker::new(client, "rust-workers");
27386        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27387        worker.register_query(
27388            "counter",
27389            "current",
27390            |_ctx, _args| async move { Ok(json!(0)) },
27391        );
27392
27393        let base_task = QueryTask {
27394            query_task_id: "query-errors".to_string(),
27395            observability_context: None,
27396            dispatch_observability_context: None,
27397            observability_links: None,
27398            query_task_attempt: 1,
27399            lease_owner: None,
27400            workflow_id: Some("counter-errors".to_string()),
27401            run_id: Some("run-errors".to_string()),
27402            workflow_type: "counter".to_string(),
27403            query_name: "missing".to_string(),
27404            payload_codec: DEFAULT_CODEC.to_string(),
27405            workflow_arguments: Some(fixture_envelope(json!([]))),
27406            query_arguments: Some(fixture_envelope(json!([]))),
27407            history_events: Vec::new(),
27408            history_export: None,
27409            run_status: Some("running".to_string()),
27410        };
27411
27412        let unknown = worker
27413            .execute_query_task(base_task.clone())
27414            .await
27415            .expect_err("unknown query");
27416        assert_eq!(unknown.reason, "rejected_unknown_query");
27417
27418        let mut malformed = base_task;
27419        malformed.query_name = "current".to_string();
27420        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
27421        let malformed = worker
27422            .execute_query_task(malformed)
27423            .await
27424            .expect_err("malformed payload");
27425        assert_eq!(malformed.reason, "query_payload_decode_failed");
27426
27427        let client = Client::new("http://127.0.0.1:8080").expect("client");
27428        let mut unavailable_worker = Worker::new(client, "rust-workers");
27429        unavailable_worker
27430            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27431        let empty_arguments = fixture_envelope(json!([]));
27432        let unavailable_task: QueryTask = serde_json::from_value(json!({
27433            "query_task_id": "query-unavailable",
27434            "workflow_type": "counter",
27435            "query_name": "current",
27436            "payload_codec": DEFAULT_CODEC,
27437            "workflow_arguments": empty_arguments.clone(),
27438            "query_arguments": empty_arguments
27439        }))
27440        .expect("query task");
27441        let unavailable = unavailable_worker
27442            .execute_query_task(unavailable_task)
27443            .await
27444            .expect_err("query handler unavailable");
27445        assert_eq!(unavailable.reason, "query_handler_unavailable");
27446    }
27447
27448    #[tokio::test]
27449    async fn client_query_decodes_result_and_typed_failure() {
27450        let server = MockWorkerServer::start();
27451        let client = Client::builder(server.base_url())
27452            .timeout(Duration::from_secs(2))
27453            .build()
27454            .expect("client");
27455
27456        let result = client
27457            .query_workflow("counter-1", "current", json!([]))
27458            .await
27459            .expect("query result");
27460        assert_eq!(result, json!({"count": 8}));
27461
27462        let error = client
27463            .query_workflow("counter-1", "missing", json!([]))
27464            .await
27465            .expect_err("unknown query");
27466        let Error::QueryFailed(failure) = error else {
27467            panic!("expected typed query failure");
27468        };
27469        assert_eq!(failure.status, 404);
27470        assert_eq!(failure.reason, "rejected_unknown_query");
27471    }
27472
27473    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
27474    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
27475    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
27476
27477    #[cfg(feature = "telemetry")]
27478    #[tokio::test]
27479    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
27480        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27481        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
27482        PHASE.store(0, Ordering::SeqCst);
27483        use opentelemetry::{
27484            propagation::TextMapPropagator,
27485            trace::{FutureExt, TracerProvider},
27486        };
27487        use opentelemetry_sdk::propagation::TraceContextPropagator;
27488        struct Restore;
27489        impl Drop for Restore {
27490            fn drop(&mut self) {
27491                opentelemetry::global::set_text_map_propagator(
27492                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27493                );
27494            }
27495        }
27496        let _restore = Restore;
27497        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
27498        let headers = HashMap::from([(
27499            "traceparent".to_string(),
27500            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
27501        )]);
27502        let parent = TraceContextPropagator::new().extract(&headers);
27503        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27504            request_override: Some(|path, body, _number| {
27505                if path == "/api/cluster/info" {
27506                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
27507                        ("503 Service Unavailable", "{}".into())
27508                    } else {
27509                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27510                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
27511                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27512                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27513                        }}}}).to_string())
27514                    });
27515                }
27516                let body: Value = serde_json::from_str(body).ok()?;
27517                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
27518                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
27519                    "result": "original"}).to_string()))
27520            }),
27521            ..MockWorkerBehavior::default()
27522        });
27523        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
27524        let client = Client::new(server.base_url()).unwrap().with_telemetry(
27525            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
27526        );
27527        let input = json!([{"observability_context": {"business": "preserved"}}]);
27528        async {
27529            client
27530                .start_workflow("orders", "orders", "order", &input)
27531                .await
27532                .unwrap();
27533            assert!(server
27534                .request_body("/api/workflows")
27535                .get("observability_context")
27536                .is_none());
27537            client.cluster_info().await.unwrap();
27538            client
27539                .start_workflow("orders", "orders", "order", &input)
27540                .await
27541                .unwrap();
27542            client
27543                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
27544                .await
27545                .unwrap();
27546            client
27547                .update_workflow("order", "status", &input, Some("update-original"))
27548                .await
27549                .unwrap();
27550            client
27551                .cancel_workflow("order", WorkflowCommandOptions::default())
27552                .await
27553                .unwrap();
27554            for path in [
27555                "/api/workflows",
27556                "/api/workflows/order/signal/ready",
27557                "/api/workflows/order/update/status",
27558                "/api/workflows/order/cancel",
27559            ] {
27560                let bodies = server.request_bodies(path);
27561                let body = bodies.last().unwrap();
27562                assert_eq!(
27563                    body["observability_context"]["carrier"]["traceparent"],
27564                    headers["traceparent"]
27565                );
27566                assert!(body["observability_context"]["carrier"]
27567                    .get("baggage")
27568                    .is_none());
27569            }
27570            let starts = server.request_bodies("/api/workflows");
27571            assert_eq!(
27572                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
27573                input
27574            );
27575            assert_eq!(
27576                server.request_body("/api/workflows/order/signal/ready")["request_id"],
27577                "signal-original"
27578            );
27579            assert_eq!(
27580                server.request_body("/api/workflows/order/update/status")["request_id"],
27581                "update-original"
27582            );
27583            PHASE.store(1, Ordering::SeqCst);
27584            client.cluster_info().await.unwrap();
27585            client
27586                .start_workflow("orders", "orders", "order", &input)
27587                .await
27588                .unwrap();
27589            assert!(server
27590                .request_bodies("/api/workflows")
27591                .last()
27592                .unwrap()
27593                .get("observability_context")
27594                .is_none());
27595            PHASE.store(2, Ordering::SeqCst);
27596            assert!(client.cluster_info().await.is_err());
27597            let before = server.captured_paths().len();
27598            client
27599                .start_workflow("orders", "orders", "order", &input)
27600                .await
27601                .unwrap();
27602            assert_eq!(server.captured_paths().len(), before + 1);
27603            assert!(server
27604                .request_bodies("/api/workflows")
27605                .last()
27606                .unwrap()
27607                .get("observability_context")
27608                .is_none());
27609        }
27610        .with_context(parent)
27611        .await;
27612    }
27613
27614    #[cfg(feature = "telemetry")]
27615    fn observability_worker_server(
27616        path: &str,
27617        _body: &str,
27618        _: usize,
27619    ) -> Option<(&'static str, String)> {
27620        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27621            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
27622                        "baggage": "credential=private"}});
27623        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27624            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
27625        if path == "/api/cluster/info" {
27626            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27627                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
27628                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27629                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27630            }}}}).to_string()));
27631        }
27632        if path.ends_with("/complete") {
27633            return Some(("200 OK", json!({"recorded": true}).to_string()));
27634        }
27635        let task_id = match path {
27636            "/api/worker/workflow-tasks/poll" => "workflow-task",
27637            "/api/worker/activity-tasks/poll" => "activity-task",
27638            "/api/worker/query-tasks/poll" => "query-task",
27639            _ => return None,
27640        };
27641        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
27642        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
27643        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
27644        "activity_type": "wire.activity", "activity_execution_id": "activity",
27645        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
27646        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
27647        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
27648        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
27649        "query_arguments": input, "history_events": [], "observability_context": context,
27650        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
27651            "task_id": task_id, "context": link_context},
27652        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
27653            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
27654                {"kind": "command", "command_id": "accepted-command", "context": link_context},
27655                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
27656                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
27657                 "event_type": "WorkflowCancelled", "context": link_context}
27658            ]}});
27659        if task_id == "workflow-task" {
27660            task["arguments"] = encode_value_envelope(
27661                &json!([{"observability_context": {"business": "preserved"}}]),
27662                DEFAULT_CODEC,
27663            )
27664            .unwrap();
27665        }
27666        Some((
27667            "200 OK",
27668            json!({"task": task, "poll_status": "leased"}).to_string(),
27669        ))
27670    }
27671
27672    #[cfg(feature = "telemetry")]
27673    #[tokio::test]
27674    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
27675    {
27676        use opentelemetry::trace::TracerProvider;
27677        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27678        opentelemetry::global::set_text_map_propagator(
27679            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
27680        );
27681        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27682        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27683            .with_simple_exporter(exporter.clone())
27684            .build();
27685        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
27686        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27687            request_override: Some(observability_worker_server),
27688            ..MockWorkerBehavior::default()
27689        });
27690        let client = Client::builder(server.base_url())
27691            .namespace("shipping")
27692            .build()
27693            .unwrap();
27694        client.cluster_info().await.unwrap();
27695        let mut worker = Worker::new(client, "shipping")
27696            .worker_id("test-worker")
27697            .telemetry(telemetry);
27698        worker.register_workflow("wire.workflow", |ctx, input| async move {
27699            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
27700            assert_eq!(
27701                input,
27702                json!([{"observability_context": {"business": "preserved"}}])
27703            );
27704            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
27705                .await?;
27706            Ok(Value::Null)
27707        });
27708        worker.register_activity("wire.activity", |_, _| async {
27709            let fields = telemetry::current_log_context();
27710            assert_eq!(fields["workflow_run_id"], "run");
27711            assert_eq!(fields["activity_id"], "activity");
27712            assert_eq!(fields["activity_attempt_id"], "attempt");
27713            assert_eq!(fields["activity_attempt_number"], "3");
27714            Ok(json!("original-result"))
27715        });
27716        worker.register_query("wire.workflow", "state", |_, _| async {
27717            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
27718            Ok(json!("original-query"))
27719        });
27720        assert_eq!(worker.run_once().await.unwrap(), 3);
27721        let spans = exporter.get_finished_spans().unwrap();
27722        assert_eq!(spans.len(), 4);
27723        let origin_trace = "12345678901234567890123456789012";
27724        for span in spans
27725            .iter()
27726            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
27727        {
27728            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
27729            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
27730            assert_eq!(span.links.len(), 3);
27731            assert!(!format!("{:?}", span.attributes).contains("credential"));
27732        }
27733        let task = spans
27734            .iter()
27735            .find(|span| span.name.as_ref() == "durable.workflow.task")
27736            .unwrap();
27737        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
27738        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
27739        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
27740            .as_str()
27741            .unwrap();
27742        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
27743        assert!(telemetry::current_log_context().is_empty());
27744        opentelemetry::global::set_text_map_propagator(
27745            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27746        );
27747    }
27748
27749    #[cfg(feature = "telemetry")]
27750    #[tokio::test]
27751    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
27752        use opentelemetry::trace::TracerProvider;
27753        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
27754        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
27755            let (status, reply) = observability_worker_server(path, body, count)?;
27756            if path != "/api/worker/query-tasks/poll" {
27757                return Some((status, reply));
27758            }
27759            let mut reply: Value = serde_json::from_str(&reply).unwrap();
27760            match REFUSAL.load(Ordering::SeqCst) {
27761                0 => reply["task"]["lease_owner"] = json!("other-worker"),
27762                1 => reply["task"]["query_task_attempt"] = json!(0),
27763                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
27764            }
27765            Some((status, reply.to_string()))
27766        }
27767        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27768        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27769            .with_simple_exporter(exporter.clone())
27770            .build();
27771        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27772            request_override: Some(refused_query),
27773            ..MockWorkerBehavior::default()
27774        });
27775        let client = Client::builder(server.base_url())
27776            .namespace("shipping")
27777            .build()
27778            .unwrap();
27779        client.cluster_info().await.unwrap();
27780        let mut worker = Worker::new(client, "shipping")
27781            .worker_id("test-worker")
27782            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
27783                provider.tracer("test"),
27784            ));
27785        let calls = Arc::new(AtomicUsize::new(0));
27786        let query_calls = calls.clone();
27787        worker.register_query("wire.workflow", "state", move |_, _| {
27788            query_calls.fetch_add(1, Ordering::SeqCst);
27789            async { Ok(Value::Null) }
27790        });
27791        for refusal in 0..3 {
27792            REFUSAL.store(refusal, Ordering::SeqCst);
27793            assert!(matches!(
27794                worker.poll_query_once().await.unwrap(),
27795                ManagedPollOutcome::Handled
27796            ));
27797            assert_eq!(calls.load(Ordering::SeqCst), 0);
27798            assert!(exporter.get_finished_spans().unwrap().is_empty());
27799            assert!(telemetry::current_log_context().is_empty());
27800        }
27801        assert!(!server
27802            .captured_paths()
27803            .iter()
27804            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
27805    }
27806
27807    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
27808        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
27809            return None;
27810        }
27811        serde_json::from_str(body).ok()
27812    }
27813
27814    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
27815    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27816        let request = keyed_command_request(path, body)?;
27817        let mut receipt = json!({
27818            "outcome": "accepted",
27819            "command_status": "accepted",
27820            "command_id": "cmd-keyed-1",
27821            "request_id": request["request_id"],
27822            "retained": false,
27823            "intent_verified": true,
27824        });
27825        if path == KEYED_UPDATE_PATH {
27826            receipt["update_id"] = json!("upd-keyed-1");
27827            receipt["result_envelope"] =
27828                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
27829        }
27830        Some(("202 Accepted", receipt.to_string()))
27831    }
27832
27833    /// A Server released before #216: accepts the body field but echoes nothing.
27834    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27835        keyed_command_request(path, body)?;
27836        Some((
27837            "202 Accepted",
27838            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
27839                .to_string(),
27840        ))
27841    }
27842
27843    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27844        let request = keyed_command_request(path, body)?;
27845        Some((
27846            "202 Accepted",
27847            json!({
27848                "outcome": "accepted",
27849                "command_status": "accepted",
27850                "command_id": "cmd-first",
27851                "request_id": request["request_id"],
27852                "retained": true,
27853                "intent_verified": true,
27854            })
27855            .to_string(),
27856        ))
27857    }
27858
27859    fn conflicting_command_server(
27860        path: &str,
27861        body: &str,
27862        _: usize,
27863    ) -> Option<(&'static str, String)> {
27864        let request = keyed_command_request(path, body)?;
27865        let retained_type = if path == KEYED_UPDATE_PATH {
27866            "update"
27867        } else {
27868            "signal"
27869        };
27870        Some((
27871            "409 Conflict",
27872            json!({
27873                "reason": "request_id_conflict",
27874                "message": format!("request id is retained for a different {retained_type} intent"),
27875                "request_id": request["request_id"],
27876                "retained_command_id": "cmd-retained-1",
27877                "retained_command_type": retained_type,
27878                "retained_outcome": "accepted",
27879                "conflict": ["arguments", "target"],
27880                "control_plane": {"operation": retained_type},
27881            })
27882            .to_string(),
27883        ))
27884    }
27885
27886    fn closed_run_command_server(
27887        path: &str,
27888        body: &str,
27889        _: usize,
27890    ) -> Option<(&'static str, String)> {
27891        let request = keyed_command_request(path, body)?;
27892        Some((
27893            "409 Conflict",
27894            json!({
27895                "reason": "run_not_active",
27896                "message": "run is closed",
27897                "request_id": request["request_id"],
27898            })
27899            .to_string(),
27900        ))
27901    }
27902
27903    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
27904        path == KEYED_SIGNAL_PATH && request_number == 1
27905    }
27906
27907    fn keyed_client(server: &MockWorkerServer) -> Client {
27908        Client::builder(server.base_url())
27909            .timeout(Duration::from_secs(2))
27910            .build()
27911            .expect("client")
27912    }
27913
27914    fn keyed_handle(client: &Client) -> WorkflowHandle {
27915        WorkflowHandle {
27916            client: client.clone(),
27917            workflow_id: "keyed-1".to_string(),
27918            run_id: Some("run-keyed-1".to_string()),
27919            workflow_type: "keyed".to_string(),
27920        }
27921    }
27922
27923    fn assert_generated_request_id(request_id: &str, prefix: &str) {
27924        let suffix = request_id
27925            .strip_prefix(prefix)
27926            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
27927        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
27928        assert!(
27929            suffix
27930                .bytes()
27931                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
27932            "lowercase hex suffix: {request_id:?}"
27933        );
27934        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
27935    }
27936
27937    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
27938        let headers = server.request_headers(path);
27939        assert!(!headers.is_empty(), "no request captured for {path}");
27940        for headers in headers {
27941            let header_names: Vec<String> = headers
27942                .lines()
27943                .skip(1)
27944                .filter_map(|line| line.split_once(':'))
27945                .map(|(name, _)| name.trim().to_ascii_lowercase())
27946                .collect();
27947            assert!(
27948                !header_names.iter().any(|name| name == "x-request-id"),
27949                "the caller command key is a body field, never an X-Request-Id header: {headers}"
27950            );
27951        }
27952    }
27953
27954    #[tokio::test]
27955    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
27956        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27957            request_override: Some(legacy_command_server),
27958            ..MockWorkerBehavior::default()
27959        });
27960        let client = keyed_client(&server);
27961
27962        let receipt = client
27963            .signal_workflow("keyed-1", "approve", json!(["ok"]))
27964            .await
27965            .expect("signal receipt");
27966
27967        let sent = server.request_body(KEYED_SIGNAL_PATH);
27968        let request_id = sent["request_id"].as_str().expect("generated request_id");
27969        assert_generated_request_id(request_id, "sdk-rust-signal-");
27970        assert_eq!(
27971            receipt,
27972            json!({
27973                "outcome": "accepted",
27974                "command_status": "accepted",
27975                "command_id": "cmd-legacy",
27976                "request_id": request_id,
27977            }),
27978            "the sent key is added when an older Server omits it"
27979        );
27980        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
27981
27982        let receipt = keyed_handle(&client)
27983            .signal_selected_run("approve", json!(["ok"]))
27984            .await
27985            .expect("selected-run signal receipt");
27986        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
27987        let run_request_id = run_sent["request_id"]
27988            .as_str()
27989            .expect("generated request_id");
27990        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
27991        assert_eq!(receipt["request_id"], run_request_id);
27992        assert_ne!(
27993            run_request_id, request_id,
27994            "each logical call gets its own key"
27995        );
27996        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
27997    }
27998
27999    #[tokio::test]
28000    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
28001        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28002            request_override: Some(keyed_command_server),
28003            ..MockWorkerBehavior::default()
28004        });
28005        let client = keyed_client(&server);
28006
28007        let result = client
28008            .update_workflow("keyed-1", "adjust", json!([1]), None)
28009            .await
28010            .expect("update result");
28011        assert_eq!(
28012            result,
28013            json!(42),
28014            "the decoded update result is returned unchanged"
28015        );
28016        let typed = client
28017            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
28018            .await
28019            .expect("typed update result");
28020        assert_eq!(typed, AvroValue::Long(42));
28021        keyed_handle(&client)
28022            .update("adjust", json!([1]), None)
28023            .await
28024            .expect("handle update result");
28025
28026        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
28027        assert_eq!(bodies.len(), 3);
28028        for body in &bodies {
28029            assert_generated_request_id(
28030                body["request_id"].as_str().expect("generated request_id"),
28031                "sdk-rust-update-",
28032            );
28033            assert_eq!(body["wait_for"], "completed");
28034        }
28035        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
28036        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
28037        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
28038    }
28039
28040    #[tokio::test]
28041    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
28042        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28043            request_override: Some(keyed_command_server),
28044            ..MockWorkerBehavior::default()
28045        });
28046        let client = keyed_client(&server);
28047        let handle = keyed_handle(&client);
28048
28049        let receipt = client
28050            .signal_workflow_with_request_id(
28051                "keyed-1",
28052                "approve",
28053                json!(["ok"]),
28054                "Order-42/approve",
28055            )
28056            .await
28057            .expect("signal receipt");
28058        assert_eq!(receipt["request_id"], "Order-42/approve");
28059        assert_eq!(receipt["retained"], false);
28060        assert_eq!(receipt["intent_verified"], true);
28061        handle
28062            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
28063            .await
28064            .expect("handle signal receipt");
28065        client
28066            .signal_workflow_run_with_request_id(
28067                "keyed-1",
28068                "run-keyed-1",
28069                "approve",
28070                json!(["ok"]),
28071                "run-signal-key",
28072            )
28073            .await
28074            .expect("selected-run signal receipt");
28075        handle
28076            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
28077            .await
28078            .expect("handle selected-run signal receipt");
28079        let result = client
28080            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
28081            .await
28082            .expect("update result");
28083        assert_eq!(result, json!(42));
28084        handle
28085            .update("adjust", json!([1]), Some("handle-update-key"))
28086            .await
28087            .expect("handle update result");
28088        handle
28089            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
28090            .await
28091            .expect("handle typed update result");
28092
28093        let signal_keys: Vec<Value> = server
28094            .request_bodies(KEYED_SIGNAL_PATH)
28095            .into_iter()
28096            .map(|body| body["request_id"].clone())
28097            .collect();
28098        assert_eq!(
28099            signal_keys,
28100            [json!("Order-42/approve"), json!("handle-signal-key")]
28101        );
28102        let run_signal_keys: Vec<Value> = server
28103            .request_bodies(KEYED_RUN_SIGNAL_PATH)
28104            .into_iter()
28105            .map(|body| body["request_id"].clone())
28106            .collect();
28107        assert_eq!(
28108            run_signal_keys,
28109            [json!("run-signal-key"), json!("handle-run-signal-key")]
28110        );
28111        let update_keys: Vec<Value> = server
28112            .request_bodies(KEYED_UPDATE_PATH)
28113            .into_iter()
28114            .map(|body| body["request_id"].clone())
28115            .collect();
28116        assert_eq!(
28117            update_keys,
28118            [
28119                json!("update-key"),
28120                json!("handle-update-key"),
28121                json!("handle-typed-update-key")
28122            ]
28123        );
28124        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
28125            assert_key_sent_only_in_body(&server, path);
28126        }
28127    }
28128
28129    #[tokio::test]
28130    async fn retained_receipts_are_returned_unchanged() {
28131        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28132            request_override: Some(retained_command_server),
28133            ..MockWorkerBehavior::default()
28134        });
28135        let client = keyed_client(&server);
28136
28137        let receipt = client
28138            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
28139            .await
28140            .expect("retained receipt");
28141
28142        assert_eq!(
28143            receipt,
28144            json!({
28145                "outcome": "accepted",
28146                "command_status": "accepted",
28147                "command_id": "cmd-first",
28148                "request_id": "retry-key",
28149                "retained": true,
28150                "intent_verified": true,
28151            })
28152        );
28153    }
28154
28155    #[tokio::test]
28156    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
28157        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28158            request_override: Some(conflicting_command_server),
28159            ..MockWorkerBehavior::default()
28160        });
28161        let client = keyed_client(&server);
28162
28163        let error = client
28164            .signal_workflow_with_request_id(
28165                "keyed-1",
28166                "approve",
28167                json!(["changed"]),
28168                "Order-42/approve",
28169            )
28170            .await
28171            .expect_err("different intent under a retained key");
28172        assert!(
28173            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
28174            "existing Error::Http matching keeps working: {error:?}"
28175        );
28176        assert!(error.is_request_id_conflict());
28177        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
28178        let conflict = error.request_id_conflict().expect("conflict details");
28179        assert_eq!(conflict.status, 409);
28180        assert_eq!(conflict.request_id, "Order-42/approve");
28181        assert_eq!(
28182            conflict.message,
28183            "request id is retained for a different signal intent"
28184        );
28185        assert_eq!(
28186            conflict.retained_command_id.as_deref(),
28187            Some("cmd-retained-1")
28188        );
28189        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
28190        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
28191        assert_eq!(conflict.conflict, ["arguments", "target"]);
28192        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
28193
28194        let error = client
28195            .update_workflow("keyed-1", "adjust", json!([2]), None)
28196            .await
28197            .expect_err("different intent under a retained generated key");
28198        let sent = server.request_body(KEYED_UPDATE_PATH);
28199        assert_eq!(
28200            error.request_id(),
28201            sent["request_id"].as_str().map(str::to_string)
28202        );
28203        assert_eq!(
28204            error
28205                .request_id_conflict()
28206                .expect("conflict details")
28207                .retained_command_type
28208                .as_deref(),
28209            Some("update")
28210        );
28211    }
28212
28213    #[tokio::test]
28214    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
28215        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28216            request_override: Some(closed_run_command_server),
28217            ..MockWorkerBehavior::default()
28218        });
28219        let client = keyed_client(&server);
28220
28221        let error = client
28222            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
28223            .await
28224            .expect_err("closed run");
28225
28226        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
28227        assert!(!error.is_request_id_conflict());
28228        assert_eq!(error.request_id_conflict(), None);
28229        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
28230    }
28231
28232    #[tokio::test]
28233    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
28234        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28235            request_override: Some(keyed_command_server),
28236            drop_request: Some(drop_first_keyed_signal),
28237            ..MockWorkerBehavior::default()
28238        });
28239        let client = keyed_client(&server);
28240        let request_id = Client::generate_signal_request_id();
28241
28242        let error = client
28243            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28244            .await
28245            .expect_err("connection closed before any response");
28246        assert!(
28247            matches!(error, Error::Transport(_)),
28248            "the transport variant is unchanged: {error:?}"
28249        );
28250        assert_eq!(
28251            error.request_id(),
28252            None,
28253            "nothing was echoed; the application holds the key it chose"
28254        );
28255
28256        let receipt = client
28257            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28258            .await
28259            .expect("manual retry with the same key");
28260        assert_eq!(receipt["request_id"], request_id);
28261        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
28262        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
28263        assert_eq!(
28264            bodies[0], bodies[1],
28265            "the retry resends the identical key and input"
28266        );
28267        assert_eq!(bodies[0]["request_id"], request_id);
28268    }
28269
28270    #[tokio::test]
28271    async fn invalid_command_keys_are_refused_before_sending() {
28272        let server = MockWorkerServer::start();
28273        let client = keyed_client(&server);
28274        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
28275
28276        for request_id in ["", too_long.as_str()] {
28277            let error = client
28278                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
28279                .await
28280                .expect_err("invalid signal key");
28281            assert!(
28282                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
28283                "{error:?}"
28284            );
28285            let error = client
28286                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
28287                .await
28288                .expect_err("invalid update key");
28289            assert!(matches!(error, Error::Codec(_)), "{error:?}");
28290        }
28291        assert!(server.captured_paths().is_empty(), "nothing was sent");
28292
28293        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
28294        let _ = client
28295            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
28296            .await;
28297        assert_eq!(
28298            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
28299            longest
28300        );
28301    }
28302
28303    #[test]
28304    fn generated_command_keys_are_distinct_and_well_formed() {
28305        let signal = Client::generate_signal_request_id();
28306        let update = Client::generate_update_request_id();
28307        assert_generated_request_id(&signal, "sdk-rust-signal-");
28308        assert_generated_request_id(&update, "sdk-rust-update-");
28309        assert_ne!(Client::generate_signal_request_id(), signal);
28310        assert!(validate_request_id(&signal).is_ok());
28311    }
28312
28313    #[test]
28314    fn command_keys_preserve_the_published_server_unicode_character_limit() {
28315        assert!(validate_request_id(&"é".repeat(255)).is_ok());
28316        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
28317        assert!(validate_request_id(&"é".repeat(256)).is_err());
28318    }
28319
28320    #[test]
28321    fn request_id_accessors_read_only_echoed_refusal_bodies() {
28322        let conflict = Error::Http {
28323            status: reqwest::StatusCode::CONFLICT,
28324            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(),
28325        };
28326        assert!(conflict.is_request_id_conflict());
28327        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
28328        let details = conflict.request_id_conflict().expect("conflict details");
28329        assert_eq!(details.conflict, ["name"]);
28330        assert_eq!(
28331            details.message,
28332            "request id is retained for a different command intent"
28333        );
28334
28335        let echoed = Error::Http {
28336            status: reqwest::StatusCode::CONFLICT,
28337            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
28338        };
28339        assert!(!echoed.is_request_id_conflict());
28340        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
28341
28342        let blank = Error::Http {
28343            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
28344            body: r#"{"request_id":""}"#.to_string(),
28345        };
28346        assert_eq!(blank.request_id(), None);
28347        let text = Error::Http {
28348            status: reqwest::StatusCode::BAD_GATEWAY,
28349            body: "upstream unavailable".to_string(),
28350        };
28351        assert_eq!(text.request_id(), None);
28352        assert!(!text.is_request_id_conflict());
28353
28354        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
28355            command: WorkflowCommandKind::Cancel,
28356            status: 409,
28357            reason: "request_id_conflict".to_string(),
28358            message: "retained".to_string(),
28359            workflow_id: "wf".to_string(),
28360            run_id: None,
28361            target_scope: None,
28362            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
28363        });
28364        assert!(rejection.is_request_id_conflict());
28365        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
28366
28367        assert_eq!(Error::Timeout.request_id(), None);
28368        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
28369    }
28370
28371    #[tokio::test]
28372    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
28373        let server = MockWorkerServer::start();
28374        let client = Client::builder(server.base_url())
28375            .timeout(Duration::from_secs(2))
28376            .build()
28377            .expect("client");
28378        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
28379
28380        client
28381            .start_workflow(
28382                "typed.echo",
28383                "rust-workers",
28384                "typed-start",
28385                arguments.clone(),
28386            )
28387            .await
28388            .expect("typed workflow start");
28389        assert_eq!(
28390            decode_wire_avro_value(
28391                &server.request_body("/api/workflows")["input"],
28392                DEFAULT_CODEC,
28393            )
28394            .expect("typed start input"),
28395            arguments
28396        );
28397
28398        client
28399            .signal_workflow("typed-1", "changed", arguments.clone())
28400            .await
28401            .expect("typed signal");
28402        assert_eq!(
28403            decode_wire_avro_value(
28404                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
28405                DEFAULT_CODEC,
28406            )
28407            .expect("typed signal input"),
28408            arguments
28409        );
28410
28411        assert_eq!(
28412            client
28413                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
28414                .await
28415                .expect("typed query"),
28416            typed_fidelity_probe()
28417        );
28418        assert_eq!(
28419            decode_wire_avro_value(
28420                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
28421                DEFAULT_CODEC,
28422            )
28423            .expect("typed query input"),
28424            arguments
28425        );
28426
28427        assert_eq!(
28428            client
28429                .update_workflow_avro_value(
28430                    "typed-1",
28431                    "replace",
28432                    arguments.clone(),
28433                    Some("typed-request"),
28434                )
28435                .await
28436                .expect("typed update"),
28437            typed_fidelity_probe()
28438        );
28439        let update = server.request_body("/api/workflows/typed-1/update/replace");
28440        assert_eq!(update["request_id"], "typed-request");
28441        assert_eq!(
28442            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
28443            arguments
28444        );
28445
28446        let handle = WorkflowHandle {
28447            client: client.clone(),
28448            workflow_id: "typed-1".to_string(),
28449            run_id: Some("run-typed-1".to_string()),
28450            workflow_type: "typed.echo".to_string(),
28451        };
28452        assert_eq!(
28453            handle
28454                .result_avro_value(WorkflowResultOptions::default())
28455                .await
28456                .expect("typed workflow result"),
28457            typed_fidelity_probe()
28458        );
28459
28460        client
28461            .complete_activity_task(
28462                "activity-typed",
28463                "attempt-typed",
28464                "rust-worker",
28465                typed_fidelity_probe(),
28466                DEFAULT_CODEC,
28467            )
28468            .await
28469            .expect("typed activity completion");
28470        assert_eq!(
28471            decode_wire_avro_value(
28472                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
28473                    ["result"],
28474                DEFAULT_CODEC,
28475            )
28476            .expect("typed activity result"),
28477            typed_fidelity_probe()
28478        );
28479        client
28480            .fail_activity_task(
28481                "activity-typed",
28482                "attempt-typed",
28483                "rust-worker",
28484                "typed failure",
28485                true,
28486            )
28487            .await
28488            .expect("activity failure");
28489    }
28490
28491    #[tokio::test]
28492    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
28493        let server = MockWorkerServer::start();
28494        let client = Client::builder(server.base_url())
28495            .timeout(Duration::from_secs(2))
28496            .build()
28497            .expect("client");
28498
28499        let options = WorkflowCommandOptions::new()
28500            .reason("cleanup requested")
28501            .request_id("cancel-17");
28502        let cancelled = client
28503            .cancel_workflow("wf-lifecycle", options)
28504            .await
28505            .expect("instance cancellation");
28506        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
28507        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
28508        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
28509        assert_eq!(
28510            server.request_body("/api/workflows/wf-lifecycle/cancel"),
28511            json!({"reason":"cleanup requested","request_id":"cancel-17"})
28512        );
28513
28514        let terminated = client
28515            .terminate_workflow(
28516                "wf-lifecycle",
28517                WorkflowCommandOptions::new().reason("forced stop"),
28518            )
28519            .await
28520            .expect("instance termination");
28521        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
28522        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
28523
28524        client
28525            .cancel_workflow_run(
28526                "wf-lifecycle",
28527                "run-current",
28528                WorkflowCommandOptions::default(),
28529            )
28530            .await
28531            .expect("selected run cancellation");
28532        client
28533            .terminate_workflow_run(
28534                "wf-lifecycle",
28535                "run-current",
28536                WorkflowCommandOptions::default(),
28537            )
28538            .await
28539            .expect("selected run termination");
28540
28541        for (command, error) in [
28542            (
28543                WorkflowCommandKind::Cancel,
28544                client
28545                    .cancel_workflow_run(
28546                        "wf-lifecycle",
28547                        "run-stale",
28548                        WorkflowCommandOptions::default(),
28549                    )
28550                    .await
28551                    .expect_err("stale cancellation must be rejected"),
28552            ),
28553            (
28554                WorkflowCommandKind::Terminate,
28555                client
28556                    .terminate_workflow_run(
28557                        "wf-lifecycle",
28558                        "run-stale",
28559                        WorkflowCommandOptions::default(),
28560                    )
28561                    .await
28562                    .expect_err("stale termination must be rejected"),
28563            ),
28564        ] {
28565            let Error::WorkflowCommandRejected(rejection) = error else {
28566                panic!("expected typed command rejection");
28567            };
28568            assert_eq!(rejection.command, command);
28569            assert_eq!(rejection.status, 409);
28570            assert_eq!(rejection.reason, "historical_run_command_rejected");
28571            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
28572            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
28573        }
28574    }
28575
28576    #[tokio::test]
28577    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
28578        let server = MockWorkerServer::start();
28579        let client = Client::builder(server.base_url())
28580            .timeout(Duration::from_secs(2))
28581            .build()
28582            .expect("client");
28583
28584        let result = client
28585            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
28586            .await
28587            .expect("redrive accepted");
28588        assert_eq!(result.workflow_id, "wf-lifecycle");
28589        assert_eq!(result.source_run_id, "run-failed");
28590        assert_eq!(result.run_id, "run-successor");
28591        assert_eq!(result.resume_step_sequence, 2);
28592        assert_eq!(
28593            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
28594            json!({"request_id":"retry-1"})
28595        );
28596
28597        let repeated = client
28598            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
28599            .await
28600            .expect("idempotent redrive response accepted");
28601        assert_eq!(repeated.run_id, "run-successor");
28602
28603        let error = client
28604            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
28605            .await
28606            .expect_err("completed run must be rejected");
28607        let Error::Http { status, body } = error else {
28608            panic!("expected HTTP redrive rejection");
28609        };
28610        assert_eq!(status.as_u16(), 409);
28611        assert!(body.contains("run_not_failed"));
28612        assert_eq!(
28613            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
28614            json!({})
28615        );
28616
28617        let handle = WorkflowHandle {
28618            client: client.clone(),
28619            workflow_id: "wf-lifecycle".to_string(),
28620            run_id: Some("run-failed".to_string()),
28621            workflow_type: "test".to_string(),
28622        };
28623        assert_eq!(
28624            handle.redrive(None).await.expect("handle redrive").run_id,
28625            "run-successor"
28626        );
28627        let missing_run = WorkflowHandle {
28628            run_id: None,
28629            ..handle
28630        };
28631        assert!(matches!(
28632            missing_run.redrive(None).await,
28633            Err(Error::Codec(_))
28634        ));
28635    }
28636
28637    #[tokio::test]
28638    async fn workflow_start_options_send_server_enforced_deadlines() {
28639        let server = MockWorkerServer::start();
28640        let client = Client::builder(server.base_url())
28641            .timeout(Duration::from_secs(2))
28642            .build()
28643            .expect("client");
28644
28645        let handle = client
28646            .start_workflow_with_options(
28647                "rust.timeout",
28648                "rust-timeouts",
28649                "wf-start-options",
28650                WorkflowStartOptions::new()
28651                    .execution_timeout_seconds(30)
28652                    .run_timeout_seconds(1),
28653                json!([]),
28654            )
28655            .await
28656            .expect("workflow start");
28657
28658        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
28659        let body = server.request_body("/api/workflows");
28660        assert_eq!(body["execution_timeout_seconds"], 30);
28661        assert_eq!(body["run_timeout_seconds"], 1);
28662
28663        let invalid = client
28664            .start_workflow_with_options(
28665                "rust.timeout",
28666                "rust-timeouts",
28667                "wf-invalid-options",
28668                WorkflowStartOptions::new()
28669                    .execution_timeout_seconds(1)
28670                    .run_timeout_seconds(2),
28671                json!([]),
28672            )
28673            .await
28674            .expect_err("invalid deadline ordering");
28675        assert!(invalid
28676            .to_string()
28677            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
28678    }
28679
28680    #[tokio::test]
28681    async fn workflow_result_returns_each_typed_terminal_outcome() {
28682        let server = MockWorkerServer::start();
28683        let client = Client::builder(server.base_url())
28684            .timeout(Duration::from_secs(2))
28685            .build()
28686            .expect("client");
28687        let options = WorkflowResultOptions {
28688            poll_interval: Duration::ZERO,
28689            timeout: Duration::from_secs(1),
28690        };
28691
28692        let failed = WorkflowHandle {
28693            client: client.clone(),
28694            workflow_id: "wf-failed".to_string(),
28695            run_id: Some("run-failed".to_string()),
28696            workflow_type: "failure".to_string(),
28697        }
28698        .result(options)
28699        .await
28700        .expect_err("failed outcome");
28701        let Error::WorkflowFailed(failure) = failed else {
28702            panic!("expected WorkflowFailed");
28703        };
28704        assert_eq!(failure.workflow_id, "wf-failed");
28705        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
28706        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
28707        assert_eq!(failure.failure_category.as_deref(), Some("application"));
28708        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
28709        assert_eq!(
28710            failure.exception_class.as_deref(),
28711            Some("billing::PaymentError")
28712        );
28713        assert_eq!(failure.non_retryable, Some(true));
28714
28715        for (workflow_id, expected_kind, expected_reason) in [
28716            (
28717                "wf-cancelled",
28718                WorkflowTerminalKind::Cancelled,
28719                "cleanup requested",
28720            ),
28721            (
28722                "wf-terminated",
28723                WorkflowTerminalKind::Terminated,
28724                "forced stop",
28725            ),
28726            (
28727                "wf-timed-out",
28728                WorkflowTerminalKind::TimedOut,
28729                "run_timeout",
28730            ),
28731        ] {
28732            let error = WorkflowHandle {
28733                client: client.clone(),
28734                workflow_id: workflow_id.to_string(),
28735                run_id: None,
28736                workflow_type: "terminal".to_string(),
28737            }
28738            .result(options)
28739            .await
28740            .expect_err("typed terminal outcome");
28741            let outcome = match error {
28742                Error::WorkflowCancelled(outcome) => outcome,
28743                Error::WorkflowTerminated(outcome) => outcome,
28744                Error::WorkflowTimedOut(outcome) => outcome,
28745                other => panic!("unexpected terminal error: {other}"),
28746            };
28747            assert_eq!(outcome.kind, expected_kind);
28748            assert_eq!(outcome.workflow_id, workflow_id);
28749            assert_eq!(outcome.reason, expected_reason);
28750        }
28751
28752        let wait_timeout = WorkflowHandle {
28753            client,
28754            workflow_id: "wf-waiting".to_string(),
28755            run_id: Some("run-waiting".to_string()),
28756            workflow_type: "waiting".to_string(),
28757        }
28758        .result(WorkflowResultOptions {
28759            poll_interval: Duration::ZERO,
28760            timeout: Duration::ZERO,
28761        })
28762        .await
28763        .expect_err("client wait timeout");
28764        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
28765            panic!("expected typed client timeout");
28766        };
28767        assert_eq!(timeout.reason, "result_wait_timeout");
28768        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
28769        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
28770    }
28771
28772    #[tokio::test]
28773    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
28774        let server = MockWorkerServer::start();
28775        let client = Client::builder(server.base_url())
28776            .timeout(Duration::from_secs(2))
28777            .build()
28778            .expect("client");
28779
28780        let handle = WorkflowHandle {
28781            client,
28782            workflow_id: "wf-selected".to_string(),
28783            run_id: Some("run-selected".to_string()),
28784            workflow_type: "selected".to_string(),
28785        };
28786        let options = WorkflowResultOptions {
28787            poll_interval: Duration::ZERO,
28788            timeout: Duration::from_secs(1),
28789        };
28790
28791        let current = handle
28792            .result(options)
28793            .await
28794            .expect("instance result follows the current run");
28795        assert_eq!(current, json!("current run output"));
28796
28797        let error = handle
28798            .result_selected_run(options)
28799            .await
28800            .expect_err("the selected run is cancelled even though the current run completed");
28801
28802        let Error::WorkflowCancelled(outcome) = error else {
28803            panic!("expected selected run cancellation");
28804        };
28805        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
28806        assert_eq!(outcome.reason, "selected run cancelled");
28807        assert_eq!(
28808            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
28809            1
28810        );
28811        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
28812    }
28813
28814    #[tokio::test]
28815    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
28816        let server = MockWorkerServer::draining_polls();
28817        let client = Client::builder(server.base_url())
28818            .timeout(Duration::from_secs(2))
28819            .build()
28820            .expect("client");
28821
28822        let workflow = client
28823            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
28824            .await
28825            .expect("workflow drain response");
28826        let activity = client
28827            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
28828            .await
28829            .expect("activity drain response");
28830        let query = client
28831            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
28832            .await
28833            .expect("query drain response");
28834
28835        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
28836            assert_eq!(
28837                outcome,
28838                WorkerPollOutcome::Stop {
28839                    poll_status: Some("draining".to_string()),
28840                    reason: Some("worker_draining".to_string()),
28841                }
28842            );
28843        }
28844
28845        assert!(client
28846            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
28847            .await
28848            .expect("compatibility poll")
28849            .is_none());
28850    }
28851
28852    #[tokio::test]
28853    async fn managed_worker_honors_drain_stop_for_every_task_family() {
28854        let server = MockWorkerServer::draining_polls();
28855        let client = Client::builder(server.base_url())
28856            .timeout(Duration::from_secs(2))
28857            .build()
28858            .expect("client");
28859
28860        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
28861            .worker_id("draining-workflow-worker")
28862            .poll_timeout(Duration::ZERO);
28863        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
28864        workflow_worker
28865            .run()
28866            .await
28867            .expect("workflow drain is a clean stop");
28868
28869        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
28870            .worker_id("draining-activity-worker")
28871            .poll_timeout(Duration::ZERO);
28872        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
28873        activity_worker
28874            .run()
28875            .await
28876            .expect("activity drain is a clean stop");
28877
28878        let mut query_worker = Worker::new(client, "rust-workers")
28879            .worker_id("draining-query-worker")
28880            .poll_timeout(Duration::ZERO);
28881        query_worker.register_query("counter", "current", |_ctx, _args| async {
28882            Ok(Value::Null)
28883        });
28884        query_worker
28885            .run()
28886            .await
28887            .expect("query drain is a clean stop");
28888    }
28889
28890    #[tokio::test]
28891    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
28892        let server = MockWorkerServer::start();
28893        let client = Client::builder(server.base_url())
28894            .timeout(Duration::from_secs(2))
28895            .build()
28896            .expect("client");
28897
28898        let details: Value = serde_json::from_str(include_str!(
28899            "../tests/fixtures/activity-heartbeat-progress.json"
28900        ))
28901        .expect("heartbeat progress fixture");
28902        // Every individual field fits Server's progress contract, while the
28903        // obsolete encoded envelope exceeded its 191-character string limit.
28904        assert!(
28905            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
28906                .unwrap()["blob"]
28907                .as_str()
28908                .unwrap()
28909                .len()
28910                > 191
28911        );
28912        let heartbeat = client
28913            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
28914            .await
28915            .expect("cancellation heartbeat");
28916        assert!(heartbeat.cancel_requested);
28917        assert!(heartbeat.should_stop());
28918        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
28919        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
28920        let heartbeat_body =
28921            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
28922        assert_eq!(heartbeat_body["details"], details);
28923        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
28924        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
28925
28926        let error = client
28927            .complete_activity_task(
28928                "activity-cancel",
28929                "attempt-cancel",
28930                "rust-worker",
28931                json!({"late":true}),
28932                DEFAULT_CODEC,
28933            )
28934            .await
28935            .expect_err("late completion must be refused");
28936        assert!(activity_task_rejection_is_final(&error));
28937        let Error::ActivityTaskRejected(rejection) = error else {
28938            panic!("expected typed activity rejection");
28939        };
28940        assert_eq!(rejection.status, 409);
28941        assert_eq!(rejection.reason, "run_cancelled");
28942        assert!(rejection.cancel_requested);
28943        assert_eq!(rejection.can_continue, Some(false));
28944    }
28945
28946    #[tokio::test]
28947    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
28948        let server = MockWorkerServer::cancelled_activity();
28949        let client = Client::builder(server.base_url())
28950            .timeout(Duration::from_secs(2))
28951            .build()
28952            .expect("client");
28953        let cancellation_observed = Arc::new(AtomicBool::new(false));
28954        let observed = Arc::clone(&cancellation_observed);
28955        let mut worker = Worker::new(client.clone(), "rust-workers")
28956            .worker_id("rust-cancel-worker")
28957            .poll_timeout(Duration::from_millis(10));
28958        worker.register_activity("cancel-aware", move |ctx, _args| {
28959            let observed = Arc::clone(&observed);
28960            async move {
28961                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
28962                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
28963                Ok(json!({"late":"completion"}))
28964            }
28965        });
28966
28967        assert_eq!(
28968            worker.run_once().await.expect("cancelled attempt handled"),
28969            1
28970        );
28971        assert!(cancellation_observed.load(Ordering::SeqCst));
28972        assert_eq!(
28973            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
28974            1
28975        );
28976
28977        let mut restarted = Worker::new(client, "rust-workers")
28978            .worker_id("rust-cancel-worker-restarted")
28979            .poll_timeout(Duration::from_millis(10));
28980        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
28981        assert_eq!(
28982            restarted
28983                .run_once()
28984                .await
28985                .expect("replacement worker continues polling"),
28986            0
28987        );
28988    }
28989
28990    #[tokio::test]
28991    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
28992        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"}"#;
28993        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
28994        let client = Client::builder(server.base_url())
28995            .timeout(Duration::from_secs(2))
28996            .build()
28997            .expect("client");
28998
28999        let direct_error = client
29000            .complete_workflow_task(
29001                "workflow-timeout-task",
29002                "timeout-worker",
29003                3,
29004                vec![json!({
29005                    "type": "complete_workflow",
29006                    "result": fixture_envelope(Value::Null)
29007                })],
29008            )
29009            .await
29010            .expect_err("the low-level client preserves the completion rejection");
29011        let Error::Http { status, body } = direct_error else {
29012            panic!("expected the original HTTP completion rejection");
29013        };
29014        assert_eq!(status, reqwest::StatusCode::CONFLICT);
29015        assert_eq!(
29016            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
29017            "run_timed_out"
29018        );
29019
29020        let mut worker = Worker::new(client, "rust-workers")
29021            .worker_id("timeout-worker")
29022            .poll_timeout(Duration::from_millis(10));
29023        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29024            Ok(json!({"late": "result"}))
29025        });
29026
29027        assert_eq!(
29028            worker
29029                .run_once()
29030                .await
29031                .expect("authoritative selected-run timeout settles the tick"),
29032            1
29033        );
29034        assert_eq!(
29035            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
29036            2,
29037            "both the direct client proof and managed worker must see the rejection"
29038        );
29039    }
29040
29041    #[tokio::test]
29042    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
29043        for (name, status, response) in [
29044            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
29045            (
29046                "command was recorded",
29047                "409 Conflict",
29048                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29049            ),
29050            (
29051                "lease conflict",
29052                "409 Conflict",
29053                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
29054            ),
29055            (
29056                "nonterminal run",
29057                "409 Conflict",
29058                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
29059            ),
29060            (
29061                "different selected run",
29062                "409 Conflict",
29063                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"}"#,
29064            ),
29065            (
29066                "different task attempt",
29067                "409 Conflict",
29068                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29069            ),
29070            (
29071                "authentication failure",
29072                "401 Unauthorized",
29073                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29074            ),
29075            (
29076                "authorization failure",
29077                "403 Forbidden",
29078                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29079            ),
29080            (
29081                "protocol failure",
29082                "400 Bad Request",
29083                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
29084            ),
29085            (
29086                "malformed command",
29087                "422 Unprocessable Entity",
29088                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29089            ),
29090            (
29091                "transient server failure",
29092                "503 Service Unavailable",
29093                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29094            ),
29095        ] {
29096            let server = MockWorkerServer::workflow_completion(status, response);
29097            let client = Client::builder(server.base_url())
29098                .timeout(Duration::from_secs(2))
29099                .build()
29100                .expect("client");
29101            let mut worker = Worker::new(client, "rust-workers")
29102                .worker_id("timeout-worker")
29103                .poll_timeout(Duration::from_millis(10));
29104            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29105                Ok(json!({"late": "result"}))
29106            });
29107
29108            let error = worker
29109                .run_once()
29110                .await
29111                .expect_err(&format!("{name} must remain an error"));
29112            assert!(
29113                matches!(error, Error::Http { .. } | Error::Protocol(_)),
29114                "{name} returned an unexpected error variant: {error}"
29115            );
29116        }
29117    }
29118
29119    #[tokio::test]
29120    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
29121        let server = MockWorkerServer::start();
29122        let client = Client::builder(server.base_url())
29123            .worker_token(Some("worker-secret".to_string()))
29124            .namespace("orders")
29125            .timeout(Duration::from_secs(2))
29126            .build()
29127            .expect("client");
29128        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
29129
29130        let result = client
29131            .deregister_worker_registration("worker/α space")
29132            .await
29133            .expect("deregister worker registration");
29134
29135        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
29136        assert_eq!(
29137            server.worker_protocol_for(path).as_deref(),
29138            Some(WORKER_PROTOCOL_VERSION)
29139        );
29140        assert_eq!(server.control_protocol_for(path), None);
29141        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
29142        assert_eq!(
29143            server.authorization_for(path).as_deref(),
29144            Some("Bearer worker-secret")
29145        );
29146        assert_eq!(
29147            result,
29148            WorkerDeregistrationEnvelope {
29149                worker_id: "deregistered-worker".to_string(),
29150                outcome: "deregistered".to_string(),
29151                recovered_workflow_task_count: 2,
29152            }
29153        );
29154    }
29155
29156    #[tokio::test]
29157    async fn low_level_registration_rejects_update_validators_before_transport() {
29158        let server = MockWorkerServer::start();
29159        let client = Client::builder(server.base_url())
29160            .timeout(Duration::from_secs(2))
29161            .build()
29162            .expect("client");
29163
29164        for update_validators in [json!(["approve"]), json!("approve")] {
29165            let error = client
29166                .register_worker_with_command_contracts(
29167                    "validator-claiming-worker",
29168                    "rust-workers",
29169                    vec!["orders".to_string()],
29170                    vec![],
29171                    1,
29172                    1,
29173                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29174                    json!({
29175                        "orders": {
29176                            "queries": ["current"],
29177                            "updates": ["approve"],
29178                            "update_validators": update_validators,
29179                        },
29180                    }),
29181                )
29182                .await
29183                .expect_err("unsupported validator claims must fail before registration");
29184
29185            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
29186                panic!("expected typed unsupported-validator failure");
29187            };
29188            assert_eq!(workflow_type, "orders");
29189        }
29190        assert_eq!(server.request_count("/api/worker/register"), 0);
29191    }
29192
29193    #[tokio::test]
29194    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
29195        let server = MockWorkerServer::start();
29196        let client = Client::builder(server.base_url())
29197            .timeout(Duration::from_secs(2))
29198            .build()
29199            .expect("client");
29200        let mut worker = Worker::new(client, "rust-workers");
29201        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
29202        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
29203        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29204        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
29205        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29206        worker
29207            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
29208            .expect("declare workflow signals");
29209
29210        worker.register().await.expect("register handler contracts");
29211
29212        let declaration =
29213            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
29214        let expected_contracts = json!([
29215            {
29216                "name": "a-avro",
29217                "parameters": [{
29218                    "name": "args", "position": 0, "required": false,
29219                    "variadic": true, "type": null, "allows_null": true,
29220                    "default_available": false, "default": null,
29221                }],
29222            },
29223            {
29224                "name": "z-json",
29225                "parameters": [{
29226                    "name": "args", "position": 0, "required": false,
29227                    "variadic": true, "type": null, "allows_null": true,
29228                    "default_available": false, "default": null,
29229                }],
29230            },
29231        ]);
29232        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
29233        assert_eq!(declaration["query_contracts"], expected_contracts);
29234        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
29235        assert_eq!(declaration["update_contracts"], expected_contracts);
29236        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
29237        assert_eq!(declaration["signal_contracts"], expected_contracts);
29238        assert_eq!(declaration["update_validators"], json!([]));
29239    }
29240
29241    #[tokio::test]
29242    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
29243        let server = MockWorkerServer::start();
29244        let client = Client::new(server.base_url()).expect("client");
29245        let mut worker = Worker::new(client, "rust-workers");
29246        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
29247        assert!(worker
29248            .declare_workflow_signals("missing", &["finish"])
29249            .is_err());
29250        worker
29251            .declare_workflow_signals("orders", &["finish"])
29252            .unwrap();
29253        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
29254            assert!(worker.declare_workflow_signals("orders", names).is_err());
29255        }
29256        worker.register().await.unwrap();
29257        assert_eq!(
29258            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
29259                ["signals"],
29260            json!(["finish"])
29261        );
29262        worker.declare_workflow_signals("orders", &[]).unwrap();
29263        worker.register().await.unwrap();
29264        let registrations = server.request_bodies("/api/worker/register");
29265        assert_eq!(
29266            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
29267            json!([])
29268        );
29269        assert_eq!(
29270            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
29271            json!([])
29272        );
29273    }
29274
29275    #[tokio::test]
29276    async fn low_level_registration_preserves_query_and_update_contracts() {
29277        let server = MockWorkerServer::start();
29278        let client = Client::builder(server.base_url())
29279            .timeout(Duration::from_secs(2))
29280            .build()
29281            .expect("client");
29282        let contracts = json!({
29283            "orders": {
29284                "queries": ["current"],
29285                "updates": ["approve"],
29286                "update_validators": [],
29287            },
29288            "payments": {
29289                "queries": ["status"],
29290                "updates": ["capture"],
29291            },
29292        });
29293
29294        client
29295            .register_worker_with_command_contracts(
29296                "command-worker",
29297                "rust-workers",
29298                vec!["orders".to_string(), "payments".to_string()],
29299                vec![],
29300                1,
29301                1,
29302                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29303                contracts.clone(),
29304            )
29305            .await
29306            .expect("query and update contracts must remain supported");
29307
29308        assert_eq!(
29309            server.request_body("/api/worker/register")["workflow_command_contracts"],
29310            contracts
29311        );
29312        assert!(server
29313            .request_body("/api/worker/register")
29314            .get("workflow_definition_fingerprints")
29315            .is_none());
29316    }
29317
29318    #[tokio::test]
29319    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
29320        let server = MockWorkerServer::start();
29321        let client = Client::builder(server.base_url())
29322            .timeout(Duration::from_secs(2))
29323            .build()
29324            .expect("client");
29325        let mut worker = Worker::new(client.clone(), "rust-workers");
29326        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29327
29328        assert!(worker
29329            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
29330            .is_err());
29331        assert!(worker
29332            .set_workflow_definition_sources("orders", &[])
29333            .is_err());
29334        worker
29335            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
29336            .expect("embed workflow source");
29337        worker.register().await.expect("register worker");
29338        let first = server.request_bodies("/api/worker/register")[0]
29339            ["workflow_definition_fingerprints"]["orders"]
29340            .as_str()
29341            .expect("source-backed fingerprint")
29342            .to_string();
29343        assert!(first.starts_with("sha256:"));
29344
29345        worker
29346            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
29347            .expect("change embedded helper source");
29348        worker.register().await.expect("register changed source");
29349        let changed = server.request_bodies("/api/worker/register")[1]
29350            ["workflow_definition_fingerprints"]["orders"]
29351            .as_str()
29352            .expect("changed fingerprint")
29353            .to_string();
29354        assert_ne!(first, changed);
29355
29356        let mut replacement =
29357            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
29358        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29359        replacement
29360            .register()
29361            .await
29362            .expect("register replacement handler");
29363        assert_eq!(
29364            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
29365            json!({})
29366        );
29367    }
29368
29369    #[tokio::test]
29370    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
29371        let server = MockWorkerServer::start();
29372        let control_only = Client::builder(server.base_url())
29373            .control_token(Some("control-secret".to_string()))
29374            .build()
29375            .expect("control client");
29376
29377        let error = control_only
29378            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29379            .await
29380            .expect_err("control token must not authorize a worker request");
29381        assert!(matches!(
29382            error,
29383            Error::MissingRoleCredentials { role: "worker", .. }
29384        ));
29385        assert_eq!(server.request_count("/api/worker/register"), 0);
29386
29387        let worker_only = Client::builder(server.base_url())
29388            .worker_token(Some("worker-secret".to_string()))
29389            .build()
29390            .expect("worker client");
29391        let error = worker_only
29392            .health()
29393            .await
29394            .expect_err("worker token must not authorize a control request");
29395        assert!(matches!(
29396            error,
29397            Error::MissingRoleCredentials {
29398                role: "control",
29399                ..
29400            }
29401        ));
29402        assert_eq!(server.request_count("/api/health"), 0);
29403    }
29404
29405    #[tokio::test]
29406    async fn shared_token_supports_worker_and_control_planes() {
29407        let server = MockWorkerServer::start();
29408        let client = Client::builder(server.base_url())
29409            .token(Some("shared-secret".to_string()))
29410            .build()
29411            .expect("client");
29412
29413        client.health().await.expect("control request");
29414        client
29415            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29416            .await
29417            .expect("worker request");
29418
29419        assert_eq!(
29420            server.authorization_for("/api/health").as_deref(),
29421            Some("Bearer shared-secret")
29422        );
29423        assert_eq!(
29424            server.control_protocol_for("/api/health").as_deref(),
29425            Some(CONTROL_PLANE_VERSION)
29426        );
29427        assert_eq!(
29428            server.authorization_for("/api/worker/register").as_deref(),
29429            Some("Bearer shared-secret")
29430        );
29431        assert_eq!(
29432            server
29433                .worker_protocol_for("/api/worker/register")
29434                .as_deref(),
29435            Some(WORKER_PROTOCOL_VERSION)
29436        );
29437    }
29438
29439    #[tokio::test]
29440    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
29441        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
29442        let server = MockWorkerServer::start();
29443        let client = Client::builder(server.base_url())
29444            .timeout(Duration::from_secs(2))
29445            .build()
29446            .expect("client");
29447
29448        client
29449            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
29450            .await
29451            .expect("register");
29452        client
29453            .heartbeat_worker("capture-worker", 1, 1)
29454            .await
29455            .expect("heartbeat");
29456        client
29457            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29458            .await
29459            .expect("workflow poll");
29460        client
29461            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29462            .await
29463            .expect("activity poll");
29464
29465        for path in [
29466            "/api/worker/register",
29467            "/api/worker/heartbeat",
29468            "/api/worker/workflow-tasks/poll",
29469            "/api/worker/activity-tasks/poll",
29470        ] {
29471            assert_eq!(
29472                server.worker_protocol_for(path).as_deref(),
29473                Some(WORKER_PROTOCOL_VERSION),
29474                "unexpected protocol for {path}"
29475            );
29476        }
29477
29478        assert_eq!(
29479            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
29480            1
29481        );
29482        assert_eq!(
29483            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
29484            500
29485        );
29486        assert_eq!(
29487            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
29488            1
29489        );
29490        assert!(
29491            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
29492                .as_str()
29493                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
29494        );
29495        assert!(
29496            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
29497                .as_str()
29498                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
29499        );
29500        let registration = server.request_body("/api/worker/register");
29501        for optional in [
29502            "cooperative_cancellation",
29503            "local_activities",
29504            "worker_sessions",
29505            "sticky_execution",
29506        ] {
29507            assert!(!registration["capabilities"]
29508                .as_array()
29509                .is_some_and(|capabilities| capabilities
29510                    .iter()
29511                    .any(|capability| capability.as_str() == Some(optional))));
29512        }
29513    }
29514
29515    #[tokio::test]
29516    async fn explicit_previous_worker_protocol_preserves_headers() {
29517        let server = MockWorkerServer::start();
29518        let client = Client::builder(server.base_url())
29519            .worker_protocol_version(WorkerProtocolVersion::V119)
29520            .timeout(Duration::from_secs(2))
29521            .build()
29522            .expect("client");
29523        client
29524            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
29525            .await
29526            .expect("register");
29527        client
29528            .heartbeat_worker("legacy-worker", 1, 1)
29529            .await
29530            .expect("heartbeat");
29531        client
29532            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
29533            .await
29534            .expect("workflow poll");
29535        client
29536            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
29537            .await
29538            .expect("activity poll");
29539        client
29540            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
29541            .await
29542            .expect("query poll");
29543        client
29544            .deregister_worker_registration("legacy-worker")
29545            .await
29546            .expect("deregister");
29547        for path in [
29548            "/api/worker/register",
29549            "/api/worker/heartbeat",
29550            "/api/worker/workflow-tasks/poll",
29551            "/api/worker/activity-tasks/poll",
29552            "/api/worker/query-tasks/poll",
29553            "/api/worker/registrations/legacy-worker",
29554        ] {
29555            assert_eq!(
29556                server.worker_protocol_for(path).as_deref(),
29557                Some("1.19"),
29558                "{path}"
29559            );
29560            assert_eq!(server.control_protocol_for(path), None, "{path}");
29561        }
29562    }
29563
29564    #[tokio::test]
29565    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
29566        let server = MockWorkerServer::start();
29567        let client = Client::builder(server.base_url())
29568            .worker_protocol_version(WorkerProtocolVersion::V119)
29569            .timeout(Duration::from_secs(2))
29570            .build()
29571            .expect("client");
29572        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
29573        let error = worker
29574            .register()
29575            .await
29576            .expect_err("legacy cooperation must be refused");
29577        assert!(matches!(
29578            error,
29579            Error::CooperativeCancellationUnavailable(_)
29580        ));
29581        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
29582    }
29583
29584    #[tokio::test]
29585    async fn query_task_endpoints_send_the_selected_worker_protocol() {
29586        let server = MockWorkerServer::start();
29587        let client = Client::builder(server.base_url())
29588            .timeout(Duration::from_secs(2))
29589            .build()
29590            .expect("client");
29591
29592        client
29593            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29594            .await
29595            .expect("query poll");
29596        client
29597            .complete_query_task(
29598                "query-capture",
29599                "capture-worker",
29600                1,
29601                json!(8),
29602                DEFAULT_CODEC,
29603            )
29604            .await
29605            .expect("query complete");
29606        client
29607            .fail_query_task(
29608                "query-capture",
29609                "capture-worker",
29610                1,
29611                "failed",
29612                "query_rejected",
29613                "QueryFailed",
29614            )
29615            .await
29616            .expect("query fail");
29617
29618        for path in [
29619            "/api/worker/query-tasks/poll",
29620            "/api/worker/query-tasks/query-capture/complete",
29621            "/api/worker/query-tasks/query-capture/fail",
29622        ] {
29623            assert_eq!(
29624                server.worker_protocol_for(path).as_deref(),
29625                Some(WORKER_PROTOCOL_VERSION),
29626                "unexpected protocol for {path}"
29627            );
29628        }
29629
29630        assert_eq!(
29631            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
29632            1
29633        );
29634        assert!(
29635            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
29636                .as_str()
29637                .is_some_and(|id| id.starts_with("rust-query-poll-"))
29638        );
29639    }
29640
29641    #[tokio::test]
29642    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
29643        let server = MockWorkerServer::transient_worker_failures();
29644        let client = Client::builder(server.base_url())
29645            .timeout(Duration::from_secs(2))
29646            .build()
29647            .expect("client");
29648
29649        client
29650            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29651            .await
29652            .expect("workflow poll retry");
29653        client
29654            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29655            .await
29656            .expect("activity poll retry");
29657        client
29658            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29659            .await
29660            .expect("query poll retry");
29661
29662        for path in [
29663            "/api/worker/workflow-tasks/poll",
29664            "/api/worker/activity-tasks/poll",
29665            "/api/worker/query-tasks/poll",
29666        ] {
29667            let bodies = server.request_bodies(path);
29668            assert_eq!(bodies.len(), 2, "{path} must be retried once");
29669            assert_eq!(
29670                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
29671                "{path} must preserve the request binding across retry"
29672            );
29673        }
29674    }
29675
29676    #[tokio::test]
29677    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
29678        let server = MockWorkerServer::consecutive_poll_failures(2);
29679        let client = Client::builder(server.base_url())
29680            .timeout(Duration::from_secs(2))
29681            .build()
29682            .expect("client");
29683        let mut worker = Worker::new(client, "capture")
29684            .worker_id("capture-worker")
29685            .poll_timeout(Duration::from_millis(10))
29686            .retry_policy(WorkerRetryPolicy {
29687                max_retries: 2,
29688                initial_backoff: Duration::from_millis(1),
29689                max_backoff: Duration::from_millis(1),
29690            });
29691        worker.register_workflow(
29692            "capture.workflow",
29693            |_ctx, _input| async move { Ok(Value::Null) },
29694        );
29695        worker.register_activity(
29696            "capture.activity",
29697            |_ctx, _input| async move { Ok(Value::Null) },
29698        );
29699        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
29700            Ok(Value::Null)
29701        });
29702
29703        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
29704
29705        for path in [
29706            "/api/worker/workflow-tasks/poll",
29707            "/api/worker/activity-tasks/poll",
29708            "/api/worker/query-tasks/poll",
29709        ] {
29710            let bodies = server.request_bodies(path);
29711            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
29712            assert!(
29713                bodies
29714                    .iter()
29715                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
29716                "{path} must preserve one request binding across every retry"
29717            );
29718        }
29719    }
29720
29721    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
29722        let reason = if unavailable {
29723            "storage_admission_unavailable"
29724        } else {
29725            "storage_pressure"
29726        };
29727        let mut body = json!({
29728            "reason": reason,
29729            "storage_state": if unavailable { "fenced" } else { "draining" },
29730            "retryable": true,
29731            "retry_after_seconds": 1,
29732        });
29733        if !mid_poll {
29734            body["request_admitted"] = json!(false);
29735        }
29736        if let Some(id) = poll_id {
29737            body["task"] = Value::Null;
29738            body["poll_status"] = json!(reason);
29739            body["poll_request_id"] = json!(id);
29740            body["retry_same_poll_request_id"] = json!(true);
29741            body["claim_admitted"] = json!(false);
29742        }
29743        body
29744    }
29745
29746    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
29747        let operation = match path {
29748            "/api/worker/register" => "register_worker",
29749            "/api/worker/heartbeat" => "heartbeat_worker",
29750            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
29751            "/api/worker/activity-tasks/poll" => "poll_activity_task",
29752            "/api/worker/query-tasks/poll" => "poll_query_task",
29753            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
29754            _ => return None,
29755        };
29756        let request: Value = serde_json::from_str(request).ok()?;
29757        let mut response = json!({
29758            "reason": "backend_unavailable",
29759            "operation": operation,
29760            "outcome": "unknown",
29761            "retryable": true,
29762            "retry_after_seconds": 1,
29763            "worker_id": request["worker_id"],
29764            "task_queue": request.get("task_queue"),
29765        });
29766        if path.ends_with("/poll") {
29767            response["task"] = Value::Null;
29768            response["poll_status"] = json!("backend_unavailable");
29769            response["poll_request_id"] = request["poll_request_id"].clone();
29770            response["retry_same_poll_request_id"] = json!(true);
29771        }
29772        Some(response)
29773    }
29774
29775    fn backend_retry_override(
29776        path: &str,
29777        request: &str,
29778        number: usize,
29779    ) -> Option<(&'static str, String)> {
29780        if number > 8 {
29781            return None;
29782        }
29783        Some((
29784            "503 Service Unavailable",
29785            backend_refusal(path, request)?.to_string(),
29786        ))
29787    }
29788
29789    fn backend_unavailable_override(
29790        path: &str,
29791        request: &str,
29792        _number: usize,
29793    ) -> Option<(&'static str, String)> {
29794        Some((
29795            "503 Service Unavailable",
29796            backend_refusal(path, request)?.to_string(),
29797        ))
29798    }
29799
29800    fn storage_worker(server: &MockWorkerServer) -> Worker {
29801        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
29802            .worker_id("storage-worker")
29803            .retry_policy(WorkerRetryPolicy {
29804                max_retries: 1,
29805                initial_backoff: Duration::from_millis(1),
29806                max_backoff: Duration::from_millis(1),
29807            })
29808    }
29809
29810    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
29811        let requests = server.requests.lock().expect("requests");
29812        let bodies: Vec<_> = requests
29813            .iter()
29814            .filter(|request| request.path == path)
29815            .map(|request| &request.body)
29816            .collect();
29817        assert_eq!(bodies.len(), count, "{path}");
29818        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
29819    }
29820
29821    #[test]
29822    fn backend_recovery_requires_the_explicit_worker_contract() {
29823        for (path, operation) in [
29824            ("/worker/register", "register_worker"),
29825            ("/worker/heartbeat", "heartbeat_worker"),
29826            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
29827            ("/worker/activity-tasks/poll", "poll_activity_task"),
29828            ("/worker/query-tasks/poll", "poll_query_task"),
29829            (
29830                "/worker/update-validation-tasks/poll",
29831                "poll_update_validation_task",
29832            ),
29833        ] {
29834            let poll_id = path.ends_with("/poll").then_some("same-poll");
29835            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
29836            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
29837                .expect("worker operation");
29838            assert_eq!(body["operation"], operation);
29839            let error = Error::Http {
29840                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29841                body: body.to_string(),
29842            };
29843            assert_eq!(
29844                worker_backend_unavailable_retry_after(&error, path, poll_id),
29845                Some(Duration::from_secs(1))
29846            );
29847            assert!(!worker_operation_is_retryable(&error));
29848            for (field, value) in [
29849                ("operation", json!("wrong_operation")),
29850                ("outcome", json!("completed")),
29851                ("retryable", json!(false)),
29852                ("retry_after_seconds", json!(0)),
29853                ("worker_id", json!("")),
29854            ] {
29855                let mut invalid = body.clone();
29856                invalid[field] = value;
29857                let error = Error::Http {
29858                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29859                    body: invalid.to_string(),
29860                };
29861                assert!(
29862                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
29863                    "{path}: {field}"
29864                );
29865                assert!(!worker_operation_is_retryable(&error));
29866            }
29867            if let Some(poll_id) = poll_id {
29868                for (field, value) in [
29869                    ("poll_request_id", json!("wrong-poll")),
29870                    ("poll_status", json!("empty")),
29871                    ("task", json!({"task_id":"claimed"})),
29872                    ("retry_same_poll_request_id", json!(false)),
29873                ] {
29874                    let mut invalid = body.clone();
29875                    invalid[field] = value;
29876                    let error = Error::Http {
29877                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29878                        body: invalid.to_string(),
29879                    };
29880                    assert!(
29881                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
29882                            .is_none(),
29883                        "{path}: {field}"
29884                    );
29885                }
29886            }
29887            let error = Error::Http {
29888                status: reqwest::StatusCode::UNAUTHORIZED,
29889                body: body.to_string(),
29890            };
29891            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
29892            assert!(!worker_operation_is_retryable(&error));
29893        }
29894    }
29895
29896    #[tokio::test]
29897    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
29898        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29899            request_override: Some(backend_retry_override),
29900            ..MockWorkerBehavior::default()
29901        });
29902        let mut worker =
29903            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
29904        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29905        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
29906        worker.register_query("backend.workflow", "state", |_, _| async {
29907            Ok(Value::Null)
29908        });
29909        worker.register().await.expect("registration recovery");
29910        worker
29911            .client
29912            .heartbeat_worker("storage-worker", 1, 1)
29913            .await
29914            .expect("heartbeat recovery");
29915        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
29916        for path in [
29917            "/api/worker/register",
29918            "/api/worker/heartbeat",
29919            "/api/worker/workflow-tasks/poll",
29920            "/api/worker/activity-tasks/poll",
29921            "/api/worker/query-tasks/poll",
29922        ] {
29923            assert_identical_requests(&server, path, 9);
29924        }
29925    }
29926
29927    #[tokio::test]
29928    async fn backend_recovery_wait_stops_with_worker() {
29929        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29930            request_override: Some(backend_unavailable_override),
29931            ..MockWorkerBehavior::default()
29932        });
29933        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
29934            max_retries: 1,
29935            initial_backoff: Duration::from_secs(2),
29936            max_backoff: Duration::from_secs(2),
29937        });
29938        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29939        let started = tokio::time::Instant::now();
29940        let _ = tokio::time::timeout(
29941            Duration::from_secs(1),
29942            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
29943        )
29944        .await
29945        .expect("shutdown interrupts backend wait");
29946        assert!(started.elapsed() < Duration::from_secs(1));
29947        assert!(server.request_count("/api/worker/register") >= 1);
29948    }
29949
29950    #[test]
29951    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
29952        for unavailable in [false, true] {
29953            for mid_poll in [false, true] {
29954                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
29955                let error = Error::Http {
29956                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29957                    body: body.to_string(),
29958                };
29959                assert_eq!(
29960                    worker_storage_admission_retry_after(&error, Some("same-poll")),
29961                    Some(Duration::from_secs(1))
29962                );
29963                assert!(
29964                    !worker_operation_is_retryable(&error),
29965                    "storage is not a bounded generic retry"
29966                );
29967                for (field, value) in [
29968                    ("poll_request_id", json!("wrong-poll")),
29969                    ("task", json!({"task_id":"claimed"})),
29970                    ("retryable", json!(false)),
29971                    ("retry_after_seconds", json!(0)),
29972                    ("retry_after_seconds", json!(true)),
29973                    ("retry_after_seconds", json!(1.0)),
29974                    ("storage_state", json!("normal")),
29975                    ("poll_status", json!("empty")),
29976                    ("claim_admitted", json!(true)),
29977                    ("retry_same_poll_request_id", json!(false)),
29978                    ("request_admitted", json!(true)),
29979                ] {
29980                    let mut invalid = body.clone();
29981                    invalid[field] = value;
29982                    let error = Error::Http {
29983                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29984                        body: invalid.to_string(),
29985                    };
29986                    assert!(
29987                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
29988                        "{field}"
29989                    );
29990                }
29991            }
29992        }
29993        let body = storage_refusal(None, false, false);
29994        let error = Error::Http {
29995            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29996            body: body.to_string(),
29997        };
29998        assert!(worker_storage_admission_retry_after(&error, None).is_some());
29999        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
30000        let error = Error::Http {
30001            status: reqwest::StatusCode::FORBIDDEN,
30002            body: body.to_string(),
30003        };
30004        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30005        let body = storage_refusal(None, false, true);
30006        let error = Error::Http {
30007            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30008            body: body.to_string(),
30009        };
30010        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30011    }
30012
30013    #[tokio::test]
30014    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
30015        for unavailable in [false, true] {
30016            for mid_poll in [false, true] {
30017                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30018                    poll_failures_per_path: 1,
30019                    storage_refusals: 7,
30020                    storage_path: Some("/poll"),
30021                    storage_unavailable: unavailable,
30022                    storage_mid_poll: mid_poll,
30023                    ..MockWorkerBehavior::default()
30024                });
30025                let mut worker = storage_worker(&server);
30026                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
30027                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
30028                for path in [
30029                    "/api/worker/workflow-tasks/poll",
30030                    "/api/worker/activity-tasks/poll",
30031                    "/api/worker/query-tasks/poll",
30032                ] {
30033                    assert_identical_requests(&server, path, 9);
30034                }
30035            }
30036        }
30037    }
30038
30039    #[tokio::test]
30040    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
30041        struct CountedBody(Arc<AtomicUsize>);
30042        impl Serialize for CountedBody {
30043            fn serialize<S: Serializer>(
30044                &self,
30045                serializer: S,
30046            ) -> std::result::Result<S::Ok, S::Error> {
30047                let count = self.0.fetch_add(1, Ordering::SeqCst);
30048                json!({"serialization":count,"lease_owner":"worker","attempt":7})
30049                    .serialize(serializer)
30050            }
30051        }
30052        for path in [
30053            "/api/worker/register",
30054            "/api/worker/heartbeat",
30055            "/api/worker/workflow-tasks/storage-task/complete",
30056            "/api/worker/workflow-tasks/storage-task/fail",
30057            "/api/worker/activity-tasks/storage-task/complete",
30058            "/api/worker/activity-tasks/storage-task/fail",
30059            "/api/worker/activity-tasks/storage-task/heartbeat",
30060            "/api/worker/query-tasks/storage-task/complete",
30061            "/api/worker/query-tasks/storage-task/fail",
30062        ] {
30063            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30064                storage_refusals: 7,
30065                storage_path: Some(path),
30066                ..MockWorkerBehavior::default()
30067            });
30068            let worker =
30069                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30070            let calls = Arc::new(AtomicUsize::new(0));
30071            let _: Value = worker
30072                .client
30073                .request_json(
30074                    reqwest::Method::POST,
30075                    &path[4..],
30076                    RequestProtocol::DefaultWorker,
30077                    Some(&CountedBody(Arc::clone(&calls))),
30078                )
30079                .await
30080                .expect("prepared request recovery");
30081            assert_eq!(calls.load(Ordering::SeqCst), 1);
30082            assert_identical_requests(&server, path, 8);
30083        }
30084        for worker_scope in [false, true] {
30085            let path = if worker_scope {
30086                "/api/health"
30087            } else {
30088                "/api/worker/register"
30089            };
30090            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30091                storage_refusals: usize::MAX,
30092                storage_path: Some(path),
30093                ..MockWorkerBehavior::default()
30094            });
30095            let worker = storage_worker(&server);
30096            let client = worker.client.clone();
30097            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
30098            let error = if worker_scope {
30099                worker
30100                    .client
30101                    .health()
30102                    .await
30103                    .expect_err("control plane is not retried")
30104            } else {
30105                client
30106                    .request_json::<Value, Value>(
30107                        reqwest::Method::POST,
30108                        "/worker/register",
30109                        RequestProtocol::DefaultWorker,
30110                        Some(&json!({})),
30111                    )
30112                    .await
30113                    .expect_err("direct client is not retried")
30114            };
30115            assert!(worker_storage_admission_body(&error).is_some());
30116            assert_eq!(server.request_count(path), 1);
30117        }
30118    }
30119
30120    #[tokio::test]
30121    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
30122        for fail in [false, true] {
30123            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30124                storage_activity: true,
30125                storage_refusals: 7,
30126                storage_path: Some("/storage-activity/"),
30127                ..MockWorkerBehavior::default()
30128            });
30129            let mut worker = storage_worker(&server);
30130            let calls = Arc::new(AtomicUsize::new(0));
30131            let observed = Arc::clone(&calls);
30132            worker.register_activity("storage.activity", move |ctx, _| {
30133                let calls = Arc::clone(&observed);
30134                async move {
30135                    calls.fetch_add(1, Ordering::SeqCst);
30136                    ctx.heartbeat(json!({"step":2})).await?;
30137                    if fail {
30138                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
30139                    } else {
30140                        Ok(json!({"receipt":true}))
30141                    }
30142                }
30143            });
30144            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30145            assert_eq!(calls.load(Ordering::SeqCst), 1);
30146            assert_identical_requests(
30147                &server,
30148                "/api/worker/activity-tasks/storage-activity/heartbeat",
30149                8,
30150            );
30151            let suffix = if fail { "fail" } else { "complete" };
30152            assert_identical_requests(
30153                &server,
30154                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
30155                8,
30156            );
30157            let other = if fail { "complete" } else { "fail" };
30158            assert_eq!(
30159                server.request_count(&format!(
30160                    "/api/worker/activity-tasks/storage-activity/{other}"
30161                )),
30162                0
30163            );
30164        }
30165    }
30166
30167    #[tokio::test]
30168    async fn storage_waits_are_interruptible_without_false_activity_failure() {
30169        for path in [
30170            "/api/worker/register",
30171            "/api/worker/heartbeat",
30172            "/api/worker/activity-tasks/poll",
30173            "/api/worker/activity-tasks/storage-activity/heartbeat",
30174            "/api/worker/activity-tasks/storage-activity/complete",
30175        ] {
30176            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30177                storage_activity: true,
30178                storage_refusals: usize::MAX,
30179                storage_path: Some(path),
30180                ..MockWorkerBehavior::default()
30181            });
30182            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
30183            worker.register_activity("storage.activity", |ctx, _| async move {
30184                ctx.heartbeat(json!({"step":2})).await?;
30185                Ok(json!({"receipt":true}))
30186            });
30187            let shutdown = async {
30188                while server.request_count(path) == 0 {
30189                    tokio::time::sleep(Duration::from_millis(1)).await;
30190                }
30191            };
30192            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
30193                .await
30194                .expect("shutdown interrupts admission");
30195            assert!(
30196                result.is_err(),
30197                "a refused operation must not appear acknowledged: {path}, {result:?}"
30198            );
30199            assert_eq!(server.request_count(path), 1);
30200            assert_eq!(
30201                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
30202                0
30203            );
30204            assert_eq!(
30205                server.request_count("/api/worker/registrations/mock-worker"),
30206                usize::from(!path.ends_with("/register"))
30207            );
30208        }
30209    }
30210
30211    #[tokio::test]
30212    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
30213        for fail in [false, true] {
30214            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30215                storage_query: true,
30216                storage_refusals: 7,
30217                storage_path: Some("/storage-query/"),
30218                ..MockWorkerBehavior::default()
30219            });
30220            let mut worker = storage_worker(&server);
30221            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
30222            let calls = Arc::new(AtomicUsize::new(0));
30223            let observed = Arc::clone(&calls);
30224            worker.register_query("storage.workflow", "state", move |_, _| {
30225                let calls = Arc::clone(&observed);
30226                async move {
30227                    calls.fetch_add(1, Ordering::SeqCst);
30228                    if fail {
30229                        Err(Error::WorkerLoop("intentional query failure".to_string()))
30230                    } else {
30231                        Ok(json!({"state":"waiting"}))
30232                    }
30233                }
30234            });
30235            assert_eq!(worker.run_once().await.expect("query settled"), 1);
30236            assert_eq!(calls.load(Ordering::SeqCst), 1);
30237            let suffix = if fail { "fail" } else { "complete" };
30238            assert_identical_requests(
30239                &server,
30240                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
30241                8,
30242            );
30243            let other = if fail { "complete" } else { "fail" };
30244            assert_eq!(
30245                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
30246                0
30247            );
30248        }
30249    }
30250
30251    #[tokio::test]
30252    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
30253        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30254            storage_refusals: 7,
30255            storage_path: Some("/poll"),
30256            unauthorized_polls: true,
30257            ..MockWorkerBehavior::default()
30258        });
30259        let error = storage_worker(&server)
30260            .run_once()
30261            .await
30262            .expect_err("auth remains terminal");
30263        assert!(matches!(
30264            error,
30265            Error::Http {
30266                status: reqwest::StatusCode::UNAUTHORIZED,
30267                ..
30268            }
30269        ));
30270        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
30271
30272        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30273            storage_refusals: 7,
30274            storage_path: Some("/activity-cancel/complete"),
30275            ..MockWorkerBehavior::default()
30276        });
30277        let worker =
30278            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30279        let error = worker
30280            .client
30281            .complete_activity_task(
30282                "activity-cancel",
30283                "attempt-cancel",
30284                "worker",
30285                json!({}),
30286                DEFAULT_CODEC,
30287            )
30288            .await
30289            .expect_err("cancellation remains terminal");
30290        assert!(activity_task_rejection_is_final(&error));
30291        assert_identical_requests(
30292            &server,
30293            "/api/worker/activity-tasks/activity-cancel/complete",
30294            8,
30295        );
30296
30297        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30298            storage_refusals: usize::MAX,
30299            storage_path: Some("/poll"),
30300            storage_wrong_poll_id: true,
30301            ..MockWorkerBehavior::default()
30302        });
30303        assert!(storage_worker(&server).run_once().await.is_err());
30304        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
30305    }
30306
30307    #[tokio::test]
30308    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
30309        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30310            storage_refusals: usize::MAX,
30311            storage_path: Some("/poll"),
30312            ..MockWorkerBehavior::default()
30313        });
30314        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
30315        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
30316        let run = tokio::spawn(async move { worker.run().await });
30317        tokio::time::timeout(Duration::from_secs(2), async {
30318            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
30319                tokio::time::sleep(Duration::from_millis(1)).await;
30320            }
30321        })
30322        .await
30323        .expect("poll started");
30324        run.abort();
30325        assert!(run.await.expect_err("cancelled run").is_cancelled());
30326        tokio::time::sleep(Duration::from_millis(250)).await;
30327        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
30328    }
30329
30330    #[tokio::test]
30331    async fn query_protocol_rejection_from_older_server_is_typed() {
30332        let server = MockWorkerServer::reject_query_protocol();
30333        let client = Client::builder(server.base_url())
30334            .timeout(Duration::from_secs(2))
30335            .build()
30336            .expect("client");
30337
30338        let error = client
30339            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
30340            .await
30341            .expect_err("server below query protocol floor must reject");
30342        let Error::Protocol(failure) = error else {
30343            panic!("expected typed protocol failure");
30344        };
30345
30346        assert_eq!(failure.status, 400);
30347        assert_eq!(failure.reason, "unsupported_protocol_version");
30348        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
30349        assert_eq!(
30350            failure.requested_version.as_deref(),
30351            Some(WORKER_PROTOCOL_VERSION)
30352        );
30353        assert_eq!(
30354            server
30355                .worker_protocol_for("/api/worker/query-tasks/poll")
30356                .as_deref(),
30357            Some(WORKER_PROTOCOL_VERSION)
30358        );
30359    }
30360
30361    #[tokio::test]
30362    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
30363        let server = MockWorkerServer::reject_query_protocol();
30364        let client = Client::builder(server.base_url())
30365            .timeout(Duration::from_secs(2))
30366            .build()
30367            .expect("client");
30368        let mut worker = Worker::new(client, "rust-workers")
30369            .worker_id("baseline-worker")
30370            .poll_timeout(Duration::from_millis(10));
30371
30372        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
30373            Ok(Value::Null)
30374        });
30375
30376        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
30377        assert_eq!(
30378            server
30379                .worker_protocol_for("/api/worker/workflow-tasks/poll")
30380                .as_deref(),
30381            Some(WORKER_PROTOCOL_VERSION)
30382        );
30383        assert_eq!(
30384            server.worker_protocol_for("/api/worker/query-tasks/poll"),
30385            None,
30386            "a worker without query handlers must not use the query-task endpoint"
30387        );
30388    }
30389
30390    #[tokio::test]
30391    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
30392        let server = MockWorkerServer::reject_query_completion();
30393        let client = Client::builder(server.base_url())
30394            .timeout(Duration::from_secs(2))
30395            .build()
30396            .expect("client");
30397
30398        let error = client
30399            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
30400            .await
30401            .expect_err("expired completion must be rejected");
30402        let Error::QueryFailed(failure) = error else {
30403            panic!("expected typed query failure");
30404        };
30405        assert_eq!(failure.status, 409);
30406        assert_eq!(failure.reason, "query_task_timed_out");
30407
30408        let mut worker = Worker::new(client, "rust-workers")
30409            .worker_id("late-worker")
30410            .poll_timeout(Duration::from_millis(10));
30411        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30412        worker.register_query(
30413            "counter",
30414            "current",
30415            |_ctx, _args| async move { Ok(json!(8)) },
30416        );
30417
30418        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
30419        assert_eq!(
30420            worker
30421                .run_once()
30422                .await
30423                .expect("worker continues after late completion"),
30424            0
30425        );
30426        assert_eq!(
30427            server.request_count("/api/worker/query-tasks/query-late/complete"),
30428            2
30429        );
30430        assert_eq!(
30431            server.request_count("/api/worker/query-tasks/query-late/fail"),
30432            0,
30433            "a server completion rejection must not be reported as an encoding failure"
30434        );
30435    }
30436
30437    #[tokio::test]
30438    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
30439        let server = MockWorkerServer::start();
30440        let client = Client::builder(server.base_url())
30441            .timeout(Duration::from_secs(2))
30442            .build()
30443            .expect("client");
30444        let mut worker = Worker::new(client, "rust-workers")
30445            .worker_id("joined-worker")
30446            .poll_timeout(Duration::from_millis(10));
30447        worker.register_workflow(
30448            "joined.workflow",
30449            |_ctx, _input| async move { Ok(Value::Null) },
30450        );
30451        worker.register_activity(
30452            "joined.activity",
30453            |_ctx, _input| async move { Ok(Value::Null) },
30454        );
30455        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
30456            Ok(Value::Null)
30457        });
30458
30459        worker
30460            .run_until(tokio::time::sleep(Duration::from_millis(20)))
30461            .await
30462            .expect("normal shutdown");
30463
30464        let deregistration_path = "/api/worker/registrations/mock-worker";
30465        assert_eq!(server.request_count(deregistration_path), 1);
30466        for poll_path in [
30467            "/api/worker/workflow-tasks/poll",
30468            "/api/worker/activity-tasks/poll",
30469            "/api/worker/query-tasks/poll",
30470        ] {
30471            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
30472        }
30473        assert_eq!(
30474            server.captured_paths().last().map(String::as_str),
30475            Some(deregistration_path),
30476            "deregistration must start only after every poller has joined"
30477        );
30478    }
30479
30480    #[tokio::test]
30481    async fn registration_failure_does_not_deregister() {
30482        let server = MockWorkerServer::rejected_registration();
30483        let client = Client::builder(server.base_url())
30484            .timeout(Duration::from_secs(2))
30485            .build()
30486            .expect("client");
30487        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
30488
30489        let error = worker
30490            .run_until(async {})
30491            .await
30492            .expect_err("registration must fail");
30493        assert!(matches!(
30494            error,
30495            Error::Http {
30496                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30497                ..
30498            }
30499        ));
30500        assert!(server
30501            .captured_paths()
30502            .iter()
30503            .all(|path| !path.starts_with("/api/worker/registrations/")));
30504    }
30505
30506    #[tokio::test]
30507    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
30508        let server = MockWorkerServer::rejected_registration_protocol();
30509        let client = Client::builder(server.base_url())
30510            .timeout(Duration::from_secs(2))
30511            .build()
30512            .expect("client");
30513        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
30514
30515        let error = worker
30516            .run_until(async {})
30517            .await
30518            .expect_err("a protocol 1.16 server must reject this worker");
30519        let Error::Protocol(failure) = error else {
30520            panic!("expected typed protocol rejection");
30521        };
30522        assert_eq!(failure.reason, "unsupported_protocol_version");
30523        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
30524        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
30525        assert_eq!(
30526            server
30527                .worker_protocol_for("/api/worker/register")
30528                .as_deref(),
30529            Some(WORKER_PROTOCOL_VERSION)
30530        );
30531    }
30532
30533    #[tokio::test]
30534    async fn declined_registration_does_not_deregister() {
30535        let server = MockWorkerServer::declined_registration();
30536        let client = Client::builder(server.base_url())
30537            .timeout(Duration::from_secs(2))
30538            .build()
30539            .expect("client");
30540        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
30541
30542        let error = worker
30543            .run_until(async {})
30544            .await
30545            .expect_err("declined registration must fail");
30546        assert!(matches!(error, Error::WorkerLoop(_)));
30547        assert!(error.to_string().contains("was not accepted"));
30548        assert!(server
30549            .captured_paths()
30550            .iter()
30551            .all(|path| !path.starts_with("/api/worker/registrations/")));
30552    }
30553
30554    #[tokio::test]
30555    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
30556        let server = MockWorkerServer::rejected_deregistration();
30557        let client = Client::builder(server.base_url())
30558            .timeout(Duration::from_secs(2))
30559            .build()
30560            .expect("client");
30561        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
30562
30563        let error = worker
30564            .run_until(async {})
30565            .await
30566            .expect_err("deregistration must fail");
30567        assert!(matches!(
30568            error,
30569            Error::Http {
30570                status: reqwest::StatusCode::FORBIDDEN,
30571                ..
30572            }
30573        ));
30574        assert_eq!(
30575            server.request_count("/api/worker/registrations/mock-worker"),
30576            1
30577        );
30578    }
30579
30580    #[tokio::test]
30581    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
30582        let server = MockWorkerServer::rejected_deregistration_protocol();
30583        let client = Client::builder(server.base_url())
30584            .timeout(Duration::from_secs(2))
30585            .build()
30586            .expect("client");
30587        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
30588
30589        let error = worker
30590            .run_until(async {})
30591            .await
30592            .expect_err("protocol rejection must fail shutdown");
30593        let Error::Protocol(failure) = error else {
30594            panic!("expected typed protocol failure");
30595        };
30596        assert_eq!(failure.reason, "unsupported_protocol_version");
30597        assert_eq!(
30598            failure.requested_version.as_deref(),
30599            Some(WORKER_PROTOCOL_VERSION)
30600        );
30601        assert_eq!(
30602            server.request_count("/api/worker/registrations/mock-worker"),
30603            1
30604        );
30605    }
30606
30607    #[tokio::test]
30608    async fn primary_poller_error_retains_deregistration_failure_context() {
30609        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
30610        let client = Client::builder(server.base_url())
30611            .timeout(Duration::from_secs(2))
30612            .build()
30613            .expect("client");
30614        let mut worker = Worker::new(client, "rust-workers")
30615            .worker_id("combined-failure")
30616            .poll_timeout(Duration::from_millis(10));
30617        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
30618            Ok(Value::Null)
30619        });
30620
30621        let error = worker
30622            .run()
30623            .await
30624            .expect_err("worker and cleanup must fail");
30625        let summary = error.to_string();
30626        assert!(summary.contains("authentication_failed"));
30627        assert!(summary.contains("worker cannot deregister"));
30628        let Error::WorkerShutdown {
30629            primary,
30630            deregistration,
30631        } = error
30632        else {
30633            panic!("expected combined worker shutdown error");
30634        };
30635        assert!(matches!(
30636            *primary,
30637            Error::Http {
30638                status: reqwest::StatusCode::UNAUTHORIZED,
30639                ..
30640            }
30641        ));
30642        assert!(matches!(
30643            *deregistration,
30644            Error::Http {
30645                status: reqwest::StatusCode::FORBIDDEN,
30646                ..
30647            }
30648        ));
30649        assert_eq!(
30650            server.request_count("/api/worker/registrations/mock-worker"),
30651            1
30652        );
30653    }
30654
30655    #[tokio::test]
30656    async fn activity_only_worker_can_shutdown_without_workflow_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("activity-only-worker")
30664            .poll_timeout(Duration::from_millis(10));
30665
30666        worker.register_activity(
30667            "activity.only",
30668            |_ctx, _args| async move { Ok(Value::Null) },
30669        );
30670
30671        worker.run_until(async {}).await.expect("run worker");
30672    }
30673
30674    #[tokio::test]
30675    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
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 mut worker = Worker::new(client, "rust-workers")
30682            .worker_id("workflow-only-worker")
30683            .poll_timeout(Duration::from_millis(10));
30684
30685        worker.register_workflow(
30686            "workflow.only",
30687            |_ctx, _input| async move { Ok(Value::Null) },
30688        );
30689
30690        worker.run_until(async {}).await.expect("run worker");
30691    }
30692
30693    #[tokio::test]
30694    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
30695        let server = MockWorkerServer::start();
30696        let client = Client::builder(server.base_url())
30697            .timeout(Duration::from_secs(2))
30698            .build()
30699            .expect("client");
30700        let observations = Arc::new(Mutex::new(Vec::new()));
30701        let observed = Arc::clone(&observations);
30702        let mut worker = Worker::new(client, "rust-workers")
30703            .worker_id("observed-heartbeat-worker")
30704            .poll_timeout(Duration::from_millis(10))
30705            .on_worker_heartbeat(move |observation| {
30706                observed
30707                    .lock()
30708                    .expect("heartbeat observations")
30709                    .push(observation.clone());
30710            });
30711
30712        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
30713            Ok(Value::Null)
30714        });
30715        let acknowledged = Arc::clone(&observations);
30716        worker
30717            .run_until(async move {
30718                tokio::time::timeout(Duration::from_secs(2), async move {
30719                    loop {
30720                        if !acknowledged
30721                            .lock()
30722                            .expect("heartbeat observations")
30723                            .is_empty()
30724                        {
30725                            break;
30726                        }
30727                        tokio::time::sleep(Duration::from_millis(1)).await;
30728                    }
30729                })
30730                .await
30731                .expect("heartbeat acknowledgement within timeout");
30732            })
30733            .await
30734            .expect("run worker");
30735
30736        let observations = observations.lock().expect("heartbeat observations");
30737        let first = observations.first().expect("heartbeat acknowledgement");
30738        assert_eq!(first.worker_id, "observed-heartbeat-worker");
30739        assert_eq!(first.task_queue, "rust-workers");
30740        assert!(first.acknowledged_at_unix_millis > 0);
30741        assert_eq!(first.acknowledgement, json!({}));
30742    }
30743
30744    #[tokio::test]
30745    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
30746        let server = MockWorkerServer::delayed_heartbeat_worker();
30747        let client = Client::builder(server.base_url())
30748            .timeout(Duration::from_secs(3))
30749            .build()
30750            .expect("client");
30751        let observations = Arc::new(Mutex::new(Vec::new()));
30752        let observed = Arc::clone(&observations);
30753        let mut worker = Worker::new(client, "rust-snapshot-workers")
30754            .worker_id("rust-snapshot-worker")
30755            .poll_timeout(Duration::from_millis(10))
30756            .on_worker_heartbeat(move |observation| {
30757                observed
30758                    .lock()
30759                    .expect("heartbeat observations")
30760                    .push(observation.clone());
30761            });
30762
30763        worker.register_workflow("snapshot", |ctx, _input| async move {
30764            ctx.wait_signal("finish").await?;
30765            Ok(json!({"status": "finished"}))
30766        });
30767        worker.register_query("snapshot", "current", |ctx, _args| async move {
30768            Ok(json!(ctx
30769                .signals("increment")
30770                .iter()
30771                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30772                .sum::<i64>()))
30773        });
30774        worker.register_activity("cancel-aware", |_ctx, _args| async move {
30775            Ok(json!({"late": "completion"}))
30776        });
30777
30778        worker
30779            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
30780            .await
30781            .expect("delayed heartbeat must allow a clean worker shutdown");
30782
30783        let observations = observations.lock().expect("heartbeat observations");
30784        assert!(
30785            observations.len() >= 3,
30786            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
30787        );
30788        assert!(
30789            observations.windows(2).all(|pair| {
30790                pair[1].acknowledged_at_unix_millis
30791                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30792                    >= 850
30793            }),
30794            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
30795        );
30796        drop(observations);
30797
30798        let heartbeat_times = server.request_times("/api/worker/heartbeat");
30799        let delayed_request_at = *heartbeat_times
30800            .get(1)
30801            .expect("intentionally delayed heartbeat request");
30802        let delay_window_start = delayed_request_at + Duration::from_millis(100);
30803        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
30804        for path in [
30805            "/api/worker/workflow-tasks/poll",
30806            "/api/worker/activity-tasks/poll",
30807            "/api/worker/query-tasks/poll",
30808        ] {
30809            assert!(
30810                server
30811                    .request_times(path)
30812                    .iter()
30813                    .any(|received_at| *received_at >= delay_window_start
30814                        && *received_at <= delay_window_end),
30815                "{path} must keep polling while a heartbeat acknowledgement is delayed"
30816            );
30817        }
30818        assert!(
30819            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
30820            "workflow work must be settled"
30821        );
30822        assert!(
30823            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
30824            "activity work must be settled"
30825        );
30826        assert!(
30827            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
30828            "query work must be settled"
30829        );
30830    }
30831
30832    #[tokio::test]
30833    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
30834        let server = MockWorkerServer::heartbeat_retry_worker();
30835        let client = Client::builder(server.base_url())
30836            .timeout(Duration::from_secs(2))
30837            .build()
30838            .expect("client");
30839        let observations = Arc::new(Mutex::new(Vec::new()));
30840        let observed = Arc::clone(&observations);
30841        let worker = Worker::new(client, "rust-workers")
30842            .worker_id("heartbeat-retry-worker")
30843            .retry_policy(WorkerRetryPolicy {
30844                max_retries: 1,
30845                initial_backoff: Duration::from_millis(300),
30846                max_backoff: Duration::from_millis(300),
30847            })
30848            .on_worker_heartbeat(move |observation| {
30849                observed
30850                    .lock()
30851                    .expect("heartbeat observations")
30852                    .push(observation.clone());
30853            });
30854
30855        worker
30856            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
30857            .await
30858            .expect("retryable heartbeat failure must remain bounded and recover");
30859
30860        let observations = observations.lock().expect("heartbeat observations");
30861        assert!(observations.len() >= 3, "heartbeat retry must recover");
30862        assert!(
30863            observations.windows(2).all(|pair| {
30864                pair[1]
30865                    .acknowledged_at_unix_millis
30866                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30867                    >= 850
30868            }),
30869            "a successful retry must start a fresh advertised cadence: {observations:?}"
30870        );
30871        assert_eq!(
30872            server.request_count("/api/worker/heartbeat"),
30873            observations.len() + 1,
30874            "one retryable failure must add exactly one bounded request"
30875        );
30876    }
30877
30878    #[tokio::test]
30879    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
30880        let server = MockWorkerServer::waiting_query_worker();
30881        let client = Client::builder(server.base_url())
30882            .timeout(Duration::from_secs(2))
30883            .build()
30884            .expect("client");
30885        let observations = Arc::new(Mutex::new(Vec::new()));
30886        let observed = Arc::clone(&observations);
30887        let mut worker = Worker::new(client, "rust-snapshot-workers")
30888            .worker_id("rust-snapshot-worker")
30889            .poll_timeout(Duration::from_millis(10))
30890            .on_worker_heartbeat(move |observation| {
30891                observed
30892                    .lock()
30893                    .expect("heartbeat observations")
30894                    .push(observation.clone());
30895            });
30896
30897        worker.register_workflow("snapshot", |ctx, _input| async move {
30898            ctx.wait_signal("finish").await?;
30899            Ok(json!({"status": "finished"}))
30900        });
30901        worker.register_query("snapshot", "current", |ctx, _args| async move {
30902            let current = ctx
30903                .signals("increment")
30904                .iter()
30905                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30906                .sum::<i64>();
30907            Ok(json!(current))
30908        });
30909        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
30910        worker
30911            .declare_workflow_signals("snapshot", &["finish"])
30912            .expect("declare finish signal");
30913
30914        worker
30915            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
30916            .await
30917            .expect("pending workflow and query poller must remain live until shutdown");
30918
30919        assert!(
30920            observations.lock().expect("heartbeat observations").len() >= 4,
30921            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
30922        );
30923        assert!(
30924            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
30925            "workflow polling must continue after empty replay acknowledgements"
30926        );
30927        assert!(
30928            server.request_count("/api/worker/query-tasks/poll") >= 2,
30929            "query polling must continue after serving the current query"
30930        );
30931        assert_eq!(
30932            server.request_body("/api/worker/register")["capabilities"],
30933            json!([
30934                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
30935                "workflow_entry_arguments_validation",
30936                DURABLE_SELECTION_CAPABILITY,
30937                MEMO_UPSERTS_CAPABILITY,
30938                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
30939                QUERY_TASKS_CAPABILITY,
30940                WORKFLOW_UPDATES_CAPABILITY,
30941                MESSAGE_STREAMS_CAPABILITY
30942            ])
30943        );
30944        assert_eq!(
30945            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
30946            json!({
30947                "queries": ["current"],
30948                "query_contracts": [{
30949                    "name": "current",
30950                    "parameters": [{
30951                        "name": "args", "position": 0, "required": false,
30952                        "variadic": true, "type": null, "allows_null": true,
30953                        "default_available": false, "default": null,
30954                    }],
30955                }],
30956                "signals": ["finish"],
30957                "signal_contracts": [{
30958                    "name": "finish",
30959                    "parameters": [{
30960                        "name": "args", "position": 0, "required": false,
30961                        "variadic": true, "type": null, "allows_null": true,
30962                        "default_available": false, "default": null,
30963                    }],
30964                }],
30965                "updates": ["replace"],
30966                "update_contracts": [{
30967                    "name": "replace",
30968                    "parameters": [{
30969                        "name": "args", "position": 0, "required": false,
30970                        "variadic": true, "type": null, "allows_null": true,
30971                        "default_available": false, "default": null,
30972                    }],
30973                }],
30974                "update_validators": [],
30975            })
30976        );
30977
30978        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
30979        assert_eq!(
30980            opened["commands"],
30981            json!([{
30982                "type": "open_signal_wait",
30983                "signal_name": "finish",
30984            }])
30985        );
30986
30987        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
30988            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
30989            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
30990            let failure = server.request_body(&fail_path);
30991            assert_eq!(
30992                failure["failure"]["type"],
30993                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
30994            );
30995            assert_eq!(server.request_count(&completion_path), 0);
30996        }
30997
30998        let query_completion =
30999            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
31000        assert_eq!(query_completion["result"], json!(8));
31001
31002        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
31003        assert_eq!(
31004            server.request_count(terminal_path),
31005            1,
31006            "the matching signal must settle the workflow exactly once"
31007        );
31008        let terminal = server.request_body(terminal_path);
31009        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
31010        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
31011        assert_eq!(
31012            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
31013                .expect("terminal workflow result"),
31014            json!({"status": "finished"})
31015        );
31016    }
31017
31018    #[tokio::test]
31019    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
31020        let server = MockWorkerServer::transient_worker_failures();
31021        let client = Client::builder(server.base_url())
31022            .timeout(Duration::from_secs(2))
31023            .build()
31024            .expect("client");
31025        let mut worker = Worker::new(client, "rust-workers")
31026            .worker_id("retry-worker")
31027            .poll_timeout(Duration::from_millis(10))
31028            .retry_policy(WorkerRetryPolicy {
31029                max_retries: 2,
31030                initial_backoff: Duration::from_millis(1),
31031                max_backoff: Duration::from_millis(1),
31032            });
31033        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31034        worker.register_activity(
31035            "counter.activity",
31036            |_ctx, _input| async move { Ok(Value::Null) },
31037        );
31038        worker.register_query(
31039            "counter",
31040            "current",
31041            |_ctx, _args| async move { Ok(json!(8)) },
31042        );
31043
31044        worker
31045            .run_until(tokio::time::sleep(Duration::from_millis(75)))
31046            .await
31047            .expect("transient failures must not stop the worker");
31048
31049        for path in [
31050            "/api/worker/heartbeat",
31051            "/api/worker/workflow-tasks/poll",
31052            "/api/worker/activity-tasks/poll",
31053            "/api/worker/query-tasks/poll",
31054        ] {
31055            assert!(
31056                server.request_count(path) >= 2,
31057                "{path} must continue after its transient failure"
31058            );
31059        }
31060    }
31061
31062    #[tokio::test]
31063    async fn worker_continues_after_long_poll_capacity_backpressure() {
31064        let server = MockWorkerServer::capacity_limited_activity_poll();
31065        let client = Client::builder(server.base_url())
31066            .timeout(Duration::from_secs(2))
31067            .build()
31068            .expect("client");
31069        let mut worker = Worker::new(client, "rust-workers")
31070            .worker_id("capacity-worker")
31071            .poll_timeout(Duration::from_millis(10))
31072            .retry_policy(WorkerRetryPolicy {
31073                max_retries: 0,
31074                initial_backoff: Duration::from_millis(1),
31075                max_backoff: Duration::from_millis(1),
31076            });
31077        worker.register_activity("capacity.activity", |_ctx, _input| async move {
31078            Ok(json!({"handled": true}))
31079        });
31080
31081        worker
31082            .run_until(tokio::time::sleep(Duration::from_millis(50)))
31083            .await
31084            .expect("capacity backpressure must not stop the worker");
31085
31086        assert!(
31087            server.request_count("/api/worker/activity-tasks/poll") >= 2,
31088            "the activity poller must continue after capacity backpressure"
31089        );
31090        assert_eq!(
31091            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
31092            1,
31093            "the worker must complete work returned after capacity recovers"
31094        );
31095    }
31096
31097    #[test]
31098    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
31099        let capacity = Error::Http {
31100            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31101            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
31102        };
31103        assert_eq!(
31104            worker_poll_capacity_retry_after(&capacity),
31105            Some(Duration::from_secs(3))
31106        );
31107
31108        let rejected_capacity = Error::Http {
31109            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31110            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
31111        };
31112        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
31113        assert!(!worker_operation_is_retryable(&rejected_capacity));
31114
31115        let ordinary_rate_limit = Error::Http {
31116            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31117            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
31118                .to_string(),
31119        };
31120        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
31121        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
31122    }
31123
31124    #[tokio::test]
31125    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
31126        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31127            poll_failures_per_path: 8,
31128            heartbeat_failures: 8,
31129            ..MockWorkerBehavior::default()
31130        });
31131        let client = Client::builder(server.base_url())
31132            .timeout(Duration::from_secs(2))
31133            .build()
31134            .expect("client");
31135        let acknowledgements = Arc::new(AtomicUsize::new(0));
31136        let observed = Arc::clone(&acknowledgements);
31137        let mut worker = Worker::new(client, "rust-workers")
31138            .recover_transient_outages(true)
31139            .poll_timeout(Duration::from_millis(10))
31140            .retry_policy(WorkerRetryPolicy {
31141                max_retries: 2,
31142                initial_backoff: Duration::from_millis(2),
31143                max_backoff: Duration::from_millis(5),
31144            })
31145            .on_worker_heartbeat(move |_| {
31146                observed.fetch_add(1, Ordering::SeqCst);
31147            });
31148        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31149        worker.register_activity(
31150            "counter.activity",
31151            |_ctx, _input| async move { Ok(Value::Null) },
31152        );
31153        worker.register_query("counter", "current", |_ctx, _args| async move {
31154            Ok(Value::Null)
31155        });
31156
31157        worker
31158            .run_until(tokio::time::sleep(Duration::from_millis(500)))
31159            .await
31160            .expect("a recoverable outage must not stop the service worker");
31161
31162        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
31163        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
31164        for path in [
31165            "/api/worker/workflow-tasks/poll",
31166            "/api/worker/activity-tasks/poll",
31167            "/api/worker/query-tasks/poll",
31168        ] {
31169            let bodies = server.request_bodies(path);
31170            assert!(bodies.len() >= 10, "{path} must resume after recovery");
31171            let first = &bodies[0]["poll_request_id"];
31172            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
31173            for body in &bodies[..9] {
31174                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
31175            }
31176            assert_ne!(&bodies[9]["poll_request_id"], first);
31177            let times = server.request_times(path);
31178            for pair in times[..9].windows(2) {
31179                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
31180            }
31181        }
31182    }
31183
31184    #[tokio::test]
31185    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
31186        for heartbeat_outage in [false, true] {
31187            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31188                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
31189                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
31190                ..MockWorkerBehavior::default()
31191            });
31192            let client = Client::builder(server.base_url()).build().expect("client");
31193            let mut worker = Worker::new(client, "rust-workers")
31194                .recover_transient_outages(true)
31195                .retry_policy(WorkerRetryPolicy {
31196                    max_retries: 1,
31197                    initial_backoff: Duration::from_secs(5),
31198                    max_backoff: Duration::from_secs(5),
31199                });
31200            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31201            let started = Instant::now();
31202            worker
31203                .run_until(tokio::time::sleep(Duration::from_millis(200)))
31204                .await
31205                .expect("shutdown during an outage is a normal stop");
31206            assert!(started.elapsed() < Duration::from_secs(1));
31207            let path = if heartbeat_outage {
31208                "/api/worker/heartbeat"
31209            } else {
31210                "/api/worker/workflow-tasks/poll"
31211            };
31212            assert_eq!(server.request_count(path), 1);
31213            assert_eq!(
31214                server.request_count("/api/worker/registrations/mock-worker"),
31215                1
31216            );
31217        }
31218    }
31219
31220    #[tokio::test]
31221    async fn worker_outage_recovery_keeps_run_once_bounded() {
31222        let server = MockWorkerServer::unavailable_polls();
31223        let client = Client::builder(server.base_url()).build().expect("client");
31224        let mut worker = Worker::new(client, "rust-workers")
31225            .recover_transient_outages(true)
31226            .retry_policy(WorkerRetryPolicy {
31227                max_retries: 2,
31228                initial_backoff: Duration::from_millis(1),
31229                max_backoff: Duration::from_millis(1),
31230            });
31231        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31232        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
31233        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
31234    }
31235
31236    #[tokio::test]
31237    async fn worker_outage_recovery_respects_disabled_retries() {
31238        let server = MockWorkerServer::unavailable_polls();
31239        let client = Client::builder(server.base_url()).build().expect("client");
31240        let mut worker = Worker::new(client, "rust-workers")
31241            .recover_transient_outages(true)
31242            .retry_policy(WorkerRetryPolicy {
31243                max_retries: 0,
31244                ..WorkerRetryPolicy::default()
31245            });
31246        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31247        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
31248        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31249    }
31250
31251    #[tokio::test]
31252    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
31253        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31254            heartbeat_failures: usize::MAX,
31255            unauthorized_polls: true,
31256            ..MockWorkerBehavior::default()
31257        });
31258        let client = Client::builder(server.base_url()).build().expect("client");
31259        let mut worker = Worker::new(client, "rust-workers")
31260            .recover_transient_outages(true)
31261            .retry_policy(WorkerRetryPolicy {
31262                max_retries: 1,
31263                initial_backoff: Duration::from_secs(5),
31264                max_backoff: Duration::from_secs(5),
31265            });
31266        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31267        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
31268            .await
31269            .expect("fatal poll errors must interrupt heartbeat recovery")
31270            .expect_err("authentication failure is terminal");
31271        assert!(
31272            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
31273        );
31274        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31275    }
31276
31277    #[tokio::test]
31278    async fn worker_bounds_transport_retries() {
31279        let server = MockWorkerServer::unavailable_polls();
31280        let client = Client::builder(server.base_url())
31281            .timeout(Duration::from_secs(2))
31282            .build()
31283            .expect("client");
31284        let mut worker = Worker::new(client, "rust-workers")
31285            .worker_id("bounded-retry-worker")
31286            .poll_timeout(Duration::from_millis(10))
31287            .retry_policy(WorkerRetryPolicy {
31288                max_retries: 2,
31289                initial_backoff: Duration::from_millis(1),
31290                max_backoff: Duration::from_millis(1),
31291            });
31292        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31293
31294        let error = worker.run().await.expect_err("retry bound must terminate");
31295        assert!(matches!(error, Error::Transport(_)));
31296        assert_eq!(
31297            server.request_count("/api/worker/workflow-tasks/poll"),
31298            3,
31299            "one initial request plus exactly two retries"
31300        );
31301    }
31302
31303    #[tokio::test]
31304    async fn worker_retry_policy_can_disable_poll_retries() {
31305        let server = MockWorkerServer::unavailable_polls();
31306        let client = Client::builder(server.base_url())
31307            .timeout(Duration::from_secs(2))
31308            .build()
31309            .expect("client");
31310        let mut worker = Worker::new(client, "rust-workers")
31311            .worker_id("no-retry-worker")
31312            .poll_timeout(Duration::from_millis(10))
31313            .retry_policy(WorkerRetryPolicy {
31314                max_retries: 0,
31315                initial_backoff: Duration::from_millis(1),
31316                max_backoff: Duration::from_millis(1),
31317            });
31318        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31319
31320        let error = worker
31321            .run_once()
31322            .await
31323            .expect_err("disabled retries must return the first transport failure");
31324        assert!(matches!(error, Error::Transport(_)));
31325        assert_eq!(
31326            server.request_count("/api/worker/workflow-tasks/poll"),
31327            1,
31328            "max_retries=0 must send only the initial request"
31329        );
31330    }
31331
31332    #[tokio::test]
31333    async fn worker_does_not_retry_authentication_failures() {
31334        let server = MockWorkerServer::unauthorized_polls();
31335        let client = Client::builder(server.base_url())
31336            .timeout(Duration::from_secs(2))
31337            .build()
31338            .expect("client");
31339        let mut worker = Worker::new(client, "rust-workers")
31340            .worker_id("unauthorized-worker")
31341            .recover_transient_outages(true)
31342            .poll_timeout(Duration::from_millis(10));
31343        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31344
31345        let error = worker
31346            .run()
31347            .await
31348            .expect_err("authentication must terminate");
31349        let Error::Http { status, body } = error else {
31350            panic!("expected stable HTTP authentication error");
31351        };
31352        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
31353        assert!(body.contains("authentication_failed"));
31354        assert_eq!(
31355            server.request_count("/api/worker/workflow-tasks/poll"),
31356            1,
31357            "authentication failures must not be retried"
31358        );
31359    }
31360
31361    #[test]
31362    fn duplicate_registration_keeps_the_original_workflow() {
31363        let client = Client::new("http://127.0.0.1:9").expect("client");
31364        let mut worker = Worker::new(client, "registration-tests");
31365        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31366        let original = Arc::clone(&worker.workflows["same"].execute);
31367        worker
31368            .set_workflow_definition_sources("same", &["first workflow source"])
31369            .expect("source identity");
31370        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
31371        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
31372        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
31373        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
31374    }
31375
31376    #[test]
31377    fn duplicate_registration_keeps_the_original_activity() {
31378        let client = Client::new("http://127.0.0.1:9").expect("client");
31379        let mut worker = Worker::new(client, "registration-tests");
31380        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
31381        let original = Arc::clone(&worker.activities["same"]);
31382        worker.register_activity_avro_value("same", |_ctx, _input| async {
31383            Ok(AvroValue::String("second".into()))
31384        });
31385        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
31386    }
31387
31388    #[test]
31389    fn duplicate_registration_keeps_original_query_and_update_handlers() {
31390        let client = Client::new("http://127.0.0.1:9").expect("client");
31391        let mut worker = Worker::new(client, "registration-tests");
31392        worker.register_query("orders", "same", |_ctx, _input| async {
31393            Ok(json!("first"))
31394        });
31395        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
31396            panic!("snapshot query");
31397        };
31398        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
31399            Ok(json!("second"))
31400        });
31401        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
31402            panic!("duplicate replaced the query adapter");
31403        };
31404        assert!(Arc::ptr_eq(&original, retained));
31405        worker.register_update("orders", "same", |_ctx, _input| async {
31406            Ok(json!("first"))
31407        });
31408        let original = Arc::clone(&worker.updates["orders"]["same"]);
31409        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
31410            Ok(AvroValue::Null)
31411        });
31412        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
31413    }
31414
31415    #[tokio::test]
31416    async fn duplicate_registration_fails_before_server_contact() {
31417        let server = MockWorkerServer::start();
31418        let client = Client::builder(server.base_url()).build().expect("client");
31419        let mut worker =
31420            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
31421        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31422        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
31423        let error = worker
31424            .run_once()
31425            .await
31426            .expect_err("ambiguous worker must not poll");
31427        assert!(
31428            error.to_string().contains("duplicate_registration"),
31429            "{error}"
31430        );
31431        assert!(server.requests.lock().expect("requests").is_empty());
31432    }
31433
31434    #[derive(Clone, Debug)]
31435    struct CapturedRequest {
31436        headers: String,
31437        method: String,
31438        path: String,
31439        authorization: Option<String>,
31440        namespace: Option<String>,
31441        worker_protocol: Option<String>,
31442        control_protocol: Option<String>,
31443        body: String,
31444        received_at: Instant,
31445    }
31446
31447    struct MockWorkerServer {
31448        addr: SocketAddr,
31449        stop: Arc<AtomicBool>,
31450        requests: Arc<Mutex<Vec<CapturedRequest>>>,
31451        thread: Option<thread::JoinHandle<()>>,
31452    }
31453
31454    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
31455
31456    #[derive(Clone, Copy, Default)]
31457    struct MockWorkerBehavior {
31458        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
31459        request_override: Option<RequestOverride>,
31460        /// Close the connection after reading the request, without any response.
31461        drop_request: Option<fn(&str, usize) -> bool>,
31462        storage_refusals: usize,
31463        storage_path: Option<&'static str>,
31464        storage_unavailable: bool,
31465        storage_mid_poll: bool,
31466        storage_activity: bool,
31467        storage_query: bool,
31468        storage_wrong_poll_id: bool,
31469        reject_query_protocol: bool,
31470        reject_query_completion: bool,
31471        waiting_query_worker: bool,
31472        decline_registration: bool,
31473        complete_named_signal: bool,
31474        poll_failures_per_path: usize,
31475        long_poll_capacity_responses_per_path: usize,
31476        heartbeat_failures: usize,
31477        heartbeat_failure_request: Option<usize>,
31478        delayed_heartbeat_request: Option<usize>,
31479        heartbeat_response_delay: Duration,
31480        concurrent_requests: bool,
31481        unauthorized_polls: bool,
31482        reject_registration: bool,
31483        reject_registration_protocol: bool,
31484        reject_deregistration: bool,
31485        reject_deregistration_protocol: bool,
31486        cancelled_activity: bool,
31487        draining_polls: bool,
31488        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
31489        workflow_completion_status: Option<&'static str>,
31490        workflow_completion_body: Option<&'static str>,
31491    }
31492
31493    impl MockWorkerServer {
31494        fn start() -> Self {
31495            Self::start_with_behavior(MockWorkerBehavior::default())
31496        }
31497
31498        fn reject_query_protocol() -> Self {
31499            Self::start_with_behavior(MockWorkerBehavior {
31500                reject_query_protocol: true,
31501                ..MockWorkerBehavior::default()
31502            })
31503        }
31504
31505        fn reject_query_completion() -> Self {
31506            Self::start_with_behavior(MockWorkerBehavior {
31507                reject_query_completion: true,
31508                ..MockWorkerBehavior::default()
31509            })
31510        }
31511
31512        fn waiting_query_worker() -> Self {
31513            Self::start_with_behavior(MockWorkerBehavior {
31514                waiting_query_worker: true,
31515                complete_named_signal: true,
31516                ..MockWorkerBehavior::default()
31517            })
31518        }
31519
31520        fn transient_worker_failures() -> Self {
31521            Self::start_with_behavior(MockWorkerBehavior {
31522                poll_failures_per_path: 1,
31523                heartbeat_failures: 1,
31524                ..MockWorkerBehavior::default()
31525            })
31526        }
31527
31528        fn consecutive_poll_failures(count: usize) -> Self {
31529            Self::start_with_behavior(MockWorkerBehavior {
31530                poll_failures_per_path: count,
31531                ..MockWorkerBehavior::default()
31532            })
31533        }
31534
31535        fn capacity_limited_activity_poll() -> Self {
31536            Self::start_with_behavior(MockWorkerBehavior {
31537                long_poll_capacity_responses_per_path: 1,
31538                ..MockWorkerBehavior::default()
31539            })
31540        }
31541
31542        fn delayed_heartbeat_worker() -> Self {
31543            Self::start_with_behavior(MockWorkerBehavior {
31544                waiting_query_worker: true,
31545                delayed_heartbeat_request: Some(2),
31546                heartbeat_response_delay: Duration::from_millis(1_500),
31547                concurrent_requests: true,
31548                cancelled_activity: true,
31549                ..MockWorkerBehavior::default()
31550            })
31551        }
31552
31553        fn heartbeat_retry_worker() -> Self {
31554            Self::start_with_behavior(MockWorkerBehavior {
31555                waiting_query_worker: true,
31556                heartbeat_failure_request: Some(2),
31557                concurrent_requests: true,
31558                ..MockWorkerBehavior::default()
31559            })
31560        }
31561
31562        fn unavailable_polls() -> Self {
31563            Self::start_with_behavior(MockWorkerBehavior {
31564                poll_failures_per_path: usize::MAX,
31565                ..MockWorkerBehavior::default()
31566            })
31567        }
31568
31569        fn unauthorized_polls() -> Self {
31570            Self::start_with_behavior(MockWorkerBehavior {
31571                unauthorized_polls: true,
31572                ..MockWorkerBehavior::default()
31573            })
31574        }
31575
31576        fn rejected_registration() -> Self {
31577            Self::start_with_behavior(MockWorkerBehavior {
31578                reject_registration: true,
31579                ..MockWorkerBehavior::default()
31580            })
31581        }
31582
31583        fn rejected_registration_protocol() -> Self {
31584            Self::start_with_behavior(MockWorkerBehavior {
31585                reject_registration_protocol: true,
31586                ..MockWorkerBehavior::default()
31587            })
31588        }
31589
31590        fn declined_registration() -> Self {
31591            Self::start_with_behavior(MockWorkerBehavior {
31592                decline_registration: true,
31593                ..MockWorkerBehavior::default()
31594            })
31595        }
31596
31597        fn rejected_deregistration() -> Self {
31598            Self::start_with_behavior(MockWorkerBehavior {
31599                reject_deregistration: true,
31600                ..MockWorkerBehavior::default()
31601            })
31602        }
31603
31604        fn rejected_deregistration_protocol() -> Self {
31605            Self::start_with_behavior(MockWorkerBehavior {
31606                reject_deregistration_protocol: true,
31607                ..MockWorkerBehavior::default()
31608            })
31609        }
31610
31611        fn unauthorized_polls_and_rejected_deregistration() -> Self {
31612            Self::start_with_behavior(MockWorkerBehavior {
31613                unauthorized_polls: true,
31614                reject_deregistration: true,
31615                ..MockWorkerBehavior::default()
31616            })
31617        }
31618
31619        fn cancelled_activity() -> Self {
31620            Self::start_with_behavior(MockWorkerBehavior {
31621                cancelled_activity: true,
31622                ..MockWorkerBehavior::default()
31623            })
31624        }
31625
31626        fn draining_polls() -> Self {
31627            Self::start_with_behavior(MockWorkerBehavior {
31628                draining_polls: true,
31629                ..MockWorkerBehavior::default()
31630            })
31631        }
31632
31633        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
31634            Self::start_with_behavior(MockWorkerBehavior {
31635                invalid_task_payload_codec: Some(codec),
31636                ..MockWorkerBehavior::default()
31637            })
31638        }
31639
31640        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
31641            Self::start_with_behavior(MockWorkerBehavior {
31642                workflow_completion_status: Some(status),
31643                workflow_completion_body: Some(body),
31644                ..MockWorkerBehavior::default()
31645            })
31646        }
31647
31648        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
31649            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
31650            listener
31651                .set_nonblocking(true)
31652                .expect("configure mock listener");
31653            let addr = listener.local_addr().expect("mock server address");
31654            let stop = Arc::new(AtomicBool::new(false));
31655            let server_stop = Arc::clone(&stop);
31656            let requests = Arc::new(Mutex::new(Vec::new()));
31657            let server_requests = Arc::clone(&requests);
31658            let thread = thread::spawn(move || {
31659                let mut request_threads = Vec::new();
31660                while !server_stop.load(Ordering::SeqCst) {
31661                    match listener.accept() {
31662                        Ok((mut stream, _)) => {
31663                            if behavior.concurrent_requests {
31664                                let requests = Arc::clone(&server_requests);
31665                                request_threads.push(thread::spawn(move || {
31666                                    handle_mock_worker_request(&mut stream, &requests, behavior)
31667                                }));
31668                            } else {
31669                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
31670                            }
31671                        }
31672                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
31673                            let mut index = 0;
31674                            while index < request_threads.len() {
31675                                if request_threads[index].is_finished() {
31676                                    request_threads
31677                                        .swap_remove(index)
31678                                        .join()
31679                                        .expect("join mock request");
31680                                } else {
31681                                    index += 1;
31682                                }
31683                            }
31684                            thread::sleep(Duration::from_millis(5));
31685                        }
31686                        Err(_) => break,
31687                    }
31688                }
31689                for request_thread in request_threads {
31690                    request_thread.join().expect("join mock request");
31691                }
31692            });
31693
31694            Self {
31695                addr,
31696                stop,
31697                requests,
31698                thread: Some(thread),
31699            }
31700        }
31701
31702        fn base_url(&self) -> String {
31703            format!("http://{}", self.addr)
31704        }
31705
31706        fn worker_protocol_for(&self, path: &str) -> Option<String> {
31707            self.requests
31708                .lock()
31709                .expect("captured requests")
31710                .iter()
31711                .find(|request| request.path == path)
31712                .and_then(|request| request.worker_protocol.clone())
31713        }
31714
31715        fn control_protocol_for(&self, path: &str) -> Option<String> {
31716            self.requests
31717                .lock()
31718                .expect("captured requests")
31719                .iter()
31720                .find(|request| request.path == path)
31721                .and_then(|request| request.control_protocol.clone())
31722        }
31723
31724        fn method_for(&self, path: &str) -> Option<String> {
31725            self.requests
31726                .lock()
31727                .expect("captured requests")
31728                .iter()
31729                .find(|request| request.path == path)
31730                .map(|request| request.method.clone())
31731        }
31732
31733        fn authorization_for(&self, path: &str) -> Option<String> {
31734            self.requests
31735                .lock()
31736                .expect("captured requests")
31737                .iter()
31738                .find(|request| request.path == path)
31739                .and_then(|request| request.authorization.clone())
31740        }
31741
31742        fn namespace_for(&self, path: &str) -> Option<String> {
31743            self.requests
31744                .lock()
31745                .expect("captured requests")
31746                .iter()
31747                .find(|request| request.path == path)
31748                .and_then(|request| request.namespace.clone())
31749        }
31750
31751        fn request_count(&self, path: &str) -> usize {
31752            self.requests
31753                .lock()
31754                .expect("captured requests")
31755                .iter()
31756                .filter(|request| request.path == path)
31757                .count()
31758        }
31759
31760        fn captured_paths(&self) -> Vec<String> {
31761            self.requests
31762                .lock()
31763                .expect("captured requests")
31764                .iter()
31765                .map(|request| request.path.clone())
31766                .collect()
31767        }
31768
31769        fn request_times(&self, path: &str) -> Vec<Instant> {
31770            self.requests
31771                .lock()
31772                .expect("captured requests")
31773                .iter()
31774                .filter(|request| request.path == path)
31775                .map(|request| request.received_at)
31776                .collect()
31777        }
31778
31779        fn request_body(&self, path: &str) -> Value {
31780            let requests = self.requests.lock().expect("captured requests");
31781            let body = &requests
31782                .iter()
31783                .find(|request| request.path == path)
31784                .unwrap_or_else(|| panic!("missing request for {path}"))
31785                .body;
31786            serde_json::from_str(body).unwrap_or_else(|error| {
31787                panic!("invalid JSON request body for {path}: {error}: {body:?}")
31788            })
31789        }
31790
31791        fn request_bodies(&self, path: &str) -> Vec<Value> {
31792            self.requests
31793                .lock()
31794                .expect("captured requests")
31795                .iter()
31796                .filter(|request| request.path == path)
31797                .map(|request| {
31798                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
31799                        panic!(
31800                            "invalid JSON request body for {path}: {error}: {:?}",
31801                            request.body
31802                        )
31803                    })
31804                })
31805                .collect()
31806        }
31807
31808        fn request_headers(&self, path: &str) -> Vec<String> {
31809            self.requests
31810                .lock()
31811                .expect("captured requests")
31812                .iter()
31813                .filter(|request| request.path == path)
31814                .map(|request| request.headers.clone())
31815                .collect()
31816        }
31817    }
31818
31819    impl Drop for MockWorkerServer {
31820        fn drop(&mut self) {
31821            self.stop.store(true, Ordering::SeqCst);
31822            let _ = TcpStream::connect(self.addr);
31823
31824            if let Some(thread) = self.thread.take() {
31825                thread.join().expect("join mock server");
31826            }
31827        }
31828    }
31829
31830    #[test]
31831    fn closed_mock_connection_is_not_a_worker_request() {
31832        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
31833        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
31834        let (mut stream, _) = listener.accept().unwrap();
31835        drop(client);
31836        let requests = Arc::new(Mutex::new(Vec::new()));
31837        handle_mock_worker_request(
31838            &mut stream,
31839            &requests,
31840            MockWorkerBehavior {
31841                request_override: Some(|_, _, _| {
31842                    panic!("closed connection cannot invoke an HTTP handler")
31843                }),
31844                ..MockWorkerBehavior::default()
31845            },
31846        );
31847        assert!(requests.lock().unwrap().is_empty());
31848    }
31849
31850    fn handle_mock_worker_request(
31851        stream: &mut TcpStream,
31852        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
31853        behavior: MockWorkerBehavior,
31854    ) {
31855        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
31856        let mut buffer = [0_u8; 8192];
31857        let mut request = Vec::new();
31858
31859        loop {
31860            match stream.read(&mut buffer) {
31861                Ok(0) => break,
31862                Ok(read) => {
31863                    request.extend_from_slice(&buffer[..read]);
31864                    if mock_request_is_complete(&request) {
31865                        break;
31866                    }
31867                }
31868                Err(error)
31869                    if matches!(
31870                        error.kind(),
31871                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
31872                    ) =>
31873                {
31874                    break;
31875                }
31876                Err(_) => return,
31877            }
31878        }
31879
31880        if !mock_request_is_complete(&request) {
31881            return;
31882        }
31883
31884        let request = String::from_utf8_lossy(&request);
31885        let body = request
31886            .split_once("\r\n\r\n")
31887            .map(|(_, body)| body)
31888            .unwrap_or_default();
31889        let path = request
31890            .lines()
31891            .next()
31892            .and_then(|line| line.split_whitespace().nth(1))
31893            .unwrap_or_default();
31894        let method = request
31895            .lines()
31896            .next()
31897            .and_then(|line| line.split_whitespace().next())
31898            .unwrap_or_default();
31899        let authorization = request.lines().find_map(|line| {
31900            let (name, value) = line.split_once(':')?;
31901            name.eq_ignore_ascii_case("Authorization")
31902                .then(|| value.trim().to_string())
31903        });
31904        let namespace = request.lines().find_map(|line| {
31905            let (name, value) = line.split_once(':')?;
31906            name.eq_ignore_ascii_case("X-Namespace")
31907                .then(|| value.trim().to_string())
31908        });
31909        let worker_protocol = request.lines().find_map(|line| {
31910            let (name, value) = line.split_once(':')?;
31911            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
31912                .then(|| value.trim().to_string())
31913        });
31914        let control_protocol = request.lines().find_map(|line| {
31915            let (name, value) = line.split_once(':')?;
31916            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
31917                .then(|| value.trim().to_string())
31918        });
31919        let request_number = {
31920            let mut requests = requests.lock().expect("captured requests");
31921            requests.push(CapturedRequest {
31922                headers: request
31923                    .split_once("\r\n\r\n")
31924                    .map_or("", |(headers, _)| headers)
31925                    .to_owned(),
31926                method: method.to_string(),
31927                path: path.to_string(),
31928                authorization,
31929                namespace,
31930                worker_protocol: worker_protocol.clone(),
31931                control_protocol,
31932                body: body.to_string(),
31933                received_at: Instant::now(),
31934            });
31935            requests
31936                .iter()
31937                .filter(|request| request.path == path)
31938                .count()
31939        };
31940
31941        if behavior
31942            .drop_request
31943            .is_some_and(|dropped| dropped(path, request_number))
31944        {
31945            return;
31946        }
31947        if let Some(response) = behavior
31948            .request_override
31949            .and_then(|handler| handler(path, body, request_number))
31950        {
31951            write_mock_response(stream, response.0, &response.1);
31952            return;
31953        }
31954        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
31955            write_mock_response(stream, response.0, &response.1);
31956            return;
31957        }
31958        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
31959            return;
31960        }
31961        let pressure_path = behavior
31962            .storage_path
31963            .is_some_and(|part| path.contains(part));
31964        let prior_failures = if path.ends_with("/poll") {
31965            behavior.poll_failures_per_path
31966        } else {
31967            0
31968        };
31969        if pressure_path
31970            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
31971        {
31972            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
31973            let poll_id = path
31974                .ends_with("/poll")
31975                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
31976            let mut refusal = storage_refusal(
31977                poll_id,
31978                behavior.storage_unavailable,
31979                behavior.storage_mid_poll,
31980            );
31981            if behavior.storage_wrong_poll_id {
31982                refusal["poll_request_id"] = json!("wrong-poll");
31983            }
31984            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
31985            return;
31986        }
31987        if path.contains("/storage-task/")
31988            || path.contains("/storage-activity/")
31989            || path.contains("/storage-query/")
31990        {
31991            write_mock_response(stream, "200 OK", "{}");
31992            return;
31993        }
31994        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
31995            write_mock_response(stream, "200 OK", &json!({"task":{
31996                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
31997                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
31998                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
31999                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32000                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
32001            }}).to_string());
32002            return;
32003        }
32004        if behavior.storage_activity
32005            && path == "/api/worker/activity-tasks/poll"
32006            && request_number == 1
32007        {
32008            write_mock_response(stream, "200 OK", &json!({"task":{
32009                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
32010                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32011                "attempt_number":7, "lease_owner":"storage-worker"
32012            }}).to_string());
32013            return;
32014        }
32015
32016        if path == "/api/worker/register" {
32017            if behavior.reject_registration_protocol {
32018                write_mock_response(
32019                    stream,
32020                    "400 Bad Request",
32021                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
32022                );
32023                return;
32024            }
32025            if behavior.reject_registration {
32026                write_mock_response(
32027                    stream,
32028                    "503 Service Unavailable",
32029                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
32030                );
32031                return;
32032            }
32033        }
32034
32035        if path.starts_with("/api/worker/registrations/") {
32036            if behavior.reject_deregistration_protocol {
32037                write_mock_response(
32038                    stream,
32039                    "400 Bad Request",
32040                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
32041                );
32042            } else if behavior.reject_deregistration {
32043                write_mock_response(
32044                    stream,
32045                    "403 Forbidden",
32046                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
32047                );
32048            } else {
32049                write_mock_response(
32050                    stream,
32051                    "200 OK",
32052                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
32053                );
32054            }
32055            return;
32056        }
32057
32058        let is_poll = matches!(
32059            path,
32060            "/api/worker/workflow-tasks/poll"
32061                | "/api/worker/activity-tasks/poll"
32062                | "/api/worker/query-tasks/poll"
32063        );
32064        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
32065            write_mock_response(
32066                stream,
32067                "429 Too Many Requests",
32068                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
32069            );
32070            return;
32071        }
32072        if is_poll && request_number <= behavior.poll_failures_per_path {
32073            return;
32074        }
32075        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
32076            return;
32077        }
32078        if path == "/api/worker/heartbeat"
32079            && behavior.heartbeat_failure_request == Some(request_number)
32080        {
32081            return;
32082        }
32083        if path == "/api/worker/heartbeat"
32084            && behavior.delayed_heartbeat_request == Some(request_number)
32085        {
32086            thread::sleep(behavior.heartbeat_response_delay);
32087        }
32088        if behavior.unauthorized_polls && is_poll {
32089            write_mock_response(
32090                stream,
32091                "401 Unauthorized",
32092                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
32093            );
32094            return;
32095        }
32096        if behavior.draining_polls && is_poll {
32097            write_mock_response(
32098                stream,
32099                "409 Conflict",
32100                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
32101            );
32102            return;
32103        }
32104
32105        if let Some(codec_case) = behavior.invalid_task_payload_codec {
32106            if is_poll && request_number == 1 {
32107                let mut task = match path {
32108                    "/api/worker/workflow-tasks/poll" => json!({
32109                        "task_id": "codec-workflow",
32110                        "workflow_type": "codec.workflow",
32111                        "payload_codec": DEFAULT_CODEC,
32112                        "workflow_task_attempt": 1,
32113                        "lease_owner": "codec-worker"
32114                    }),
32115                    "/api/worker/activity-tasks/poll" => json!({
32116                        "task_id": "codec-activity",
32117                        "activity_attempt_id": "codec-activity-attempt",
32118                        "activity_type": "codec.activity",
32119                        "payload_codec": DEFAULT_CODEC,
32120                        "attempt_number": 1,
32121                        "lease_owner": "codec-worker"
32122                    }),
32123                    "/api/worker/query-tasks/poll" => json!({
32124                        "query_task_id": "codec-query",
32125                        "query_task_attempt": 1,
32126                        "workflow_type": "codec.workflow",
32127                        "query_name": "known",
32128                        "payload_codec": DEFAULT_CODEC,
32129                        "lease_owner": "codec-worker"
32130                    }),
32131                    _ => unreachable!("is_poll limits task codec probe paths"),
32132                };
32133                codec_case.apply(&mut task);
32134                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
32135                return;
32136            }
32137
32138            if matches!(
32139                path,
32140                "/api/worker/workflow-tasks/codec-workflow/fail"
32141                    | "/api/worker/activity-tasks/codec-activity/fail"
32142                    | "/api/worker/query-tasks/codec-query/fail"
32143            ) {
32144                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
32145                return;
32146            }
32147        }
32148
32149        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
32150            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
32151            let body = format!(
32152                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
32153            );
32154            write_mock_response(stream, "400 Bad Request", &body);
32155            return;
32156        }
32157
32158        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
32159        {
32160            write_mock_response(
32161                stream,
32162                "409 Conflict",
32163                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
32164            );
32165            return;
32166        }
32167
32168        if behavior.workflow_completion_status.is_some()
32169            && path == "/api/worker/workflow-tasks/poll"
32170            && request_number == 1
32171        {
32172            write_mock_response(
32173                stream,
32174                "200 OK",
32175                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"}}"#,
32176            );
32177            return;
32178        }
32179
32180        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
32181            if let (Some(status), Some(body)) = (
32182                behavior.workflow_completion_status,
32183                behavior.workflow_completion_body,
32184            ) {
32185                write_mock_response(stream, status, body);
32186                return;
32187            }
32188        }
32189
32190        if behavior.waiting_query_worker {
32191            if behavior.complete_named_signal
32192                && path == "/api/worker/workflow-tasks/poll"
32193                && request_number == 1
32194            {
32195                let body = json!({
32196                    "task": {
32197                        "task_id": "snapshot-open",
32198                        "workflow_id": "snapshot-1",
32199                        "run_id": "snapshot-run-1",
32200                        "workflow_type": "snapshot",
32201                        "payload_codec": DEFAULT_CODEC,
32202                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32203                            .expect("Avro workflow arguments"),
32204                        "history_events": [],
32205                        "workflow_task_attempt": 1,
32206                        "lease_owner": "rust-snapshot-worker"
32207                    }
32208                })
32209                .to_string();
32210                write_mock_response(stream, "200 OK", &body);
32211                return;
32212            }
32213
32214            let signal_request = request_number - usize::from(behavior.complete_named_signal);
32215            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
32216            if path == "/api/worker/workflow-tasks/poll"
32217                && signal_request >= 1
32218                && signal_request <= signal_request_limit
32219            {
32220                let finish = behavior.complete_named_signal && signal_request == 3;
32221                let amounts = if signal_request == 1 {
32222                    vec![3]
32223                } else {
32224                    vec![3, 5]
32225                };
32226                let task_id = if signal_request == 1 {
32227                    "snapshot-wait-3"
32228                } else if finish {
32229                    "snapshot-finish"
32230                } else {
32231                    "snapshot-wait-5"
32232                };
32233                let mut history_events = std::iter::once(json!({
32234                    "event_type": "SignalWaitOpened",
32235                    "payload": {"sequence": 1, "signal_name": "finish"}
32236                }))
32237                .chain(amounts.iter().enumerate().map(|(index, amount)| {
32238                    json!({
32239                        "event_type": "SignalReceived",
32240                        "payload": {
32241                            "signal_id": format!("increment-{amount}"),
32242                            "signal_name": "increment",
32243                            "workflow_sequence": index + 2,
32244                            "payload_codec": DEFAULT_CODEC,
32245                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32246                                .expect("Avro signal envelope")
32247                        }
32248                    })
32249                }))
32250                .collect::<Vec<_>>();
32251                let (resume_id, resume_name, resume_arguments) = if finish {
32252                    history_events.push(json!({
32253                        "event_type": "SignalReceived",
32254                        "payload": {
32255                            "signal_id": "finish",
32256                            "signal_name": "finish",
32257                            "workflow_sequence": 4,
32258                            "payload_codec": DEFAULT_CODEC,
32259                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32260                                .expect("Avro finish signal envelope")
32261                        }
32262                    }));
32263                    (
32264                        "finish".to_string(),
32265                        "finish".to_string(),
32266                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
32267                            .expect("Avro finish resume signal"),
32268                    )
32269                } else {
32270                    let amount = amounts.last().expect("amount");
32271                    (
32272                        format!("increment-{amount}"),
32273                        "increment".to_string(),
32274                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32275                            .expect("Avro increment resume signal"),
32276                    )
32277                };
32278                let body = json!({
32279                    "task": {
32280                        "task_id": task_id,
32281                        "workflow_id": "snapshot-1",
32282                        "run_id": "snapshot-run-1",
32283                        "workflow_type": "snapshot",
32284                        "payload_codec": DEFAULT_CODEC,
32285                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32286                            .expect("Avro workflow arguments"),
32287                        "history_events": history_events,
32288                        "workflow_task_attempt": 1,
32289                        "workflow_signal_id": resume_id,
32290                        "signal_name": resume_name,
32291                        "signal_arguments": resume_arguments,
32292                        "lease_owner": "rust-snapshot-worker"
32293                    }
32294                })
32295                .to_string();
32296                write_mock_response(stream, "200 OK", &body);
32297                return;
32298            }
32299
32300            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
32301                let history_events = [3, 5]
32302                    .into_iter()
32303                    .enumerate()
32304                    .map(|(index, amount)| {
32305                        json!({
32306                            "event_type": "SignalReceived",
32307                            "payload": {
32308                                "signal_id": format!("increment-{amount}"),
32309                                "signal_name": "increment",
32310                                "workflow_sequence": index + 2,
32311                                "payload_codec": DEFAULT_CODEC,
32312                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32313                                    .expect("Avro query signal envelope")
32314                            }
32315                        })
32316                    })
32317                    .collect::<Vec<_>>();
32318                let body = json!({
32319                    "task": {
32320                        "query_task_id": "snapshot-current",
32321                        "query_task_attempt": 1,
32322                        "lease_owner": "rust-snapshot-worker",
32323                        "workflow_id": "snapshot-1",
32324                        "run_id": "snapshot-run-1",
32325                        "workflow_type": "snapshot",
32326                        "query_name": "current",
32327                        "payload_codec": DEFAULT_CODEC,
32328                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32329                            .expect("Avro workflow arguments"),
32330                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32331                            .expect("Avro query arguments"),
32332                        "history_events": history_events,
32333                        "run_status": "waiting"
32334                    }
32335                })
32336                .to_string();
32337                write_mock_response(stream, "200 OK", &body);
32338                return;
32339            }
32340
32341            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
32342                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
32343            {
32344                write_mock_response(
32345                    stream,
32346                    "200 OK",
32347                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
32348                );
32349                return;
32350            }
32351
32352            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
32353                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
32354                return;
32355            }
32356
32357            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
32358                write_mock_response(
32359                    stream,
32360                    "200 OK",
32361                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
32362                );
32363                return;
32364            }
32365
32366            if path == "/api/worker/query-tasks/snapshot-current/complete" {
32367                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
32368                return;
32369            }
32370        }
32371
32372        if matches!(
32373            path,
32374            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
32375        ) {
32376            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32377                .expect("typed mock result");
32378            let body = json!({
32379                "result": typed_fidelity_probe().into_json().expect("result projection"),
32380                "result_envelope": result,
32381            })
32382            .to_string();
32383            write_mock_response(stream, "200 OK", &body);
32384            return;
32385        }
32386
32387        if path == "/api/workflows/typed-1" {
32388            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32389                .expect("typed mock result");
32390            let body = json!({
32391                "workflow_id": "typed-1",
32392                "run_id": "run-typed-1",
32393                "workflow_type": "typed.echo",
32394                "status": "completed",
32395                "output": typed_fidelity_probe().into_json().expect("output projection"),
32396                "output_envelope": result,
32397            })
32398            .to_string();
32399            write_mock_response(stream, "200 OK", &body);
32400            return;
32401        }
32402
32403        let (status, body) = match path {
32404            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
32405            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
32406            "/api/workflows" => (
32407                "201 Created",
32408                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
32409            ),
32410            "/api/worker/register" if behavior.decline_registration => (
32411                "200 OK",
32412                r#"{"worker_id":"declined-worker","registered":false}"#,
32413            ),
32414            "/api/worker/register" if behavior.waiting_query_worker => (
32415                "200 OK",
32416                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
32417            ),
32418            "/api/worker/register" => (
32419                "200 OK",
32420                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
32421            ),
32422            "/api/worker/heartbeat" => ("200 OK", "{}"),
32423            "/api/worker/activity-tasks/poll"
32424                if behavior.cancelled_activity && request_number == 1 =>
32425            {
32426                (
32427                    "200 OK",
32428                    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"}}"#,
32429                )
32430            }
32431            "/api/worker/activity-tasks/poll"
32432                if behavior.long_poll_capacity_responses_per_path > 0
32433                    && request_number
32434                        == behavior
32435                            .long_poll_capacity_responses_per_path
32436                            .saturating_add(1) =>
32437            {
32438                (
32439                    "200 OK",
32440                    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"}}"#,
32441                )
32442            }
32443            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
32444                ("200 OK", r#"{"task":null}"#)
32445            }
32446            "/api/worker/query-tasks/poll"
32447                if behavior.reject_query_completion && request_number == 1 =>
32448            {
32449                (
32450                    "200 OK",
32451                    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"}}"#,
32452                )
32453            }
32454            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
32455            "/api/worker/query-tasks/query-capture/complete"
32456            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
32457            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
32458                "200 OK",
32459                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
32460            ),
32461            "/api/worker/activity-tasks/activity-cancel/complete" => (
32462                "409 Conflict",
32463                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
32464            ),
32465            "/api/worker/activity-tasks/activity-typed/complete"
32466            | "/api/worker/activity-tasks/activity-typed/fail"
32467            | "/api/worker/activity-tasks/capacity-activity/complete"
32468            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
32469            "/api/workflows/counter-1/query/current" => (
32470                "200 OK",
32471                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
32472            ),
32473            "/api/workflows/counter-1/query/missing" => (
32474                "404 Not Found",
32475                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
32476            ),
32477            "/api/workflows/wf-lifecycle/cancel" => (
32478                "200 OK",
32479                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
32480            ),
32481            "/api/workflows/wf-lifecycle/terminate" => (
32482                "200 OK",
32483                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
32484            ),
32485            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
32486                "200 OK",
32487                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
32488            ),
32489            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
32490                "200 OK",
32491                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
32492            ),
32493            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
32494                "202 Accepted",
32495                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
32496            ),
32497            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
32498                "200 OK",
32499                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}"#,
32500            ),
32501            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
32502                "409 Conflict",
32503                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
32504            ),
32505            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
32506            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
32507                "409 Conflict",
32508                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
32509            ),
32510            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
32511                "200 OK",
32512                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"}]}}"#,
32513            ),
32514            "/api/workflows/wf-cancelled" => (
32515                "200 OK",
32516                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
32517            ),
32518            "/api/workflows/wf-terminated" => (
32519                "200 OK",
32520                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
32521            ),
32522            "/api/workflows/wf-timed-out" => (
32523                "200 OK",
32524                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
32525            ),
32526            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
32527                "200 OK",
32528                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
32529            ),
32530            "/api/workflows/wf-selected" => (
32531                "200 OK",
32532                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
32533            ),
32534            "/api/workflows/wf-selected/runs/run-selected" => (
32535                "200 OK",
32536                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
32537            ),
32538            _ => ("404 Not Found", r#"{"message":"not found"}"#),
32539        };
32540        write_mock_response(stream, status, body);
32541    }
32542
32543    fn mock_request_is_complete(request: &[u8]) -> bool {
32544        let Some(header_end) = request
32545            .windows(4)
32546            .position(|window| window == b"\r\n\r\n")
32547            .map(|position| position + 4)
32548        else {
32549            return false;
32550        };
32551        let headers = String::from_utf8_lossy(&request[..header_end]);
32552        let content_length = headers.lines().find_map(|line| {
32553            let (name, value) = line.split_once(':')?;
32554            name.eq_ignore_ascii_case("content-length")
32555                .then(|| value.trim().parse::<usize>().ok())
32556                .flatten()
32557        });
32558
32559        request.len() >= header_end + content_length.unwrap_or(0)
32560    }
32561
32562    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
32563        let response = format!(
32564            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
32565            body.len()
32566        );
32567
32568        let _ = stream.write_all(response.as_bytes());
32569        let _ = stream.flush();
32570    }
32571
32572    fn typed_activity_failure_server(
32573        path: &str,
32574        _body: &str,
32575        request_number: usize,
32576    ) -> Option<(&'static str, String)> {
32577        match path {
32578            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32579                "200 OK",
32580                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(),
32581            )),
32582            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
32583            _ => None,
32584        }
32585    }
32586
32587    #[tokio::test]
32588    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
32589        for non_retryable in [false, true] {
32590            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32591                request_override: Some(typed_activity_failure_server),
32592                ..MockWorkerBehavior::default()
32593            });
32594            let client = Client::builder(server.base_url()).build().unwrap();
32595            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
32596            worker.register_activity("typed.failure", move |_, _| async move {
32597                Err(ActivityError::new("PaymentDeclined", "card declined")
32598                    .non_retryable(non_retryable)
32599                    .into())
32600            });
32601            assert_eq!(worker.run_once().await.unwrap(), 1);
32602            assert_eq!(
32603                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
32604                json!({
32605                    "activity_attempt_id": "typed-attempt",
32606                    "lease_owner": "typed-worker",
32607                    "failure": {"type": "PaymentDeclined", "message": "card declined",
32608                                "non_retryable": non_retryable}
32609                })
32610            );
32611        }
32612    }
32613
32614    fn activity_completion_backend_recovery(
32615        path: &str,
32616        _body: &str,
32617        request_number: usize,
32618    ) -> Option<(&'static str, String)> {
32619        match path {
32620            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32621                "200 OK",
32622                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(),
32623            )),
32624            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
32625                "503 Service Unavailable",
32626                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(),
32627            )),
32628            "/api/worker/activity-tasks/recover-activity/complete" => Some((
32629                "200 OK",
32630                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32631            )),
32632            _ => None,
32633        }
32634    }
32635
32636    fn workflow_completion_backend_recovery(
32637        path: &str,
32638        _body: &str,
32639        request_number: usize,
32640    ) -> Option<(&'static str, String)> {
32641        match path {
32642            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
32643                "200 OK",
32644                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
32645            )),
32646            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
32647                "503 Service Unavailable",
32648                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(),
32649            )),
32650            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
32651                "200 OK",
32652                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32653            )),
32654            _ => None,
32655        }
32656    }
32657
32658    fn workflow_completion_lock_pressure(
32659        path: &str,
32660        body: &str,
32661        request_number: usize,
32662    ) -> Option<(&'static str, String)> {
32663        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
32664            return Some((
32665                "503 Service Unavailable",
32666                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32667                    "outcome":"deferred", "recorded":false, "retryable":true,
32668                    "retry_after_seconds":1, "task_id":"recover-workflow",
32669                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
32670                    "backend":{"driver":"sqlite", "lock_pressure":true}})
32671                .to_string(),
32672            ));
32673        }
32674        workflow_completion_backend_recovery(path, body, request_number)
32675    }
32676
32677    fn workflow_completion_lock_pressure_forever(
32678        path: &str,
32679        body: &str,
32680        request_number: usize,
32681    ) -> Option<(&'static str, String)> {
32682        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
32683            return workflow_completion_lock_pressure(path, body, 1);
32684        }
32685        workflow_completion_lock_pressure(path, body, request_number)
32686    }
32687
32688    fn workflow_completion_lock_pressure_then_expired(
32689        path: &str,
32690        body: &str,
32691        request_number: usize,
32692    ) -> Option<(&'static str, String)> {
32693        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32694            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
32695                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
32696        }
32697        workflow_completion_lock_pressure(path, body, request_number)
32698    }
32699
32700    fn workflow_completion_lock_pressure_then_slow(
32701        path: &str,
32702        body: &str,
32703        request_number: usize,
32704    ) -> Option<(&'static str, String)> {
32705        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32706            thread::sleep(Duration::from_secs(2));
32707        }
32708        workflow_completion_lock_pressure(path, body, request_number)
32709    }
32710
32711    fn workflow_completion_pressure_then_backend_loss(
32712        path: &str,
32713        body: &str,
32714        request_number: usize,
32715    ) -> Option<(&'static str, String)> {
32716        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32717            return Some((
32718                "503 Service Unavailable",
32719                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
32720                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
32721                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
32722                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
32723                .to_string(),
32724            ));
32725        }
32726        workflow_completion_lock_pressure(path, body, request_number)
32727    }
32728
32729    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
32730        let client = Client::builder(server.base_url())
32731            .timeout(Duration::from_secs(4))
32732            .build()
32733            .unwrap();
32734        let mut worker = Worker::new(client, "recover-queue")
32735            .worker_id("recover-worker")
32736            .poll_timeout(Duration::from_millis(10));
32737        worker.register_workflow("recover.workflow", move |_ctx, _args| {
32738            let calls = Arc::clone(&calls);
32739            async move {
32740                calls.fetch_add(1, Ordering::SeqCst);
32741                Ok(json!("done"))
32742            }
32743        });
32744        worker
32745    }
32746
32747    #[tokio::test]
32748    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
32749        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32750            request_override: Some(workflow_completion_lock_pressure_forever),
32751            ..MockWorkerBehavior::default()
32752        });
32753        let calls = Arc::new(AtomicUsize::new(0));
32754        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32755            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32756        worker
32757            .client
32758            .worker_storage_admission
32759            .as_mut()
32760            .unwrap()
32761            .workflow_completion_retry_deadline =
32762            Some(tokio::time::Instant::now() + Duration::from_millis(250));
32763        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
32764            .await
32765            .unwrap();
32766        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32767        assert_eq!(calls.load(Ordering::SeqCst), 1);
32768        assert_eq!(
32769            server
32770                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32771                .len(),
32772            1
32773        );
32774    }
32775
32776    #[tokio::test]
32777    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
32778        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32779            request_override: Some(workflow_completion_lock_pressure_then_slow),
32780            ..MockWorkerBehavior::default()
32781        });
32782        let calls = Arc::new(AtomicUsize::new(0));
32783        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32784            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32785        let start = tokio::time::Instant::now();
32786        worker
32787            .client
32788            .worker_storage_admission
32789            .as_mut()
32790            .unwrap()
32791            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32792        assert!(matches!(
32793            worker.poll_workflow_once().await,
32794            Err(Error::Timeout)
32795        ));
32796        assert!(start.elapsed() < Duration::from_secs(2));
32797        assert_eq!(calls.load(Ordering::SeqCst), 1);
32798        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32799        assert_eq!(bodies.len(), 2);
32800        assert_eq!(bodies[0], bodies[1]);
32801    }
32802
32803    #[tokio::test]
32804    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
32805        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32806            request_override: Some(workflow_completion_pressure_then_backend_loss),
32807            ..MockWorkerBehavior::default()
32808        });
32809        let calls = Arc::new(AtomicUsize::new(0));
32810        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32811            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32812        let start = tokio::time::Instant::now();
32813        worker
32814            .client
32815            .worker_storage_admission
32816            .as_mut()
32817            .unwrap()
32818            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32819        let result = worker.poll_workflow_once().await;
32820        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32821        assert!(start.elapsed() < Duration::from_secs(2));
32822        assert_eq!(calls.load(Ordering::SeqCst), 1);
32823        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32824        assert_eq!(bodies.len(), 2);
32825        assert_eq!(bodies[0], bodies[1]);
32826    }
32827
32828    #[tokio::test]
32829    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
32830        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32831            request_override: Some(workflow_completion_lock_pressure_forever),
32832            ..MockWorkerBehavior::default()
32833        });
32834        let calls = Arc::new(AtomicUsize::new(0));
32835        let stop = Arc::new(AtomicBool::new(false));
32836        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
32837            .with_storage_admission(Arc::clone(&stop));
32838        let shutdown = async {
32839            while server
32840                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32841                .is_empty()
32842            {
32843                tokio::time::sleep(Duration::from_millis(10)).await;
32844            }
32845            stop.store(true, Ordering::SeqCst);
32846        };
32847        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
32848            tokio::join!(worker.poll_workflow_once(), shutdown)
32849        })
32850        .await
32851        .unwrap();
32852        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32853        assert_eq!(calls.load(Ordering::SeqCst), 1);
32854        assert_eq!(
32855            server
32856                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32857                .len(),
32858            1
32859        );
32860    }
32861
32862    #[tokio::test]
32863    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
32864        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32865            request_override: Some(workflow_completion_lock_pressure_then_expired),
32866            ..MockWorkerBehavior::default()
32867        });
32868        let calls = Arc::new(AtomicUsize::new(0));
32869        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
32870        let result = worker.run_once().await;
32871        assert!(
32872            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
32873        );
32874        assert_eq!(calls.load(Ordering::SeqCst), 1);
32875        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32876        assert_eq!(bodies.len(), 2);
32877        assert_eq!(bodies[0], bodies[1]);
32878        assert!(server
32879            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
32880            .is_empty());
32881    }
32882
32883    #[tokio::test]
32884    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
32885        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32886            request_override: Some(workflow_completion_lock_pressure),
32887            ..MockWorkerBehavior::default()
32888        });
32889        let client = Client::builder(server.base_url())
32890            .timeout(Duration::from_secs(2))
32891            .build()
32892            .unwrap();
32893        let calls = Arc::new(AtomicUsize::new(0));
32894        let mut worker = Worker::new(client, "recover-queue")
32895            .worker_id("recover-worker")
32896            .recover_transient_outages(true)
32897            .poll_timeout(Duration::from_millis(10))
32898            .retry_policy(WorkerRetryPolicy {
32899                max_retries: 1,
32900                initial_backoff: Duration::from_millis(10),
32901                max_backoff: Duration::from_millis(10),
32902            });
32903        worker.register_workflow("recover.workflow", {
32904            let calls = Arc::clone(&calls);
32905            move |_ctx, _args| {
32906                let calls = Arc::clone(&calls);
32907                async move {
32908                    calls.fetch_add(1, Ordering::SeqCst);
32909                    Ok(json!("done"))
32910                }
32911            }
32912        });
32913        let start = tokio::time::Instant::now();
32914        assert_eq!(worker.run_once().await.unwrap(), 1);
32915        assert!(start.elapsed() >= Duration::from_secs(1));
32916        assert_eq!(calls.load(Ordering::SeqCst), 1);
32917        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32918        assert_eq!(bodies.len(), 2);
32919        assert_eq!(bodies[0], bodies[1]);
32920    }
32921
32922    #[test]
32923    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
32924        let path = "/worker/workflow-tasks/recover-workflow/complete";
32925        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
32926        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32927            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
32928            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
32929            "backend":{"driver":"sqlite", "lock_pressure":true}});
32930        let error = |body: Value| Error::Http {
32931            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
32932            body: body.to_string(),
32933        };
32934        assert_eq!(
32935            worker_deferred_workflow_completion_retry_after(
32936                &error(response.clone()),
32937                path,
32938                Some(&request)
32939            ),
32940            Some(Duration::from_secs(1))
32941        );
32942        for (field, value) in [
32943            ("reason", json!("backend_unavailable")),
32944            ("operation", json!("complete_activity_task")),
32945            ("task_id", json!("other-task")),
32946            ("lease_owner", json!("other-owner")),
32947            ("workflow_task_attempt", json!(4)),
32948            ("recorded", json!(true)),
32949            ("recorded", Value::Null),
32950            ("recorded", json!("false")),
32951            ("retryable", json!(false)),
32952            ("retry_after_seconds", json!(0)),
32953            ("retry_after_seconds", json!(-1)),
32954            ("retry_after_seconds", json!(1.0)),
32955            ("retry_after_seconds", json!("1")),
32956            ("retry_after_seconds", json!(6)),
32957            ("backend", json!({"lock_pressure":false})),
32958        ] {
32959            let mut invalid = response.clone();
32960            invalid[field] = value;
32961            assert_eq!(
32962                worker_deferred_workflow_completion_retry_after(
32963                    &error(invalid),
32964                    path,
32965                    Some(&request)
32966                ),
32967                None,
32968                "invalid {field}"
32969            );
32970        }
32971        for field in [
32972            "reason",
32973            "operation",
32974            "task_id",
32975            "lease_owner",
32976            "workflow_task_attempt",
32977            "recorded",
32978            "retryable",
32979            "retry_after_seconds",
32980            "backend",
32981        ] {
32982            let mut missing = response.clone();
32983            missing.as_object_mut().unwrap().remove(field);
32984            assert_eq!(
32985                worker_deferred_workflow_completion_retry_after(
32986                    &error(missing),
32987                    path,
32988                    Some(&request)
32989                ),
32990                None,
32991                "missing {field}"
32992            );
32993        }
32994        assert_eq!(
32995            worker_deferred_workflow_completion_retry_after(
32996                &error(response.clone()),
32997                "/worker/activity-tasks/recover-workflow/complete",
32998                Some(&request)
32999            ),
33000            None
33001        );
33002        assert_eq!(
33003            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
33004            None
33005        );
33006        let wrong_status = Error::Http {
33007            status: reqwest::StatusCode::CONFLICT,
33008            body: response.to_string(),
33009        };
33010        assert_eq!(
33011            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
33012            None
33013        );
33014    }
33015
33016    fn activity_completion_stale_after_backend_recovery(
33017        path: &str,
33018        body: &str,
33019        request_number: usize,
33020    ) -> Option<(&'static str, String)> {
33021        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
33022            return Some((
33023                "409 Conflict",
33024                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(),
33025            ));
33026        }
33027        activity_completion_backend_recovery(path, body, request_number)
33028    }
33029
33030    fn activity_completion_remains_unavailable(
33031        path: &str,
33032        body: &str,
33033        request_number: usize,
33034    ) -> Option<(&'static str, String)> {
33035        if path == "/api/worker/activity-tasks/recover-activity/complete" {
33036            return activity_completion_backend_recovery(path, body, 1);
33037        }
33038        activity_completion_backend_recovery(path, body, request_number)
33039    }
33040
33041    #[tokio::test]
33042    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
33043        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33044            request_override: Some(activity_completion_backend_recovery),
33045            ..MockWorkerBehavior::default()
33046        });
33047        let client = Client::builder(server.base_url())
33048            .timeout(Duration::from_secs(2))
33049            .build()
33050            .expect("client");
33051        let handler_calls = Arc::new(AtomicUsize::new(0));
33052        let mut worker = Worker::new(client, "recover-queue")
33053            .worker_id("recover-worker")
33054            .poll_timeout(Duration::from_millis(10));
33055        worker.register_activity("recover.activity", {
33056            let handler_calls = Arc::clone(&handler_calls);
33057            move |_ctx, _args| {
33058                let handler_calls = Arc::clone(&handler_calls);
33059                async move {
33060                    handler_calls.fetch_add(1, Ordering::SeqCst);
33061                    Ok(json!("done"))
33062                }
33063            }
33064        });
33065
33066        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33067        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33068        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33069        assert_eq!(bodies.len(), 2);
33070        assert_eq!(bodies[0], bodies[1]);
33071    }
33072
33073    #[tokio::test]
33074    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
33075        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33076            request_override: Some(workflow_completion_backend_recovery),
33077            ..MockWorkerBehavior::default()
33078        });
33079        let client = Client::builder(server.base_url())
33080            .timeout(Duration::from_secs(2))
33081            .build()
33082            .expect("client");
33083        let handler_calls = Arc::new(AtomicUsize::new(0));
33084        let mut worker = Worker::new(client, "recover-queue")
33085            .worker_id("recover-worker")
33086            .poll_timeout(Duration::from_millis(10));
33087        worker.register_workflow("recover.workflow", {
33088            let handler_calls = Arc::clone(&handler_calls);
33089            move |_ctx, _args| {
33090                let handler_calls = Arc::clone(&handler_calls);
33091                async move {
33092                    handler_calls.fetch_add(1, Ordering::SeqCst);
33093                    Ok(json!("done"))
33094                }
33095            }
33096        });
33097
33098        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
33099        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33100        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
33101        assert_eq!(bodies.len(), 2);
33102        assert_eq!(bodies[0], bodies[1]);
33103    }
33104
33105    #[tokio::test]
33106    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
33107        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33108            request_override: Some(activity_completion_stale_after_backend_recovery),
33109            ..MockWorkerBehavior::default()
33110        });
33111        let client = Client::builder(server.base_url())
33112            .timeout(Duration::from_secs(2))
33113            .build()
33114            .expect("client");
33115        let handler_calls = Arc::new(AtomicUsize::new(0));
33116        let mut worker = Worker::new(client, "recover-queue")
33117            .worker_id("recover-worker")
33118            .poll_timeout(Duration::from_millis(10));
33119        worker.register_activity("recover.activity", {
33120            let handler_calls = Arc::clone(&handler_calls);
33121            move |_ctx, _args| {
33122                let handler_calls = Arc::clone(&handler_calls);
33123                async move {
33124                    handler_calls.fetch_add(1, Ordering::SeqCst);
33125                    Ok(json!("done"))
33126                }
33127            }
33128        });
33129
33130        assert_eq!(
33131            worker
33132                .run_once()
33133                .await
33134                .expect("authoritative stale outcome"),
33135            1
33136        );
33137        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33138        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33139        assert_eq!(bodies.len(), 2);
33140        assert_eq!(bodies[0], bodies[1]);
33141    }
33142
33143    #[test]
33144    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
33145        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
33146        let response = json!({
33147            "reason":"backend_unavailable", "operation":"complete_activity_task",
33148            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
33149            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
33150            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
33151        });
33152        let path = "/worker/activity-tasks/recover-activity/complete";
33153        let error = |body: Value| Error::Http {
33154            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33155            body: body.to_string(),
33156        };
33157        assert_eq!(
33158            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
33159            Some(Duration::from_secs(1))
33160        );
33161
33162        for (field, invalid) in [
33163            ("operation", json!("poll_activity_task")),
33164            ("outcome", json!("rejected")),
33165            ("worker_id", json!("another-worker")),
33166            ("task_queue", json!("recover-queue")),
33167            ("retryable", json!(false)),
33168            ("retry_after_seconds", json!(0)),
33169            ("task_id", json!("another-task")),
33170            ("lease_owner", json!("another-worker")),
33171            ("activity_attempt_id", json!("another-attempt")),
33172        ] {
33173            let mut invalid_response = response.clone();
33174            invalid_response[field] = invalid;
33175            assert_eq!(
33176                worker_fenced_completion_retry_after(
33177                    &error(invalid_response),
33178                    path,
33179                    Some(&request)
33180                ),
33181                None,
33182                "must not retry mismatched {field}"
33183            );
33184        }
33185        assert_eq!(
33186            worker_fenced_completion_retry_after(&error(response), path, None),
33187            None
33188        );
33189    }
33190
33191    #[tokio::test]
33192    async fn shutdown_interrupts_fenced_completion_backend_wait() {
33193        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33194            request_override: Some(activity_completion_remains_unavailable),
33195            ..MockWorkerBehavior::default()
33196        });
33197        let client = Client::builder(server.base_url())
33198            .timeout(Duration::from_secs(2))
33199            .build()
33200            .expect("client");
33201        let stop = Arc::new(AtomicBool::new(false));
33202        let worker = Worker::new(client, "recover-queue")
33203            .worker_id("recover-worker")
33204            .with_storage_admission(Arc::clone(&stop));
33205        let completion = tokio::spawn(async move {
33206            worker
33207                .client
33208                .complete_activity_task(
33209                    "recover-activity",
33210                    "recover-attempt",
33211                    "recover-worker",
33212                    json!("done"),
33213                    DEFAULT_CODEC,
33214                )
33215                .await
33216        });
33217        let path = "/api/worker/activity-tasks/recover-activity/complete";
33218        tokio::time::timeout(Duration::from_secs(2), async {
33219            while server.request_count(path) == 0 {
33220                tokio::time::sleep(Duration::from_millis(10)).await;
33221            }
33222        })
33223        .await
33224        .expect("first completion request");
33225        stop.store(true, Ordering::SeqCst);
33226        let error = tokio::time::timeout(Duration::from_secs(1), completion)
33227            .await
33228            .expect("shutdown must interrupt retry wait")
33229            .expect("completion task")
33230            .expect_err("backend is still unavailable");
33231        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
33232        assert_eq!(server.request_count(path), 1);
33233    }
33234}