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;
14pub mod pagination;
15mod query_authority;
16mod runtime_payloads;
17mod runtime_uploads;
18mod sticky_worker;
19mod sticky_workflow_cache;
20#[cfg(feature = "telemetry")]
21pub mod telemetry;
22pub mod testing;
23pub use pagination::{
24    PaginationError, WorkflowHistoryIterator, WorkflowHistoryOptions, WorkflowHistoryPage,
25    WorkflowIterator, WorkflowListOptions, WorkflowListPage, WorkflowSummary,
26};
27mod tls;
28mod worker_capacity;
29mod worker_session;
30mod workflow_hydration;
31
32pub use activity_error::ActivityError;
33pub use cancellation_context::{
34    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
35};
36pub use cancellation_scope::CancellationScopeOpenReceipt;
37#[doc(hidden)]
38pub use cancellation_scope_history::{
39    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
40};
41#[doc(hidden)]
42pub use cancellation_scope_replay::CancellationScopeRequested;
43
44pub use cooperative_cancellation::{
45    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
46    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
47    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
48    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
49};
50
51use std::{
52    any::{type_name, Any, TypeId},
53    collections::{BTreeMap, BTreeSet, HashMap},
54    future::Future,
55    io::{self, Read},
56    pin::Pin,
57    sync::{
58        atomic::{AtomicBool, Ordering},
59        Arc, Mutex, OnceLock,
60    },
61    task::{Context as TaskContext, Poll},
62    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
63};
64
65use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
66use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
67use chrono::DateTime;
68use futures_util::{future::OptionFuture, task::noop_waker_ref};
69pub use local_activity::LocalActivityOptions;
70use serde::{
71    de::DeserializeOwned,
72    ser::{SerializeMap, SerializeSeq},
73    Deserialize, Deserializer, Serialize, Serializer,
74};
75pub use serde_json::{json, Value};
76use sha2::{Digest, Sha256};
77pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
78use thiserror::Error;
79pub use uuid::Uuid;
80pub use worker_session::{WorkerSession, WorkerSessionOptions};
81
82pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
83pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
84
85/// Select the worker request protocol without enabling optional capabilities.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87#[non_exhaustive]
88pub enum WorkerProtocolVersion {
89    /// Compatibility with Servers that implement only worker protocol 1.19.
90    V119,
91    /// The default worker protocol.
92    #[default]
93    V120,
94}
95
96impl WorkerProtocolVersion {
97    fn as_str(self) -> &'static str {
98        match self {
99            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
100            Self::V120 => WORKER_PROTOCOL_VERSION,
101        }
102    }
103}
104const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
105/// First additive worker protocol that defines portable worker-affinity features.
106pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
107pub const CONTROL_PLANE_VERSION: &str = "2";
108pub const DEFAULT_CODEC: &str = "avro";
109pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
110/// Worker-registration capability for authored condition-wait occurrence identity.
111pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
112    "condition_wait_occurrence_identity";
113/// Worker-registration capability for portable memo upserts.
114pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
115/// Worker-registration capability for server-routed read-only queries.
116pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
117/// Worker-registration capability for canonical typed search attributes.
118pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
119/// Worker-registration capability for synchronous workflow updates.
120pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
121/// Worker-registration capability for durable named input streams.
122pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
123/// Worker-registration capability for persisted first-completion selection.
124pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
125pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
126pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
127pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
128pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
129pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
130/// First additive worker protocol that defines query-task transport.
131pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
132/// First additive worker protocol that defines typed search-attribute upserts.
133pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
134/// First additive worker protocol that defines portable memo upserts.
135pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
136/// First additive worker protocol that preserves declared search-attribute types.
137pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
138/// First additive worker protocol that defines external durable condition waits.
139pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
140/// First additive worker protocol that preserves authored condition-wait occurrences.
141pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
142/// First additive worker protocol that defines durable selection groups.
143pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
144
145pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
146    let Some((major, minor)) = version.split_once('.') else {
147        return false;
148    };
149    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
150}
151
152fn validate_user_signal_name(signal_name: &str) -> Result<()> {
153    if signal_name == MESSAGE_STREAM_SIGNAL {
154        return Err(Error::Codec(format!(
155            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
156        )));
157    }
158    Ok(())
159}
160
161const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
162const MAX_REQUEST_ID_CHARACTERS: usize = 255;
163
164/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
165fn validate_request_id(request_id: &str) -> Result<()> {
166    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
167        return Err(Error::Codec(format!(
168            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
169        )));
170    }
171    Ok(())
172}
173
174fn generated_request_id(command: &str) -> String {
175    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
176}
177
178/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
179fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
180    if receipt.is_null() {
181        return json!({ "request_id": request_id });
182    }
183    if let Some(receipt) = receipt.as_object_mut() {
184        receipt
185            .entry("request_id")
186            .or_insert_with(|| Value::String(request_id.to_string()));
187    }
188    receipt
189}
190
191const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
192const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
193    "Workflow task waiting for scheduled history.";
194const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
195const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
196const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
197const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
198const MAX_MEMO_ENTRIES: usize = 100;
199const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
200const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
201
202const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
203    "lease_expired",
204    "query_task_not_found",
205    "query_task_not_leased",
206    "query_task_timed_out",
207    "query_deadline_unavailable",
208    "lease_owner_mismatch",
209    "query_task_attempt_mismatch",
210];
211
212/// Manifest for the default service-worker profile.
213///
214/// Inline local execution is enabled separately by [`Worker::local_activities`].
215/// Local execution, sessions and caching require explicit Worker configuration.
216pub fn portable_worker_affinity_capability_manifest() -> Value {
217    json!({
218        "local_activities": {
219            "supported": false,
220            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
221            "reason": "rust_worker_does_not_execute_record_local_activity",
222        },
223        "worker_sessions": {
224            "supported": false,
225            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
226            "reason": "rust_worker_has_no_typed_session_lifecycle",
227        },
228        "sticky_execution": {
229            "supported": false,
230            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
231            "reason": "rust_worker_uses_complete_durable_history_replay",
232        },
233    })
234}
235
236/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
237pub const AVRO_VALUE_SCHEMA_JSON: &str =
238    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
239pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
240pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
241const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
242
243static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
244static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
245    OnceLock::new();
246
247#[derive(Clone, Copy)]
248enum RequestProtocol {
249    ControlPlane,
250    DefaultWorker,
251    Worker(&'static str),
252}
253
254pub type Result<T> = std::result::Result<T, Error>;
255
256pub use nexus::{
257    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
258    NexusServiceOptions, NexusWaitFor,
259};
260
261#[derive(Debug, Error)]
262#[non_exhaustive]
263pub enum Error {
264    #[error("transport error: {0}")]
265    Transport(#[from] reqwest::Error),
266    #[error(
267        "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"
268    )]
269    InvalidBaseUrl,
270    #[error("invalid additional root certificates: {0}")]
271    InvalidRootCertificates(String),
272    #[error(transparent)]
273    Testing(#[from] testing::TestingError),
274    #[error(transparent)]
275    Pagination(#[from] pagination::PaginationError),
276    #[error("json error: {0}")]
277    Json(#[from] serde_json::Error),
278    #[error("http {status}: {body}")]
279    Http {
280        status: reqwest::StatusCode,
281        body: String,
282    },
283    #[error("codec error: {0}")]
284    Codec(String),
285    #[error(transparent)]
286    QueryFailed(QueryFailure),
287    #[error(transparent)]
288    Protocol(ProtocolFailure),
289    #[error(transparent)]
290    NonDeterministicReplay(ReplayFailure),
291    #[error(transparent)]
292    ChildWorkflowFailed(ChildWorkflowFailure),
293    #[error(transparent)]
294    ActivityFailed(ActivityFailure),
295    #[error(transparent)]
296    ActivityError(#[from] ActivityError),
297    #[error(transparent)]
298    NexusOperationFailed(Box<NexusOperationFailure>),
299    #[error(transparent)]
300    ParallelFailed(ParallelFailure),
301    #[error(transparent)]
302    SagaCompensationFailed(SagaCompensationFailure),
303    #[error(transparent)]
304    InvalidParallelGroup(ParallelGroupError),
305    #[error(transparent)]
306    DurableOperationCancelled(DurableOperationCancelled),
307    #[error(transparent)]
308    WorkflowCancellationRequested(WorkflowCancellationRequested),
309    #[error(transparent)]
310    CooperativeCancellationRequested(CooperativeCancellationRequested),
311    #[error(transparent)]
312    CancellationScopeRequested(CancellationScopeRequested),
313    #[error(transparent)]
314    WorkflowCommandRejected(WorkflowCommandRejection),
315    #[error(transparent)]
316    WorkflowFailed(WorkflowTerminalOutcome),
317    #[error(transparent)]
318    WorkflowCancelled(WorkflowTerminalOutcome),
319    #[error(transparent)]
320    WorkflowTerminated(WorkflowTerminalOutcome),
321    #[error(transparent)]
322    WorkflowTimedOut(WorkflowTerminalOutcome),
323    #[error(transparent)]
324    ActivityTaskRejected(ActivityTaskRejection),
325    #[error("activity lease renewal unavailable: {0}")]
326    ActivityLeaseRenewalUnavailable(String),
327    #[error("workflow handler {0:?} is not registered")]
328    WorkflowNotRegistered(String),
329    #[error("activity handler {0:?} is not registered")]
330    ActivityNotRegistered(String),
331    #[error(
332        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
333    )]
334    HandlerType {
335        handler_kind: HandlerKind,
336        handler_name: String,
337        value_kind: HandlerValueKind,
338        rust_type: &'static str,
339        message: String,
340    },
341    #[error("workflow future yielded without emitting a durable command")]
342    WorkflowYieldedWithoutCommand,
343    #[error(
344        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
345    )]
346    MissingWorkflowCommandIdentity,
347    #[error("workflow state lock is poisoned")]
348    WorkflowStatePoisoned,
349    #[error("timer duration is too large for the worker protocol")]
350    TimerDurationOverflow,
351    #[error(transparent)]
352    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
353    #[error(transparent)]
354    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
355    #[error("operation timed out")]
356    Timeout,
357    #[error(
358        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
359    )]
360    MissingRoleCredentials {
361        role: &'static str,
362        opposite_role: &'static str,
363    },
364    #[error("worker loop error: {0}")]
365    WorkerLoop(String),
366    #[error(
367        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
368    )]
369    UnsupportedUpdateValidators { workflow_type: String },
370    #[error("{primary}; worker deregistration also failed: {deregistration}")]
371    WorkerShutdown {
372        primary: Box<Error>,
373        deregistration: Box<Error>,
374    },
375    #[error("invalid child workflow options: {0}")]
376    InvalidChildWorkflowOptions(String),
377    #[error("invalid workflow memo update: {0}")]
378    InvalidMemoUpdate(String),
379    #[error(
380        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
381    )]
382    WorkflowMemoUpdatesUnavailable,
383    #[error("cooperative cancellation is unavailable: {0}")]
384    CooperativeCancellationUnavailable(String),
385    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
386    CancellationScopeExecutionUnavailable,
387    #[error("invalid cooperative cancellation: {0}")]
388    InvalidCooperativeCancellation(String),
389    #[error("activity execution no longer owns its claim: {0}")]
390    ActivityExecutionAbandoned(String),
391    #[error(transparent)]
392    InvalidActivityOptions(ActivityOptionsError),
393    #[error(transparent)]
394    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
395    #[doc(hidden)]
396    #[error("workflow requested continue as new")]
397    ContinueAsNew(ContinueAsNewRequest),
398}
399
400impl Error {
401    /// The caller command key echoed by the Server in a refusal body.
402    ///
403    /// Signals and updates send their key as the `request_id` body field, and a
404    /// Server refusal such as `request_id_conflict` echoes it. Transport failures
405    /// and refusals without an echoed key return `None`: keep the key you passed
406    /// to a `*_with_request_id` method, or obtained from
407    /// [`Client::generate_signal_request_id`] or
408    /// [`Client::generate_update_request_id`], to retry the same logical command
409    /// after an uncertain outcome.
410    pub fn request_id(&self) -> Option<String> {
411        self.refusal_body()?
412            .get("request_id")
413            .and_then(Value::as_str)
414            .filter(|request_id| !request_id.is_empty())
415            .map(str::to_string)
416    }
417
418    /// Whether the Server refused a signal or update because its caller command
419    /// key is retained for a command with a different intent
420    /// (HTTP 409, `reason: "request_id_conflict"`).
421    pub fn is_request_id_conflict(&self) -> bool {
422        self.request_id_conflict().is_some()
423    }
424
425    /// The retained-command details of a `request_id_conflict` refusal.
426    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
427        let status = match self {
428            Self::Http { status, .. } => status.as_u16(),
429            Self::WorkflowCommandRejected(rejection) => rejection.status,
430            _ => return None,
431        };
432        request_id_conflict(status, self.refusal_body()?)
433    }
434
435    fn refusal_body(&self) -> Option<Value> {
436        match self {
437            Self::Http { body, .. } => serde_json::from_str(body).ok(),
438            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
439            _ => None,
440        }
441    }
442}
443
444/// A refused signal or update whose caller command key is already retained for
445/// a command with a different intent.
446///
447/// Nothing was admitted or recorded, and the key stays bound to the retained
448/// command. Send a new key for a different command, or repeat the retained
449/// command's exact intent to receive its receipt. `conflict` lists the
450/// mismatched intent parts among `name`, `arguments` and `target`.
451#[derive(Clone, Debug, PartialEq)]
452#[non_exhaustive]
453pub struct RequestIdConflict {
454    pub status: u16,
455    pub request_id: String,
456    pub message: String,
457    pub retained_command_id: Option<String>,
458    pub retained_command_type: Option<String>,
459    pub retained_outcome: Option<String>,
460    pub conflict: Vec<String>,
461    pub body: Value,
462}
463
464fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
465    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
466        return None;
467    }
468    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
469    Some(RequestIdConflict {
470        status,
471        request_id: string("request_id").unwrap_or_default(),
472        message: string("message")
473            .or_else(|| string("error"))
474            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
475        retained_command_id: string("retained_command_id"),
476        retained_command_type: string("retained_command_type"),
477        retained_outcome: string("retained_outcome"),
478        conflict: body
479            .get("conflict")
480            .and_then(Value::as_array)
481            .map(|parts| {
482                parts
483                    .iter()
484                    .filter_map(Value::as_str)
485                    .map(str::to_string)
486                    .collect()
487            })
488            .unwrap_or_default(),
489        body,
490    })
491}
492
493/// Handler namespaces checked independently within a Worker.
494#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
495pub enum RegistrationKind {
496    Workflow,
497    Activity,
498    Query,
499    Update,
500}
501
502impl std::fmt::Display for RegistrationKind {
503    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504        formatter.write_str(match self {
505            Self::Workflow => "workflow",
506            Self::Activity => "activity",
507            Self::Query => "query",
508            Self::Update => "update",
509        })
510    }
511}
512
513/// The authoring adapter and source location of a handler registration.
514#[derive(Clone, Debug, PartialEq, Eq)]
515pub struct HandlerRegistration {
516    pub method: &'static str,
517    pub handler_type: &'static str,
518    pub file: &'static str,
519    pub line: u32,
520    pub column: u32,
521}
522
523impl std::fmt::Display for HandlerRegistration {
524    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
525        write!(
526            formatter,
527            "{} at {}:{}:{} ({})",
528            self.method, self.file, self.line, self.column, self.handler_type
529        )
530    }
531}
532
533/// Ambiguous local configuration, rejected before contacting Server.
534#[derive(Clone, Debug, Error, PartialEq, Eq)]
535#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
536pub struct DuplicateRegistrationError {
537    pub handler_kind: RegistrationKind,
538    pub handler_name: String,
539    /// Query/update registrations are scoped to their owning workflow type.
540    pub workflow_type: Option<String>,
541    pub first_definition: HandlerRegistration,
542    pub second_definition: HandlerRegistration,
543}
544
545impl From<DuplicateRegistrationError> for Error {
546    fn from(error: DuplicateRegistrationError) -> Self {
547        Self::WorkerLoop(error.to_string())
548    }
549}
550
551/// Validation failure for a durable condition-wait definition.
552#[derive(Clone, Debug, Error, PartialEq, Eq)]
553pub enum ConditionWaitOptionsError {
554    #[error("condition_key must be non-empty")]
555    EmptyKey,
556    #[error("condition_definition_fingerprint must be non-empty")]
557    EmptyPredicateIdentity,
558    #[error("condition timeout is too large for the worker protocol")]
559    TimeoutOverflow,
560}
561
562/// Stable identity and optional durable timeout for a condition wait.
563///
564/// `predicate_identity` is recorded as the worker protocol's
565/// `condition_definition_fingerprint` and must change whenever predicate
566/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
567/// is written inline; it derives this identity from the predicate tokens.
568#[derive(Clone, Debug, PartialEq, Eq)]
569pub struct ConditionWaitOptions {
570    condition_key: String,
571    predicate_identity: String,
572    timeout: Option<Duration>,
573}
574
575impl ConditionWaitOptions {
576    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
577        Self {
578            condition_key: condition_key.into(),
579            predicate_identity: predicate_identity.into(),
580            timeout: None,
581        }
582    }
583
584    pub fn timeout(mut self, timeout: Duration) -> Self {
585        self.timeout = Some(timeout);
586        self
587    }
588
589    fn validate(
590        &self,
591    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
592        let condition_key = self.condition_key.trim();
593        if condition_key.is_empty() {
594            return Err(ConditionWaitOptionsError::EmptyKey);
595        }
596        let predicate_identity = self.predicate_identity.trim();
597        if predicate_identity.is_empty() {
598            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
599        }
600        let timeout_seconds = self
601            .timeout
602            .map(|timeout| {
603                timeout
604                    .as_secs()
605                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
606                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
607            })
608            .transpose()?;
609
610        Ok(ValidatedConditionWaitOptions {
611            condition_key: condition_key.to_string(),
612            predicate_identity: predicate_identity.to_string(),
613            timeout_seconds,
614        })
615    }
616}
617
618#[derive(Clone, Debug, PartialEq, Eq)]
619struct ValidatedConditionWaitOptions {
620    condition_key: String,
621    predicate_identity: String,
622    timeout_seconds: Option<u64>,
623}
624
625const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
626
627/// Unambiguous terminal result of a durable condition wait.
628#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
629#[serde(rename_all = "snake_case")]
630pub enum ConditionWaitResult {
631    Satisfied,
632    TimedOut,
633}
634
635impl ConditionWaitResult {
636    pub fn is_satisfied(self) -> bool {
637        self == Self::Satisfied
638    }
639
640    pub fn is_timed_out(self) -> bool {
641        self == Self::TimedOut
642    }
643}
644
645/// Build the stable condition definition identity used by [`wait_condition!`].
646#[doc(hidden)]
647pub fn __condition_definition_fingerprint(source: &str) -> String {
648    let mut digest = Sha256::new();
649    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
650    digest.update(source.as_bytes());
651    format!("sha256:{:x}", digest.finalize())
652}
653
654/// Create a durable condition wait whose predicate definition is fingerprinted
655/// from its inline Rust tokens.
656///
657/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
658/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
659#[macro_export]
660macro_rules! wait_condition {
661    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
662        $ctx.wait_condition(
663            $crate::ConditionWaitOptions::new(
664                $key,
665                $crate::__condition_definition_fingerprint(concat!(
666                    module_path!(),
667                    "\0",
668                    stringify!($predicate)
669                )),
670            )
671            .timeout($timeout),
672            $predicate,
673        )
674    }};
675    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
676        $ctx.wait_condition(
677            $crate::ConditionWaitOptions::new(
678                $key,
679                $crate::__condition_definition_fingerprint(concat!(
680                    module_path!(),
681                    "\0",
682                    stringify!($predicate)
683                )),
684            ),
685            $predicate,
686        )
687    }};
688}
689
690const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
691const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
692const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
693const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
694const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
695
696/// Validation failure for a typed workflow search-attribute update.
697#[derive(Clone, Debug, Error, PartialEq, Eq)]
698pub enum SearchAttributeUpdateError {
699    #[error("search-attribute update requires at least one attribute")]
700    Empty,
701    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
702    InvalidKey(String),
703    #[error("search-attribute update exceeds the limit of 100 attributes")]
704    TooManyAttributes,
705    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
706    ValueTooLong {
707        key: String,
708        kind: &'static str,
709        limit: usize,
710    },
711    #[error(
712        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
713    )]
714    EmptyString(String),
715    #[error("search attribute {0:?} has a non-finite float value")]
716    NonFiniteFloat(String),
717    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
718    InvalidDateTime(String),
719    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
720    PayloadTooLarge,
721}
722
723/// One public typed search-attribute value.
724#[derive(Clone, Debug, PartialEq)]
725pub enum SearchAttributeValue {
726    String(String),
727    Keyword(String),
728    KeywordList(Vec<String>),
729    Int(i64),
730    Float(f64),
731    Bool(bool),
732    DateTime(String),
733    Delete,
734}
735
736impl SearchAttributeValue {
737    fn type_name(&self) -> Option<&'static str> {
738        match self {
739            Self::String(_) => Some("string"),
740            Self::Keyword(_) => Some("keyword"),
741            Self::KeywordList(_) => Some("keyword_list"),
742            Self::Int(_) => Some("int"),
743            Self::Float(_) => Some("float"),
744            Self::Bool(_) => Some("bool"),
745            Self::DateTime(_) => Some("datetime"),
746            Self::Delete => None,
747        }
748    }
749
750    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
751        let normalize_string = |value: String, kind: &'static str, limit: usize| {
752            let value = value.trim().to_string();
753            if value.is_empty() {
754                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
755            }
756            if value.len() > limit {
757                return Err(SearchAttributeUpdateError::ValueTooLong {
758                    key: key.to_string(),
759                    kind,
760                    limit,
761                });
762            }
763            Ok(value)
764        };
765
766        match self {
767            Self::String(value) => Ok(Self::String(normalize_string(
768                value,
769                "string",
770                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
771            )?)),
772            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
773                value,
774                "keyword",
775                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
776            )?)),
777            Self::KeywordList(values) => {
778                let values = values
779                    .into_iter()
780                    .map(|value| {
781                        let value = value.trim().to_string();
782                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
783                            return Err(SearchAttributeUpdateError::ValueTooLong {
784                                key: key.to_string(),
785                                kind: "keyword-list entry",
786                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
787                            });
788                        }
789                        Ok(value)
790                    })
791                    .collect::<std::result::Result<Vec<_>, _>>()?;
792                Ok(Self::KeywordList(values))
793            }
794            Self::Float(value) if !value.is_finite() => {
795                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
796            }
797            Self::DateTime(value) => {
798                let value =
799                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
800                if DateTime::parse_from_rfc3339(&value).is_err() {
801                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
802                }
803                Ok(Self::DateTime(value))
804            }
805            value => Ok(value),
806        }
807    }
808
809    fn into_json(self) -> Value {
810        match self {
811            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
812                Value::String(value)
813            }
814            Self::KeywordList(values) => {
815                Value::Array(values.into_iter().map(Value::String).collect())
816            }
817            Self::Int(value) => json!(value),
818            Self::Float(value) => json!(value),
819            Self::Bool(value) => json!(value),
820            Self::Delete => Value::Null,
821        }
822    }
823}
824
825/// Validated typed workflow-side search-attribute mutation.
826#[derive(Clone, Debug, Default, PartialEq)]
827pub struct SearchAttributeUpdate {
828    attributes: BTreeMap<String, SearchAttributeValue>,
829}
830
831impl SearchAttributeUpdate {
832    pub fn new() -> Self {
833        Self::default()
834    }
835
836    pub fn set(
837        mut self,
838        key: impl Into<String>,
839        value: SearchAttributeValue,
840    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
841        let key = key.into();
842        validate_search_attribute_key(&key)?;
843        if !self.attributes.contains_key(&key)
844            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
845        {
846            return Err(SearchAttributeUpdateError::TooManyAttributes);
847        }
848        self.attributes.insert(key.clone(), value.normalized(&key)?);
849        self.validate_size()?;
850        Ok(self)
851    }
852
853    pub fn string(
854        self,
855        key: impl Into<String>,
856        value: impl Into<String>,
857    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
858        self.set(key, SearchAttributeValue::String(value.into()))
859    }
860
861    pub fn keyword(
862        self,
863        key: impl Into<String>,
864        value: impl Into<String>,
865    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
866        self.set(key, SearchAttributeValue::Keyword(value.into()))
867    }
868
869    pub fn keyword_list<I, V>(
870        self,
871        key: impl Into<String>,
872        values: I,
873    ) -> std::result::Result<Self, SearchAttributeUpdateError>
874    where
875        I: IntoIterator<Item = V>,
876        V: Into<String>,
877    {
878        self.set(
879            key,
880            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
881        )
882    }
883
884    pub fn int(
885        self,
886        key: impl Into<String>,
887        value: i64,
888    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
889        self.set(key, SearchAttributeValue::Int(value))
890    }
891
892    pub fn float(
893        self,
894        key: impl Into<String>,
895        value: f64,
896    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
897        self.set(key, SearchAttributeValue::Float(value))
898    }
899
900    pub fn bool(
901        self,
902        key: impl Into<String>,
903        value: bool,
904    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
905        self.set(key, SearchAttributeValue::Bool(value))
906    }
907
908    pub fn datetime(
909        self,
910        key: impl Into<String>,
911        value: impl Into<String>,
912    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
913        self.set(key, SearchAttributeValue::DateTime(value.into()))
914    }
915
916    pub fn delete(
917        self,
918        key: impl Into<String>,
919    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
920        self.set(key, SearchAttributeValue::Delete)
921    }
922
923    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
924        let (attributes, _) = self.clone().into_wire_parts();
925        if serde_json::to_vec(&attributes)
926            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
927            .unwrap_or(true)
928        {
929            return Err(SearchAttributeUpdateError::PayloadTooLarge);
930        }
931        Ok(())
932    }
933
934    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
935        let mut attributes = serde_json::Map::new();
936        let mut attribute_types = BTreeMap::new();
937        for (key, value) in self.attributes {
938            if let Some(type_name) = value.type_name() {
939                attribute_types.insert(key.clone(), type_name.to_string());
940            }
941            attributes.insert(key, value.into_json());
942        }
943        (Value::Object(attributes), attribute_types)
944    }
945
946    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
947        if self.attributes.is_empty() {
948            return Err(SearchAttributeUpdateError::Empty);
949        }
950        self.validate_size()
951    }
952}
953
954fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
955    let valid = !key.is_empty()
956        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
957        && key
958            .bytes()
959            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
960    if valid {
961        Ok(())
962    } else {
963        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
964    }
965}
966
967/// The registered handler family reported by [`Error::HandlerType`].
968#[derive(Clone, Copy, Debug, PartialEq, Eq)]
969pub enum HandlerKind {
970    Workflow,
971    Activity,
972}
973
974impl std::fmt::Display for HandlerKind {
975    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
976        formatter.write_str(match self {
977            Self::Workflow => "workflow",
978            Self::Activity => "activity",
979        })
980    }
981}
982
983/// Whether a typed handler failed to adapt its input or result.
984#[derive(Clone, Copy, Debug, PartialEq, Eq)]
985pub enum HandlerValueKind {
986    Input,
987    Result,
988}
989
990impl std::fmt::Display for HandlerValueKind {
991    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
992        formatter.write_str(match self {
993            Self::Input => "input",
994            Self::Result => "result",
995        })
996    }
997}
998
999/// The lifecycle command sent to a workflow execution.
1000#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1001pub enum WorkflowCommandKind {
1002    Cancel,
1003    Terminate,
1004}
1005
1006impl WorkflowCommandKind {
1007    fn as_str(self) -> &'static str {
1008        match self {
1009            Self::Cancel => "cancel",
1010            Self::Terminate => "terminate",
1011        }
1012    }
1013}
1014
1015/// Optional structured fields for a cancellation or termination request.
1016#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1017pub struct WorkflowCommandOptions {
1018    #[serde(skip_serializing_if = "Option::is_none")]
1019    pub reason: Option<String>,
1020    #[serde(skip_serializing_if = "Option::is_none")]
1021    pub request_id: Option<String>,
1022}
1023
1024/// Server-enforced timeout policy for a workflow start.
1025///
1026/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1027/// only bounds how long the caller waits. A server deadline produces a terminal
1028/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1029/// `run_timeout`.
1030#[derive(Clone, Debug, PartialEq, Eq)]
1031pub struct WorkflowStartOptions {
1032    pub execution_timeout_seconds: u64,
1033    pub run_timeout_seconds: u64,
1034}
1035
1036impl Default for WorkflowStartOptions {
1037    fn default() -> Self {
1038        Self {
1039            execution_timeout_seconds: 3600,
1040            run_timeout_seconds: 600,
1041        }
1042    }
1043}
1044
1045impl WorkflowStartOptions {
1046    pub fn new() -> Self {
1047        Self::default()
1048    }
1049
1050    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1051        self.execution_timeout_seconds = seconds;
1052        self
1053    }
1054
1055    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1056        self.run_timeout_seconds = seconds;
1057        self
1058    }
1059
1060    fn validate(&self) -> Result<()> {
1061        if self.execution_timeout_seconds == 0 {
1062            return Err(Error::Codec(
1063                "execution_timeout_seconds must be at least 1".to_string(),
1064            ));
1065        }
1066        if self.run_timeout_seconds == 0 {
1067            return Err(Error::Codec(
1068                "run_timeout_seconds must be at least 1".to_string(),
1069            ));
1070        }
1071        if self.run_timeout_seconds > self.execution_timeout_seconds {
1072            return Err(Error::Codec(
1073                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1074            ));
1075        }
1076
1077        Ok(())
1078    }
1079}
1080
1081/// Optional routing overrides for a continue-as-new transition.
1082///
1083/// Omitted values retain the current workflow type and task queue. Server-owned
1084/// instance metadata is not accepted here and is carried by the server.
1085#[derive(Clone, Debug, Default, PartialEq, Eq)]
1086pub struct ContinueAsNewOptions {
1087    pub workflow_type: Option<String>,
1088    pub task_queue: Option<String>,
1089}
1090
1091impl ContinueAsNewOptions {
1092    pub fn new() -> Self {
1093        Self::default()
1094    }
1095
1096    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1097        self.workflow_type = Some(workflow_type.into());
1098        self
1099    }
1100
1101    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1102        self.task_queue = Some(task_queue.into());
1103        self
1104    }
1105
1106    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1107        for (field, value) in [
1108            ("workflow_type", self.workflow_type.as_deref()),
1109            ("task_queue", self.task_queue.as_deref()),
1110        ] {
1111            if value.is_some_and(|value| value.trim().is_empty()) {
1112                return Err(ContinueAsNewOptionsError {
1113                    field,
1114                    message: format!("{field} must not be empty"),
1115                });
1116            }
1117        }
1118        Ok(())
1119    }
1120}
1121
1122/// A stable validation error raised before a continue-as-new command is emitted.
1123#[derive(Clone, Debug, Error, PartialEq, Eq)]
1124#[error("invalid continue-as-new option {field}: {message}")]
1125pub struct ContinueAsNewOptionsError {
1126    pub field: &'static str,
1127    pub message: String,
1128}
1129
1130/// Public history-budget information attached to the current workflow task.
1131#[derive(Clone, Debug, Default, PartialEq, Eq)]
1132pub struct WorkflowHistoryBudget {
1133    pub event_count: u64,
1134    pub size_bytes: Option<u64>,
1135    pub continue_as_new_recommended: bool,
1136    pub pressure: Option<String>,
1137}
1138
1139#[doc(hidden)]
1140#[derive(Clone, Debug)]
1141pub struct ContinueAsNewRequest {
1142    arguments: AvroValue,
1143    options: ContinueAsNewOptions,
1144}
1145
1146impl WorkflowCommandOptions {
1147    pub fn new() -> Self {
1148        Self::default()
1149    }
1150
1151    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1152        self.reason = Some(reason.into());
1153        self
1154    }
1155
1156    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1157        self.request_id = Some(request_id.into());
1158        self
1159    }
1160}
1161
1162/// The accepted, machine-readable result of a lifecycle command.
1163#[derive(Clone, Debug, PartialEq)]
1164pub struct WorkflowCommandResult {
1165    pub command: WorkflowCommandKind,
1166    pub workflow_id: String,
1167    pub run_id: Option<String>,
1168    pub outcome: Option<String>,
1169    pub reason: Option<String>,
1170    pub command_status: Option<String>,
1171    pub raw: Value,
1172}
1173
1174/// A new run continuing a failed run from its recorded activity boundary.
1175#[derive(Clone, Debug, PartialEq)]
1176pub struct WorkflowRedriveResult {
1177    pub workflow_id: String,
1178    pub source_run_id: String,
1179    pub run_id: String,
1180    pub resume_step_sequence: u64,
1181    pub raw: Value,
1182}
1183
1184/// A stable rejection returned by instance- or selected-run lifecycle commands.
1185#[derive(Clone, Debug, Error)]
1186#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1187pub struct WorkflowCommandRejection {
1188    pub command: WorkflowCommandKind,
1189    pub status: u16,
1190    pub reason: String,
1191    pub message: String,
1192    pub workflow_id: String,
1193    pub run_id: Option<String>,
1194    pub target_scope: Option<String>,
1195    pub body: Value,
1196}
1197
1198/// Stable terminal categories returned by [`WorkflowHandle::result`].
1199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1200pub enum WorkflowTerminalKind {
1201    Failed,
1202    Cancelled,
1203    Terminated,
1204    TimedOut,
1205}
1206
1207/// A typed terminal workflow outcome with durable identity and failure metadata.
1208///
1209/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1210/// of parsing its display representation. Fields remain `None` when an older
1211/// server did not publish that metadata.
1212#[derive(Clone, Debug, Error)]
1213#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1214pub struct WorkflowTerminalOutcome {
1215    pub kind: WorkflowTerminalKind,
1216    pub workflow_id: String,
1217    pub run_id: Option<String>,
1218    pub reason: String,
1219    pub failure_category: Option<String>,
1220    pub failure_id: Option<String>,
1221    pub exception_type: Option<String>,
1222    pub exception_class: Option<String>,
1223    pub non_retryable: Option<bool>,
1224    pub message: Option<String>,
1225    pub exception: Option<Value>,
1226    pub raw: Value,
1227}
1228
1229/// A worker-side activity settlement or heartbeat rejected by durable state.
1230#[derive(Clone, Debug, Error)]
1231#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1232pub struct ActivityTaskRejection {
1233    pub operation: String,
1234    pub status: u16,
1235    pub reason: String,
1236    pub task_id: String,
1237    pub activity_attempt_id: String,
1238    pub cancel_requested: bool,
1239    pub can_continue: Option<bool>,
1240    pub run_closed_reason: Option<String>,
1241    pub body: Value,
1242}
1243
1244/// Stable validation categories for [`ActivityOptions`].
1245#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1246pub enum ActivityOptionsErrorKind {
1247    EmptyTaskQueue,
1248    EmptyRetryPolicy,
1249    InvalidMaxAttempts,
1250    BackoffWithoutRetryBudget,
1251    TooManyBackoffIntervals,
1252    InvalidBackoffCoefficient,
1253    BackoffGenerationTooLarge,
1254    BackoffOverflow,
1255    EmptyNonRetryableErrorType,
1256    TimeoutNotPositive,
1257    MissingTotalTimeout,
1258    TimeoutOverflow,
1259    TimeoutOrder,
1260}
1261
1262/// A machine-readable activity-options validation failure.
1263#[derive(Clone, Debug, Error, PartialEq, Eq)]
1264#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1265pub struct ActivityOptionsError {
1266    pub kind: ActivityOptionsErrorKind,
1267    pub field: Option<&'static str>,
1268    pub message: String,
1269}
1270
1271impl ActivityOptionsError {
1272    fn new(
1273        kind: ActivityOptionsErrorKind,
1274        field: Option<&'static str>,
1275        message: impl Into<String>,
1276    ) -> Self {
1277        Self {
1278            kind,
1279            field,
1280            message: message.into(),
1281        }
1282    }
1283}
1284
1285/// Stable terminal categories returned when an awaited activity does not succeed.
1286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1287pub enum ActivityFailureKind {
1288    Failed,
1289    Cancelled,
1290    TimedOut,
1291}
1292
1293/// A stable, machine-readable terminal activity failure.
1294///
1295/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1296/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1297#[derive(Clone, Debug, Error, PartialEq)]
1298#[error("activity failed ({reason}): {message}")]
1299pub struct ActivityFailure {
1300    pub kind: ActivityFailureKind,
1301    pub reason: String,
1302    pub message: String,
1303    pub activity_execution_id: Option<String>,
1304    pub activity_attempt_id: Option<String>,
1305    pub activity_type: Option<String>,
1306    pub activity_class: Option<String>,
1307    pub attempt_number: Option<u64>,
1308    pub failure_id: Option<String>,
1309    pub failure_category: Option<String>,
1310    pub timeout_kind: Option<String>,
1311    pub non_retryable: bool,
1312    pub exception_type: Option<String>,
1313    pub exception_class: Option<String>,
1314    pub code: Option<Value>,
1315    pub exception: Option<Value>,
1316}
1317
1318/// Stable terminal categories returned when an awaited child does not succeed.
1319#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1320pub enum ChildWorkflowFailureKind {
1321    Failed,
1322    Cancelled,
1323    Terminated,
1324}
1325
1326/// A stable, machine-readable child workflow failure delivered to its parent.
1327///
1328/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1329/// of parsing the display message. Child and parent identifiers retain the
1330/// relationship recorded in durable history across worker restarts.
1331#[derive(Clone, Debug, Error)]
1332#[error("child workflow failed ({reason}): {message}")]
1333pub struct ChildWorkflowFailure {
1334    pub kind: ChildWorkflowFailureKind,
1335    pub reason: String,
1336    pub message: String,
1337    pub parent_workflow_id: Option<String>,
1338    pub parent_workflow_run_id: Option<String>,
1339    pub child_workflow_id: Option<String>,
1340    pub child_workflow_run_id: Option<String>,
1341    pub child_workflow_type: Option<String>,
1342    pub failure_id: Option<String>,
1343    pub failure_category: Option<String>,
1344    pub exception_type: Option<String>,
1345    pub exception_class: Option<String>,
1346    pub non_retryable: bool,
1347    pub code: Option<Value>,
1348    pub exception: Option<Value>,
1349}
1350
1351/// The identity of one durable workflow execution.
1352#[derive(Clone, Debug, PartialEq, Eq)]
1353pub struct WorkflowIdentity {
1354    pub workflow_id: Option<String>,
1355    pub run_id: Option<String>,
1356}
1357
1358/// A successful child result together with its durable parent-child identity.
1359#[derive(Clone, Debug, PartialEq)]
1360pub struct ChildWorkflowResult {
1361    pub parent: WorkflowIdentity,
1362    pub child: WorkflowIdentity,
1363    pub child_workflow_type: Option<String>,
1364    pub result: Value,
1365}
1366
1367/// Lossless successful child result for fixed Avro Value workflows.
1368#[derive(Clone, Debug, PartialEq)]
1369pub struct ChildWorkflowAvroResult {
1370    pub parent: WorkflowIdentity,
1371    pub child: WorkflowIdentity,
1372    pub child_workflow_type: Option<String>,
1373    pub result: AvroValue,
1374}
1375
1376/// Stable user-facing identity for one member of a durable selection group.
1377#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1378#[serde(untagged)]
1379pub enum SelectionKey {
1380    Index(usize),
1381    Name(String),
1382}
1383
1384impl From<usize> for SelectionKey {
1385    fn from(value: usize) -> Self {
1386        Self::Index(value)
1387    }
1388}
1389
1390impl From<String> for SelectionKey {
1391    fn from(value: String) -> Self {
1392        Self::Name(value)
1393    }
1394}
1395
1396impl From<&str> for SelectionKey {
1397    fn from(value: &str) -> Self {
1398        Self::Name(value.to_string())
1399    }
1400}
1401
1402/// Typed result of explicitly awaiting a cancelled non-winning operation.
1403#[derive(Clone, Debug, Error, PartialEq, Eq)]
1404#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1405pub struct DurableOperationCancelled {
1406    pub selection_group_id: String,
1407    pub member_key: SelectionKey,
1408    pub member_index: usize,
1409    pub operation_kind: String,
1410    pub operation_identity: String,
1411}
1412
1413/// Stable identity for one enclosing deterministic parallel group.
1414///
1415/// The same fields are attached to every ordinary activity, timer, or child
1416/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1417/// no Rust-specific wire command is introduced.
1418#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1419pub struct ParallelGroupMetadata {
1420    pub parallel_group_id: String,
1421    pub parallel_group_kind: String,
1422    pub parallel_group_base_sequence: u64,
1423    pub parallel_group_size: usize,
1424    pub parallel_group_index: usize,
1425    #[serde(default, skip_serializing_if = "Option::is_none")]
1426    pub parallel_group_mode: Option<String>,
1427    #[serde(default, skip_serializing_if = "Option::is_none")]
1428    pub selection_member_key: Option<SelectionKey>,
1429    #[serde(default, skip_serializing_if = "Option::is_none")]
1430    pub selection_member_index: Option<usize>,
1431    #[serde(default, skip_serializing_if = "Option::is_none")]
1432    pub selection_member_base_sequence: Option<u64>,
1433    #[serde(default, skip_serializing_if = "Option::is_none")]
1434    pub selection_member_size: Option<usize>,
1435    #[serde(default, skip_serializing_if = "Option::is_none")]
1436    pub selection_member_kind: Option<String>,
1437}
1438
1439/// One input-ordered result returned by [`WorkflowContext::parallel`].
1440#[derive(Clone, Debug, PartialEq)]
1441pub enum ParallelResult {
1442    Activity(Value),
1443    ChildWorkflow(ChildWorkflowResult),
1444    Timer,
1445    Signal(Vec<Value>),
1446    Condition(ConditionWaitResult),
1447    Group(Vec<ParallelResult>),
1448}
1449
1450/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1451#[derive(Clone, Debug, PartialEq)]
1452pub enum ParallelAvroResult {
1453    Activity(AvroValue),
1454    ChildWorkflow(ChildWorkflowAvroResult),
1455    Timer,
1456    Signal(Vec<AvroValue>),
1457    Condition(ConditionWaitResult),
1458    Group(Vec<ParallelAvroResult>),
1459}
1460
1461impl ParallelAvroResult {
1462    fn into_json_result(self) -> Result<ParallelResult> {
1463        match self {
1464            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1465            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1466                parent: result.parent,
1467                child: result.child,
1468                child_workflow_type: result.child_workflow_type,
1469                result: result.result.into_json()?,
1470            })),
1471            Self::Timer => Ok(ParallelResult::Timer),
1472            Self::Signal(values) => Ok(ParallelResult::Signal(
1473                values
1474                    .into_iter()
1475                    .map(AvroValue::into_json)
1476                    .collect::<Result<Vec<_>>>()?,
1477            )),
1478            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1479            Self::Group(results) => Ok(ParallelResult::Group(
1480                results
1481                    .into_iter()
1482                    .map(Self::into_json_result)
1483                    .collect::<Result<Vec<_>>>()?,
1484            )),
1485        }
1486    }
1487}
1488
1489/// One successful leaf retained when another parallel member failed.
1490#[derive(Clone, Debug, PartialEq)]
1491pub struct ParallelCompletion {
1492    pub member_path: Vec<usize>,
1493    pub result: ParallelResult,
1494}
1495
1496/// A deterministic join failed after some siblings had already completed.
1497///
1498/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1499/// error. `completed` is declaration ordered and contains only durable
1500/// successes observed in the same replay. Late sibling completions can add
1501/// entries on a later replay without changing `member_path` or the selected
1502/// positional failure.
1503#[derive(Debug, Error)]
1504#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1505pub struct ParallelFailure {
1506    pub group_id: String,
1507    pub member_path: Vec<usize>,
1508    pub group_path: Vec<ParallelGroupMetadata>,
1509    pub completed: Vec<ParallelCompletion>,
1510    #[source]
1511    pub cause: Box<Error>,
1512}
1513
1514/// Stable validation error returned before an invalid group emits commands.
1515#[derive(Clone, Debug, Error, PartialEq, Eq)]
1516#[error("invalid deterministic parallel group ({reason}): {message}")]
1517pub struct ParallelGroupError {
1518    pub reason: &'static str,
1519    pub member_path: Vec<usize>,
1520    pub message: String,
1521}
1522
1523/// Cooperative workflow cancellation observed at an author-controlled point.
1524#[derive(Clone, Debug, Error, PartialEq, Eq)]
1525#[error("workflow cancellation was requested")]
1526pub struct WorkflowCancellationRequested;
1527
1528/// A forward saga failure followed by a terminal compensation failure.
1529#[derive(Debug, Error)]
1530#[error(
1531    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1532)]
1533pub struct SagaCompensationFailure {
1534    pub initiating_failure: Box<Error>,
1535    pub compensation_failure: Box<Error>,
1536    pub compensation_activity_type: String,
1537    pub compensation_registration_order: usize,
1538}
1539
1540/// Server behavior when a parent closes while its child is still open.
1541#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1542pub enum ParentClosePolicy {
1543    #[default]
1544    Abandon,
1545    /// Legacy terminal cancellation without cooperative cleanup.
1546    RequestCancel,
1547    /// Request cooperative cleanup with the original lineage and deadline.
1548    RequestCancellation,
1549    Terminate,
1550}
1551
1552impl ParentClosePolicy {
1553    fn as_str(self) -> &'static str {
1554        match self {
1555            Self::Abandon => "abandon",
1556            Self::RequestCancel => "request_cancel",
1557            Self::RequestCancellation => "request_cancellation",
1558            Self::Terminate => "terminate",
1559        }
1560    }
1561}
1562
1563/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1564#[non_exhaustive]
1565#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1566pub enum CancellationPolicy {
1567    /// Request cancellation and continue without waiting. Historical Activity default.
1568    TryCancel,
1569    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1570    WaitCancellationCompleted,
1571    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1572    #[default]
1573    Abandon,
1574}
1575
1576impl CancellationPolicy {
1577    fn as_str(self) -> &'static str {
1578        match self {
1579            Self::TryCancel => "try_cancel",
1580            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1581            Self::Abandon => "abandon",
1582        }
1583    }
1584}
1585
1586/// Durable retry policy for one child workflow invocation.
1587#[derive(Clone, Debug, Default, PartialEq, Eq)]
1588pub struct ChildWorkflowRetryPolicy {
1589    pub max_attempts: Option<u32>,
1590    pub backoff_seconds: Vec<u64>,
1591    pub non_retryable_error_types: Vec<String>,
1592}
1593
1594/// Options recorded with a child-workflow command.
1595///
1596/// The task queue is mandatory so routing is explicit and replay-stable.
1597#[derive(Clone, Debug, PartialEq, Eq)]
1598pub struct ChildWorkflowOptions {
1599    pub task_queue: String,
1600    pub parent_close_policy: ParentClosePolicy,
1601    pub cancellation_policy: CancellationPolicy,
1602    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1603    pub execution_timeout_seconds: Option<u64>,
1604    pub run_timeout_seconds: Option<u64>,
1605}
1606
1607impl ChildWorkflowOptions {
1608    pub fn new(task_queue: impl Into<String>) -> Self {
1609        Self {
1610            task_queue: task_queue.into(),
1611            parent_close_policy: ParentClosePolicy::Abandon,
1612            cancellation_policy: CancellationPolicy::Abandon,
1613            retry_policy: None,
1614            execution_timeout_seconds: None,
1615            run_timeout_seconds: None,
1616        }
1617    }
1618
1619    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1620        self.parent_close_policy = policy;
1621        self
1622    }
1623
1624    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1625        self.cancellation_policy = policy;
1626        self
1627    }
1628
1629    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1630        self.retry_policy = Some(policy);
1631        self
1632    }
1633
1634    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1635        self.execution_timeout_seconds = Some(seconds);
1636        self
1637    }
1638
1639    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1640        self.run_timeout_seconds = Some(seconds);
1641        self
1642    }
1643}
1644
1645/// Backoff intervals for one durable activity retry policy.
1646#[derive(Clone, Debug, PartialEq, Eq)]
1647pub enum ActivityBackoff {
1648    /// Use these intervals between attempts. The server repeats the final
1649    /// interval if the retry budget contains more attempts than entries.
1650    /// All entries are retained, including those beyond the retry budget.
1651    Explicit(Vec<Duration>),
1652    /// Generate one interval for every retry using integer exponential growth.
1653    Exponential {
1654        initial_interval: Duration,
1655        coefficient: u32,
1656        maximum_interval: Option<Duration>,
1657    },
1658}
1659
1660/// Durable server-side retry policy for one activity execution.
1661#[derive(Clone, Debug, Default, PartialEq, Eq)]
1662pub struct ActivityRetryPolicy {
1663    pub max_attempts: Option<u32>,
1664    pub backoff: Option<ActivityBackoff>,
1665    pub non_retryable_error_types: Vec<String>,
1666}
1667
1668impl ActivityRetryPolicy {
1669    /// Start a policy with a finite attempt budget, including the first attempt.
1670    pub fn new(max_attempts: u32) -> Self {
1671        Self {
1672            max_attempts: Some(max_attempts),
1673            ..Self::default()
1674        }
1675    }
1676
1677    /// Preserve the complete explicit list independently of the attempt budget.
1678    /// Unused entries remain part of the policy compared during replay.
1679    /// Set explicit durable retry intervals. Each positive fractional second
1680    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
1681    /// second. Zero stays zero. Queue latency can delay the next attempt further.
1682    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1683        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1684        self
1685    }
1686
1687    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
1688    /// Each interval is capped by `maximum_interval`, when present, then rounded
1689    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
1690    /// Zero stays zero. This policy is separate from HTTP transport retries.
1691    pub fn exponential_backoff(
1692        mut self,
1693        initial_interval: Duration,
1694        coefficient: u32,
1695        maximum_interval: Option<Duration>,
1696    ) -> Self {
1697        self.backoff = Some(ActivityBackoff::Exponential {
1698            initial_interval,
1699            coefficient,
1700            maximum_interval,
1701        });
1702        self
1703    }
1704
1705    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1706        self.non_retryable_error_types.push(error_type.into());
1707        self
1708    }
1709
1710    pub fn non_retryable_error_types(
1711        mut self,
1712        error_types: impl IntoIterator<Item = impl Into<String>>,
1713    ) -> Self {
1714        self.non_retryable_error_types
1715            .extend(error_types.into_iter().map(Into::into));
1716        self
1717    }
1718}
1719
1720/// Options recorded atomically on one deterministic `schedule_activity` command.
1721///
1722/// Durations are rounded up to whole seconds when encoded, so the server never
1723/// receives a shorter timeout or backoff than the caller requested.
1724#[derive(Clone, Debug, Default, PartialEq, Eq)]
1725pub struct ActivityOptions {
1726    pub task_queue: Option<String>,
1727    pub retry_policy: Option<ActivityRetryPolicy>,
1728    pub start_to_close_timeout: Option<Duration>,
1729    pub schedule_to_start_timeout: Option<Duration>,
1730    pub schedule_to_close_timeout: Option<Duration>,
1731    pub heartbeat_timeout: Option<Duration>,
1732    pub cancellation_policy: Option<CancellationPolicy>,
1733}
1734
1735impl ActivityOptions {
1736    pub fn new() -> Self {
1737        Self::default()
1738    }
1739
1740    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1741        self.task_queue = Some(task_queue.into());
1742        self
1743    }
1744
1745    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1746        self.retry_policy = Some(policy);
1747        self
1748    }
1749
1750    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1751        self.start_to_close_timeout = Some(timeout);
1752        self
1753    }
1754
1755    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1756        self.schedule_to_start_timeout = Some(timeout);
1757        self
1758    }
1759
1760    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1761        self.schedule_to_close_timeout = Some(timeout);
1762        self
1763    }
1764
1765    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1766        self.heartbeat_timeout = Some(timeout);
1767        self
1768    }
1769
1770    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1771        self.cancellation_policy = Some(policy);
1772        self
1773    }
1774
1775    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1776        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1777            && self.schedule_to_close_timeout.is_none()
1778        {
1779            return Err(ActivityOptionsError::new(
1780                ActivityOptionsErrorKind::MissingTotalTimeout,
1781                Some("schedule_to_close_timeout"),
1782                "remote Activity Abandon requires a finite positive total timeout",
1783            ));
1784        }
1785        if self
1786            .task_queue
1787            .as_deref()
1788            .is_some_and(|queue| queue.trim().is_empty())
1789        {
1790            return Err(ActivityOptionsError::new(
1791                ActivityOptionsErrorKind::EmptyTaskQueue,
1792                Some("task_queue"),
1793                "task_queue must not be empty",
1794            ));
1795        }
1796
1797        for (field, value) in [
1798            ("start_to_close_timeout", self.start_to_close_timeout),
1799            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1800            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1801            ("heartbeat_timeout", self.heartbeat_timeout),
1802        ] {
1803            if value.is_some_and(|value| value.is_zero()) {
1804                return Err(ActivityOptionsError::new(
1805                    ActivityOptionsErrorKind::TimeoutNotPositive,
1806                    Some(field),
1807                    format!("{field} must be positive"),
1808                ));
1809            }
1810        }
1811
1812        validate_timeout_order(
1813            "heartbeat_timeout",
1814            self.heartbeat_timeout,
1815            "start_to_close_timeout",
1816            self.start_to_close_timeout,
1817        )?;
1818        validate_timeout_order(
1819            "start_to_close_timeout",
1820            self.start_to_close_timeout,
1821            "schedule_to_close_timeout",
1822            self.schedule_to_close_timeout,
1823        )?;
1824        validate_timeout_order(
1825            "schedule_to_start_timeout",
1826            self.schedule_to_start_timeout,
1827            "schedule_to_close_timeout",
1828            self.schedule_to_close_timeout,
1829        )?;
1830
1831        Ok(ValidatedActivityOptions {
1832            task_queue: self.task_queue.clone(),
1833            retry_policy: self
1834                .retry_policy
1835                .as_ref()
1836                .map(validate_activity_retry_policy)
1837                .transpose()?,
1838            start_to_close_timeout: timeout_seconds(
1839                "start_to_close_timeout",
1840                self.start_to_close_timeout,
1841            )?,
1842            schedule_to_start_timeout: timeout_seconds(
1843                "schedule_to_start_timeout",
1844                self.schedule_to_start_timeout,
1845            )?,
1846            schedule_to_close_timeout: timeout_seconds(
1847                "schedule_to_close_timeout",
1848                self.schedule_to_close_timeout,
1849            )?,
1850            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1851            cancellation_policy: self.cancellation_policy,
1852        })
1853    }
1854}
1855
1856/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1857///
1858/// Constructors capture arguments but perform no I/O. The join validates the
1859/// complete tree, attaches the existing parallel-group metadata to every
1860/// ordinary command, schedules all leaves, and then suspends.
1861pub enum ParallelOperation {
1862    Activity {
1863        activity_type: String,
1864        options: ActivityOptions,
1865        arguments: Result<AvroValue>,
1866    },
1867    ChildWorkflow {
1868        workflow_type: String,
1869        options: ChildWorkflowOptions,
1870        arguments: Result<AvroValue>,
1871    },
1872    Timer(Duration),
1873    Signal(String),
1874    Condition {
1875        options: ConditionWaitOptions,
1876        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1877    },
1878    Group(Vec<ParallelOperation>),
1879}
1880
1881impl ParallelOperation {
1882    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1883        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1884    }
1885
1886    pub fn activity_with_options<T: Serialize>(
1887        activity_type: impl Into<String>,
1888        options: ActivityOptions,
1889        args: T,
1890    ) -> Self {
1891        Self::Activity {
1892            activity_type: activity_type.into(),
1893            options,
1894            arguments: AvroValue::from_serialize(&args),
1895        }
1896    }
1897
1898    pub fn child_workflow<T: Serialize>(
1899        workflow_type: impl Into<String>,
1900        options: ChildWorkflowOptions,
1901        args: T,
1902    ) -> Self {
1903        Self::ChildWorkflow {
1904            workflow_type: workflow_type.into(),
1905            options,
1906            arguments: AvroValue::from_serialize(&args),
1907        }
1908    }
1909
1910    pub fn timer(duration: Duration) -> Self {
1911        Self::Timer(duration)
1912    }
1913
1914    pub fn signal(signal_name: impl Into<String>) -> Self {
1915        Self::Signal(signal_name.into())
1916    }
1917
1918    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1919    where
1920        F: Fn() -> Result<bool> + Send + 'static,
1921    {
1922        Self::Condition {
1923            options,
1924            predicate: Box::new(predicate),
1925        }
1926    }
1927
1928    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1929        Self::Group(operations)
1930    }
1931}
1932
1933#[derive(Clone, Debug)]
1934struct ValidatedActivityOptions {
1935    task_queue: Option<String>,
1936    retry_policy: Option<Value>,
1937    start_to_close_timeout: Option<u64>,
1938    schedule_to_start_timeout: Option<u64>,
1939    schedule_to_close_timeout: Option<u64>,
1940    heartbeat_timeout: Option<u64>,
1941    cancellation_policy: Option<CancellationPolicy>,
1942}
1943
1944fn validate_timeout_order(
1945    smaller_name: &'static str,
1946    smaller: Option<Duration>,
1947    larger_name: &'static str,
1948    larger: Option<Duration>,
1949) -> std::result::Result<(), ActivityOptionsError> {
1950    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1951        return Err(ActivityOptionsError::new(
1952            ActivityOptionsErrorKind::TimeoutOrder,
1953            Some(smaller_name),
1954            format!("{smaller_name} must be <= {larger_name}"),
1955        ));
1956    }
1957    Ok(())
1958}
1959
1960fn timeout_seconds(
1961    field: &'static str,
1962    value: Option<Duration>,
1963) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1964    value
1965        .map(|value| {
1966            activity_protocol_seconds(value).ok_or_else(|| {
1967                ActivityOptionsError::new(
1968                    ActivityOptionsErrorKind::TimeoutOverflow,
1969                    Some(field),
1970                    format!("{field} is too large for the worker protocol"),
1971                )
1972            })
1973        })
1974        .transpose()
1975}
1976
1977fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1978    value
1979        .as_secs()
1980        .checked_add(u64::from(value.subsec_nanos() > 0))
1981}
1982
1983fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1984    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1985}
1986
1987fn validate_activity_retry_policy(
1988    policy: &ActivityRetryPolicy,
1989) -> std::result::Result<Value, ActivityOptionsError> {
1990    if policy.max_attempts.is_none()
1991        && policy.backoff.is_none()
1992        && policy.non_retryable_error_types.is_empty()
1993    {
1994        return Err(ActivityOptionsError::new(
1995            ActivityOptionsErrorKind::EmptyRetryPolicy,
1996            Some("retry_policy"),
1997            "retry_policy must configure at least one field",
1998        ));
1999    }
2000    if policy.max_attempts == Some(0) {
2001        return Err(ActivityOptionsError::new(
2002            ActivityOptionsErrorKind::InvalidMaxAttempts,
2003            Some("retry_policy.max_attempts"),
2004            "max_attempts must be >= 1",
2005        ));
2006    }
2007    if policy
2008        .non_retryable_error_types
2009        .iter()
2010        .any(|error_type| error_type.trim().is_empty())
2011    {
2012        return Err(ActivityOptionsError::new(
2013            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2014            Some("retry_policy.non_retryable_error_types"),
2015            "non_retryable_error_types must not contain empty values",
2016        ));
2017    }
2018
2019    let backoff_seconds = match &policy.backoff {
2020        None => None,
2021        Some(backoff) => {
2022            let max_attempts = policy.max_attempts.ok_or_else(|| {
2023                ActivityOptionsError::new(
2024                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2025                    Some("retry_policy.backoff"),
2026                    "backoff requires max_attempts",
2027                )
2028            })?;
2029            let retry_count = max_attempts.saturating_sub(1) as usize;
2030            let intervals = match backoff {
2031                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2032                ActivityBackoff::Exponential {
2033                    initial_interval,
2034                    coefficient,
2035                    maximum_interval,
2036                } => {
2037                    if *coefficient < 1 {
2038                        return Err(ActivityOptionsError::new(
2039                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2040                            Some("retry_policy.backoff.coefficient"),
2041                            "backoff coefficient must be >= 1",
2042                        ));
2043                    }
2044                    if retry_count > 10_000 {
2045                        return Err(ActivityOptionsError::new(
2046                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2047                            Some("retry_policy.max_attempts"),
2048                            "generated backoff supports at most 10000 retry intervals",
2049                        ));
2050                    }
2051                    let mut current = *initial_interval;
2052                    let mut intervals = Vec::with_capacity(retry_count);
2053                    for _ in 0..retry_count {
2054                        let interval = maximum_interval
2055                            .map(|maximum| current.min(maximum))
2056                            .unwrap_or(current);
2057                        intervals.push(interval);
2058                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2059                            break;
2060                        }
2061                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2062                            ActivityOptionsError::new(
2063                                ActivityOptionsErrorKind::BackoffOverflow,
2064                                Some("retry_policy.backoff"),
2065                                "generated backoff interval overflowed",
2066                            )
2067                        })?;
2068                    }
2069                    intervals
2070                }
2071            };
2072            Some(
2073                intervals
2074                    .into_iter()
2075                    .map(|interval| {
2076                        activity_protocol_seconds(interval).ok_or_else(|| {
2077                            ActivityOptionsError::new(
2078                                ActivityOptionsErrorKind::BackoffOverflow,
2079                                Some("retry_policy.backoff"),
2080                                "backoff interval is too large for the worker protocol",
2081                            )
2082                        })
2083                    })
2084                    .collect::<std::result::Result<Vec<_>, _>>()?,
2085            )
2086        }
2087    };
2088
2089    let mut encoded = serde_json::Map::new();
2090    if let Some(max_attempts) = policy.max_attempts {
2091        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2092    }
2093    if let Some(backoff_seconds) = backoff_seconds {
2094        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2095    }
2096    if !policy.non_retryable_error_types.is_empty() {
2097        let mut canonical_error_types = Vec::new();
2098        for error_type in policy
2099            .non_retryable_error_types
2100            .iter()
2101            .map(|error_type| error_type.trim())
2102        {
2103            if !canonical_error_types.contains(&error_type) {
2104                canonical_error_types.push(error_type);
2105            }
2106        }
2107        encoded.insert(
2108            "non_retryable_error_types".to_string(),
2109            json!(canonical_error_types),
2110        );
2111    }
2112    Ok(Value::Object(encoded))
2113}
2114
2115/// A stable, machine-readable failure raised when workflow code no longer
2116/// reconstructs the durable command stream recorded in history.
2117#[derive(Clone, Debug, Error)]
2118#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2119pub struct ReplayFailure {
2120    pub reason: String,
2121    pub sequence: Option<u64>,
2122    pub expected: Option<String>,
2123    pub actual: Option<String>,
2124    pub message: String,
2125}
2126
2127impl ReplayFailure {
2128    fn new(
2129        reason: impl Into<String>,
2130        sequence: Option<u64>,
2131        expected: Option<String>,
2132        actual: Option<String>,
2133        message: impl Into<String>,
2134    ) -> Self {
2135        Self {
2136            reason: reason.into(),
2137            sequence,
2138            expected,
2139            actual,
2140            message: message.into(),
2141        }
2142    }
2143}
2144
2145/// A stable, machine-readable workflow query or query-task settlement failure.
2146#[derive(Clone, Debug, Error)]
2147#[error("query failed ({reason}, HTTP {status}): {message}")]
2148pub struct QueryFailure {
2149    pub status: u16,
2150    pub reason: String,
2151    pub message: String,
2152    pub body: Value,
2153}
2154
2155/// A stable failure returned when a server rejects an SDK protocol version.
2156#[derive(Clone, Debug, Error)]
2157#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2158pub struct ProtocolFailure {
2159    pub status: u16,
2160    pub reason: String,
2161    pub message: String,
2162    pub supported_version: Option<String>,
2163    pub requested_version: Option<String>,
2164    pub body: Value,
2165}
2166
2167#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2168pub struct PayloadEnvelope {
2169    pub codec: String,
2170    pub blob: String,
2171}
2172
2173impl PayloadEnvelope {
2174    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2175        encode_payload(value, DEFAULT_CODEC)
2176    }
2177
2178    /// Encode an explicit typed value, including the bytes branch that JSON
2179    /// serialization cannot represent.
2180    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2181        encode_avro_value(value)
2182    }
2183}
2184
2185/// Native adapter for the fixed language-neutral Avro Value schema.
2186#[derive(Clone, Debug)]
2187pub enum AvroValue {
2188    Null,
2189    Boolean(bool),
2190    Long(i64),
2191    Double(f64),
2192    Bytes(Vec<u8>),
2193    String(String),
2194    Array(Vec<AvroValue>),
2195    Map(BTreeMap<String, AvroValue>),
2196}
2197
2198impl PartialEq for AvroValue {
2199    fn eq(&self, other: &Self) -> bool {
2200        match (self, other) {
2201            (Self::Null, Self::Null) => true,
2202            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2203            (Self::Long(left), Self::Long(right)) => left == right,
2204            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2205            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2206            (Self::String(left), Self::String(right)) => left == right,
2207            (Self::Array(left), Self::Array(right)) => left == right,
2208            (Self::Map(left), Self::Map(right)) => left == right,
2209            _ => false,
2210        }
2211    }
2212}
2213
2214impl AvroValue {
2215    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2216        Self::from_serde_value(
2217            serde_value::to_value(value).map_err(|error| {
2218                Error::Codec(format!("could not adapt value for Avro: {error}"))
2219            })?,
2220        )
2221    }
2222
2223    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2224        use serde_value::Value as SerdeValue;
2225
2226        match value {
2227            SerdeValue::Unit => Ok(Self::Null),
2228            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2229            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2230            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2231            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2232            SerdeValue::I64(value) => Ok(Self::Long(value)),
2233            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2234            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2235            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2236            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2237                Error::Codec(
2238                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2239                        .to_string(),
2240                )
2241            }),
2242            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2243            SerdeValue::F64(value) => Self::finite_double(value),
2244            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2245            SerdeValue::String(value) => Ok(Self::String(value)),
2246            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2247            SerdeValue::Option(None) => Ok(Self::Null),
2248            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2249                Self::from_serde_value(*value)
2250            }
2251            SerdeValue::Seq(values) => values
2252                .into_iter()
2253                .map(Self::from_serde_value)
2254                .collect::<Result<Vec<_>>>()
2255                .map(Self::Array),
2256            SerdeValue::Map(values) => values
2257                .into_iter()
2258                .map(|(key, value)| {
2259                    let SerdeValue::String(key) = key else {
2260                        return Err(Error::Codec(
2261                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2262                        ));
2263                    };
2264
2265                    Ok((key, Self::from_serde_value(value)?))
2266                })
2267                .collect::<Result<BTreeMap<_, _>>>()
2268                .map(Self::Map),
2269        }
2270    }
2271
2272    fn finite_double(value: f64) -> Result<Self> {
2273        if !value.is_finite() {
2274            return Err(Error::Codec(
2275                "non_finite_float: Avro Value doubles must be finite".to_string(),
2276            ));
2277        }
2278
2279        Ok(Self::Double(value))
2280    }
2281
2282    fn into_json(self) -> Result<Value> {
2283        match self {
2284            Self::Null => Ok(Value::Null),
2285            Self::Boolean(value) => Ok(Value::Bool(value)),
2286            Self::Long(value) => Ok(Value::Number(value.into())),
2287            Self::Double(value) => serde_json::Number::from_f64(value)
2288                .map(Value::Number)
2289                .ok_or_else(|| {
2290                    Error::Codec(
2291                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2292                    )
2293                }),
2294            Self::Bytes(value) => Ok(json!({
2295                "$type": "bytes",
2296                "base64": BASE64.encode(value),
2297            })),
2298            Self::String(value) => Ok(Value::String(value)),
2299            Self::Array(values) => values
2300                .into_iter()
2301                .map(Self::into_json)
2302                .collect::<Result<Vec<_>>>()
2303                .map(Value::Array),
2304            Self::Map(values) => values
2305                .into_iter()
2306                .map(|(key, value)| Ok((key, value.into_json()?)))
2307                .collect::<Result<serde_json::Map<_, _>>>()
2308                .map(Value::Object),
2309        }
2310    }
2311
2312    fn into_serde_value(self) -> serde_value::Value {
2313        use serde_value::Value as SerdeValue;
2314
2315        match self {
2316            Self::Null => SerdeValue::Unit,
2317            Self::Boolean(value) => SerdeValue::Bool(value),
2318            Self::Long(value) => SerdeValue::I64(value),
2319            Self::Double(value) => SerdeValue::F64(value),
2320            Self::Bytes(value) => SerdeValue::Bytes(value),
2321            Self::String(value) => SerdeValue::String(value),
2322            Self::Array(values) => {
2323                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2324            }
2325            Self::Map(values) => SerdeValue::Map(
2326                values
2327                    .into_iter()
2328                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2329                    .collect(),
2330            ),
2331        }
2332    }
2333
2334    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2335        self.into_serde_value().deserialize_into().map_err(|error| {
2336            Error::Codec(format!(
2337                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2338            ))
2339        })
2340    }
2341}
2342
2343impl Serialize for AvroValue {
2344    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2345    where
2346        S: Serializer,
2347    {
2348        match self {
2349            Self::Null => serializer.serialize_unit(),
2350            Self::Boolean(value) => serializer.serialize_bool(*value),
2351            Self::Long(value) => serializer.serialize_i64(*value),
2352            Self::Double(value) => serializer.serialize_f64(*value),
2353            Self::Bytes(value) => serializer.serialize_bytes(value),
2354            Self::String(value) => serializer.serialize_str(value),
2355            Self::Array(values) => {
2356                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2357                for value in values {
2358                    sequence.serialize_element(value)?;
2359                }
2360                sequence.end()
2361            }
2362            Self::Map(values) => {
2363                let mut map = serializer.serialize_map(Some(values.len()))?;
2364                for (key, value) in values {
2365                    map.serialize_entry(key, value)?;
2366                }
2367                map.end()
2368            }
2369        }
2370    }
2371}
2372
2373pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2374    let datum = avro_value_to_datum(value)?;
2375    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2376        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2377    let mut bytes = Vec::with_capacity(datum.len() + 10);
2378    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2379    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2380    bytes.extend_from_slice(&datum);
2381    Ok(PayloadEnvelope {
2382        codec: DEFAULT_CODEC.to_string(),
2383        blob: BASE64.encode(bytes),
2384    })
2385}
2386
2387pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2388    if envelope.codec != DEFAULT_CODEC {
2389        return Err(unsupported_payload_codec(&envelope.codec));
2390    }
2391    decode_avro_value_blob(&envelope.blob)
2392}
2393
2394pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2395    let blob = match codec {
2396        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2397        other => return Err(unsupported_payload_codec(other)),
2398    };
2399
2400    Ok(PayloadEnvelope {
2401        codec: codec.to_string(),
2402        blob,
2403    })
2404}
2405
2406pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2407    match envelope.codec.as_str() {
2408        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2409        other => Err(unsupported_payload_codec(other)),
2410    }
2411}
2412
2413fn handler_type_error<T>(
2414    handler_kind: HandlerKind,
2415    handler_name: &str,
2416    value_kind: HandlerValueKind,
2417    message: impl Into<String>,
2418) -> Error {
2419    Error::HandlerType {
2420        handler_kind,
2421        handler_name: handler_name.to_string(),
2422        value_kind,
2423        rust_type: type_name::<T>(),
2424        message: message.into(),
2425    }
2426}
2427
2428fn decode_handler_input<T: DeserializeOwned>(
2429    arguments: AvroValue,
2430    handler_kind: HandlerKind,
2431    handler_name: &str,
2432) -> Result<T> {
2433    let argument = match arguments {
2434        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2435            arguments.pop().expect("one typed handler argument")
2436        }
2437        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2438        AvroValue::Array(arguments) => {
2439            return Err(handler_type_error::<T>(
2440                handler_kind,
2441                handler_name,
2442                HandlerValueKind::Input,
2443                format!(
2444                    "typed handlers accept one request value, but the task carried {} arguments",
2445                    arguments.len()
2446                ),
2447            ));
2448        }
2449        argument => argument,
2450    };
2451
2452    argument.deserialize().map_err(|error| {
2453        handler_type_error::<T>(
2454            handler_kind,
2455            handler_name,
2456            HandlerValueKind::Input,
2457            error.to_string(),
2458        )
2459    })
2460}
2461
2462fn decode_workflow_entry<T: DeserializeOwned>(
2463    arguments: AvroValue,
2464    workflow_type: &str,
2465) -> Result<T> {
2466    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2467        // Serde errors may contain recorded values. The entry refusal exposes
2468        // only the registered workflow and expected Rust type.
2469        handler_type_error::<T>(
2470            HandlerKind::Workflow,
2471            workflow_type,
2472            HandlerValueKind::Input,
2473            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2474        )
2475    })
2476}
2477
2478fn encode_handler_result<T: Serialize>(
2479    result: &T,
2480    handler_kind: HandlerKind,
2481    handler_name: &str,
2482) -> Result<AvroValue> {
2483    AvroValue::from_serialize(result).map_err(|error| {
2484        handler_type_error::<T>(
2485            handler_kind,
2486            handler_name,
2487            HandlerValueKind::Result,
2488            error.to_string(),
2489        )
2490    })
2491}
2492
2493fn decode_handler_result<T: DeserializeOwned>(
2494    result: AvroValue,
2495    handler_kind: HandlerKind,
2496    handler_name: &str,
2497) -> Result<T> {
2498    result.deserialize().map_err(|error| {
2499        handler_type_error::<T>(
2500            handler_kind,
2501            handler_name,
2502            HandlerValueKind::Result,
2503            error.to_string(),
2504        )
2505    })
2506}
2507
2508#[cfg(test)]
2509fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2510    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2511}
2512
2513fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2514    validate_payload_codec(fallback_codec)?;
2515
2516    if value.is_null() {
2517        return Ok(Value::Null);
2518    }
2519
2520    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2521        return decode_blob(blob, codec);
2522    }
2523
2524    if let Some(blob) = value.as_str() {
2525        return decode_blob(blob, fallback_codec);
2526    }
2527
2528    Err(untagged_payload_value())
2529}
2530
2531fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2532    let envelope = match codec {
2533        DEFAULT_CODEC => encode_avro_value(value)?,
2534        other => return Err(unsupported_payload_codec(other)),
2535    };
2536    Ok(serde_json::to_value(envelope)?)
2537}
2538
2539fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2540    validate_payload_codec(fallback_codec)?;
2541
2542    if value.is_null() {
2543        return Ok(AvroValue::Null);
2544    }
2545
2546    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2547        validate_payload_codec(codec)?;
2548        return decode_avro_value_blob(blob);
2549    }
2550
2551    if let Some(blob) = value.as_str() {
2552        return match fallback_codec {
2553            DEFAULT_CODEC => decode_avro_value_blob(blob),
2554            other => Err(unsupported_payload_codec(other)),
2555        };
2556    }
2557
2558    Err(untagged_payload_value())
2559}
2560
2561fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2562    match value {
2563        AvroValue::Null => AvroValue::Array(Vec::new()),
2564        AvroValue::Array(_) => value,
2565        other => AvroValue::Array(vec![other]),
2566    }
2567}
2568
2569fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2570    match codec {
2571        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2572        other => Err(unsupported_payload_codec(other)),
2573    }
2574}
2575
2576fn validate_payload_codec(codec: &str) -> Result<()> {
2577    match codec {
2578        DEFAULT_CODEC => Ok(()),
2579        MISSING_TASK_PAYLOAD_CODEC => {
2580            Err(invalid_task_payload_codec("task payload_codec is missing"))
2581        }
2582        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2583        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2584            "task payload_codec must be a string",
2585        )),
2586        other => Err(unsupported_payload_codec(other)),
2587    }
2588}
2589
2590fn invalid_task_payload_codec(reason: &str) -> Error {
2591    Error::Codec(format!(
2592        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2593    ))
2594}
2595
2596fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2597    let Some(object) = value.as_object() else {
2598        return Ok(None);
2599    };
2600    if !object.contains_key("codec") && !object.contains_key("blob") {
2601        return Ok(None);
2602    }
2603
2604    let codec = object
2605        .get("codec")
2606        .and_then(Value::as_str)
2607        .ok_or_else(invalid_payload_envelope)?;
2608    validate_payload_codec(codec)?;
2609    let blob = object
2610        .get("blob")
2611        .and_then(Value::as_str)
2612        .ok_or_else(invalid_payload_envelope)?;
2613    Ok(Some((codec, blob)))
2614}
2615
2616fn invalid_payload_envelope() -> Error {
2617    Error::Codec(
2618        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2619            .to_string(),
2620    )
2621}
2622
2623fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2624    for command in commands {
2625        let Some(command) = command.as_object() else {
2626            continue;
2627        };
2628        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2629            continue;
2630        };
2631        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2632            continue;
2633        };
2634
2635        if let Some(codec) = command.get("payload_codec") {
2636            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2637            validate_payload_codec(codec)?;
2638        }
2639
2640        let payload = command
2641            .get(payload_field)
2642            .ok_or_else(invalid_payload_envelope)?;
2643        if runtime_payloads::Reference::parse(payload)?.is_none() {
2644            validate_outbound_payload_envelope(payload)?;
2645        }
2646    }
2647    Ok(())
2648}
2649
2650fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2651    if commands.iter().any(|command| {
2652        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2653            && command
2654                .get("condition_wait_occurrence_id")
2655                .and_then(Value::as_str)
2656                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2657    }) {
2658        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2659    } else if commands.iter().any(|command| {
2660        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2661            && command.get("attribute_types").is_some()
2662    }) {
2663        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2664    } else if commands
2665        .iter()
2666        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2667    {
2668        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2669    } else if commands
2670        .iter()
2671        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2672    {
2673        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2674    } else if commands.iter().any(|command| {
2675        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2676    }) {
2677        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2678    } else {
2679        MINIMUM_WORKER_PROTOCOL_VERSION
2680    }
2681}
2682
2683fn workflow_completion_protocol_version_with_message_streams(
2684    commands: &[Value],
2685    has_message_stream_metadata: bool,
2686) -> &'static str {
2687    let command_protocol = workflow_completion_protocol_version(commands);
2688    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2689        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2690    } else {
2691        command_protocol
2692    }
2693}
2694
2695fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2696    match command_type {
2697        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2698        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2699        "start_service_operation" => Some("request_payload"),
2700        "upsert_memo" => Some("entries"),
2701        _ => None,
2702    }
2703}
2704
2705fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2706    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2707        return Err(untagged_payload_value());
2708    };
2709    validate_payload_codec(codec)?;
2710    decode_avro_value_blob(blob)?;
2711    Ok(())
2712}
2713
2714fn unsupported_payload_codec(codec: &str) -> Error {
2715    Error::Codec(format!(
2716        "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"
2717    ))
2718}
2719
2720fn untagged_payload_value() -> Error {
2721    Error::Codec(
2722        "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"
2723            .to_string(),
2724    )
2725}
2726
2727fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2728    let bytes = BASE64.decode(blob).map_err(|err| {
2729        Error::Codec(format!(
2730            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2731        ))
2732    })?;
2733
2734    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2735        return Err(unsupported_payload_codec("json"));
2736    }
2737
2738    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2739        return Err(Error::Codec(
2740            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2741        ));
2742    }
2743
2744    let fingerprint: [u8; 8] = bytes[2..10]
2745        .try_into()
2746        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2747    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2748        return Err(Error::Codec(format!(
2749            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2750            fingerprint
2751                .iter()
2752                .map(|byte| format!("{byte:02x}"))
2753                .collect::<String>()
2754        )));
2755    }
2756
2757    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2758    // The current fingerprint selects the current immutable schema, so reader
2759    // resolution would only re-walk the same recursive union. Future retained
2760    // writer fingerprints supply a distinct reader schema in this branch.
2761    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2762    if datum_reader.truncated {
2763        return Err(Error::Codec(
2764            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2765        ));
2766    }
2767    let datum = datum.map_err(|err| {
2768        Error::Codec(format!(
2769            "invalid_payload_framing: malformed Avro Value datum: {err}"
2770        ))
2771    })?;
2772    if datum_reader.remaining() != 0 {
2773        return Err(Error::Codec(format!(
2774            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2775            datum_reader.remaining()
2776        )));
2777    }
2778    avro_value_from_datum(datum)
2779}
2780
2781struct StrictAvroDatumReader<'a> {
2782    bytes: &'a [u8],
2783    offset: usize,
2784    truncated: bool,
2785}
2786
2787impl<'a> StrictAvroDatumReader<'a> {
2788    fn new(bytes: &'a [u8]) -> Self {
2789        Self {
2790            bytes,
2791            offset: 0,
2792            truncated: false,
2793        }
2794    }
2795
2796    fn remaining(&self) -> usize {
2797        self.bytes.len() - self.offset
2798    }
2799}
2800
2801impl Read for StrictAvroDatumReader<'_> {
2802    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2803        let count = buffer.len().min(self.remaining());
2804        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2805        self.offset += count;
2806        if count < buffer.len() {
2807            self.truncated = true;
2808        }
2809
2810        Ok(count)
2811    }
2812}
2813
2814fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2815    let branch = match value {
2816        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2817        AvroValue::Boolean(value) => AvroDatum::Union(
2818            1,
2819            Box::new(AvroDatum::Record(vec![(
2820                "boolean".to_string(),
2821                AvroDatum::Boolean(*value),
2822            )])),
2823        ),
2824        AvroValue::Long(value) => AvroDatum::Union(
2825            2,
2826            Box::new(AvroDatum::Record(vec![(
2827                "long".to_string(),
2828                AvroDatum::Long(*value),
2829            )])),
2830        ),
2831        AvroValue::Double(value) => {
2832            if !value.is_finite() {
2833                return Err(Error::Codec(
2834                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2835                ));
2836            }
2837            AvroDatum::Union(
2838                3,
2839                Box::new(AvroDatum::Record(vec![(
2840                    "double".to_string(),
2841                    AvroDatum::Double(*value),
2842                )])),
2843            )
2844        }
2845        AvroValue::Bytes(value) => AvroDatum::Union(
2846            4,
2847            Box::new(AvroDatum::Record(vec![(
2848                "bytes".to_string(),
2849                AvroDatum::Bytes(value.clone()),
2850            )])),
2851        ),
2852        AvroValue::String(value) => AvroDatum::Union(
2853            5,
2854            Box::new(AvroDatum::Record(vec![(
2855                "string".to_string(),
2856                AvroDatum::String(value.clone()),
2857            )])),
2858        ),
2859        AvroValue::Array(values) => AvroDatum::Union(
2860            6,
2861            Box::new(AvroDatum::Record(vec![(
2862                "items".to_string(),
2863                AvroDatum::Array(
2864                    values
2865                        .iter()
2866                        .map(avro_value_to_datum)
2867                        .collect::<Result<Vec<_>>>()?,
2868                ),
2869            )])),
2870        ),
2871        AvroValue::Map(values) => AvroDatum::Union(
2872            7,
2873            Box::new(AvroDatum::Record(vec![(
2874                "entries".to_string(),
2875                AvroDatum::Array(
2876                    values
2877                        .iter()
2878                        .map(|(key, value)| {
2879                            Ok(AvroDatum::Record(vec![
2880                                ("key".to_string(), AvroDatum::String(key.clone())),
2881                                ("value".to_string(), avro_value_to_datum(value)?),
2882                            ]))
2883                        })
2884                        .collect::<Result<Vec<_>>>()?,
2885                ),
2886            )])),
2887        ),
2888    };
2889    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2890}
2891
2892fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2893    let AvroDatum::Record(mut outer) = datum else {
2894        return Err(Error::Codec(
2895            "invalid_payload_framing: datum is not a Value record".to_string(),
2896        ));
2897    };
2898    let (_, branch) = outer
2899        .pop()
2900        .filter(|(name, _)| name == "value")
2901        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2902    let AvroDatum::Union(_, branch) = branch else {
2903        return Err(Error::Codec(
2904            "invalid_payload_framing: invalid Value union".to_string(),
2905        ));
2906    };
2907    match *branch {
2908        AvroDatum::Null => Ok(AvroValue::Null),
2909        AvroDatum::Record(mut fields) => {
2910            let (name, value) = fields.pop().ok_or_else(|| {
2911                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2912            })?;
2913            match (name.as_str(), value) {
2914                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2915                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2916                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2917                    Ok(AvroValue::Double(value))
2918                }
2919                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2920                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2921                ("items", AvroDatum::Array(values)) => values
2922                    .into_iter()
2923                    .map(avro_value_from_datum)
2924                    .collect::<Result<Vec<_>>>()
2925                    .map(AvroValue::Array),
2926                ("entries", AvroDatum::Map(values)) => values
2927                    .into_iter()
2928                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2929                    .collect::<Result<BTreeMap<_, _>>>()
2930                    .map(AvroValue::Map),
2931                _ => Err(Error::Codec(
2932                    "invalid_payload_framing: unknown Value branch".to_string(),
2933                )),
2934            }
2935        }
2936        _ => Err(Error::Codec(
2937            "invalid_payload_framing: invalid Value branch".to_string(),
2938        )),
2939    }
2940}
2941
2942fn avro_value_schema() -> Result<&'static Schema> {
2943    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2944        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2945            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2946    }) {
2947        Ok(schema) => Ok(schema),
2948        Err(message) => Err(Error::Codec(message.clone())),
2949    }
2950}
2951
2952fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2953    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2954        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2955        // have the same block representation when each ordered array record
2956        // contains the map key followed by its value, so this encoding-only
2957        // adaptation lets the official encoder retain BTreeMap wire order.
2958        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2959            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2960        let entries_schema = schema
2961            .pointer_mut("/fields/0/type/7/fields/0/type")
2962            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2963        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2964            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2965        }
2966        *entries_schema = json!({
2967            "type": "array",
2968            "items": {
2969                "type": "record",
2970                "name": "MapEntry",
2971                "fields": [
2972                    {"name": "key", "type": "string"},
2973                    {"name": "value", "type": "Value"}
2974                ]
2975            }
2976        });
2977        Schema::parse_str(&schema.to_string())
2978            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2979    }) {
2980        Ok(schema) => Ok(schema),
2981        Err(message) => Err(Error::Codec(message.clone())),
2982    }
2983}
2984
2985#[derive(Clone, Debug)]
2986pub struct Client {
2987    http: reqwest::Client,
2988    hydration_timeout: Duration,
2989    base_url: String,
2990    token: Option<String>,
2991    control_token: Option<String>,
2992    worker_token: Option<String>,
2993    namespace: String,
2994    max_external_payload_bytes: usize,
2995    worker_storage_admission: Option<WorkerStorageAdmission>,
2996    worker_task_slot: Option<Arc<worker_capacity::TaskSlotMarker>>,
2997    cooperative_worker_protocol: bool,
2998    worker_protocol_version: WorkerProtocolVersion,
2999    local_activities_enabled: bool,
3000    worker_sessions_enabled: bool,
3001    max_concurrent_worker_sessions: usize,
3002    worker_build_id: Option<String>,
3003    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
3004    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
3005    activity_lease_renewal_supported: Arc<AtomicBool>,
3006    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
3007    #[cfg(feature = "telemetry")]
3008    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
3009    #[cfg(feature = "telemetry")]
3010    observability_context_supported: Arc<AtomicBool>,
3011}
3012
3013impl Client {
3014    /// Configure optional propagation. Actual cluster discovery must advertise
3015    /// the exact supported capability before any command carries context.
3016    #[cfg(feature = "telemetry")]
3017    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3018        self.execution_telemetry = Some(telemetry);
3019        self
3020    }
3021
3022    #[cfg(feature = "telemetry")]
3023    fn with_observability_context(&self, mut body: Value) -> Value {
3024        if self.observability_context_supported.load(Ordering::SeqCst) {
3025            if let Some(context) = self
3026                .execution_telemetry
3027                .as_ref()
3028                .and_then(|telemetry| telemetry.capture())
3029            {
3030                body["observability_context"] = context;
3031            }
3032        }
3033        body
3034    }
3035
3036    #[cfg(not(feature = "telemetry"))]
3037    fn with_observability_context(&self, body: Value) -> Value {
3038        body
3039    }
3040
3041    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3042        Self::builder(base_url).build()
3043    }
3044
3045    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3046        ClientBuilder {
3047            base_url: base_url.into(),
3048            token: None,
3049            control_token: None,
3050            worker_token: None,
3051            namespace: "default".to_string(),
3052            timeout: Duration::from_secs(60),
3053            max_external_payload_bytes: 64 * 1024 * 1024,
3054            worker_protocol_version: WorkerProtocolVersion::default(),
3055            additional_root_certificates: Vec::new(),
3056        }
3057    }
3058
3059    pub async fn health(&self) -> Result<Value> {
3060        self.request_json(
3061            reqwest::Method::GET,
3062            "/health",
3063            RequestProtocol::ControlPlane,
3064            Option::<&Value>::None,
3065        )
3066        .await
3067    }
3068
3069    pub async fn cluster_info(&self) -> Result<Value> {
3070        let discovery: Value = self
3071            .request_json(
3072                reqwest::Method::GET,
3073                "/cluster/info",
3074                RequestProtocol::ControlPlane,
3075                Option::<&Value>::None,
3076            )
3077            .await?;
3078        self.observe_activity_lease_capabilities(
3079            &discovery["worker_protocol"]["server_capabilities"],
3080        );
3081        Ok(discovery)
3082    }
3083
3084    pub async fn start_workflow<T: Serialize>(
3085        &self,
3086        workflow_type: &str,
3087        task_queue: &str,
3088        workflow_id: &str,
3089        input: T,
3090    ) -> Result<WorkflowHandle> {
3091        self.start_workflow_with_options(
3092            workflow_type,
3093            task_queue,
3094            workflow_id,
3095            WorkflowStartOptions::default(),
3096            input,
3097        )
3098        .await
3099    }
3100
3101    /// Start a workflow with explicit server-enforced execution and run
3102    /// deadlines.
3103    pub async fn start_workflow_with_options<T: Serialize>(
3104        &self,
3105        workflow_type: &str,
3106        task_queue: &str,
3107        workflow_id: &str,
3108        options: WorkflowStartOptions,
3109        input: T,
3110    ) -> Result<WorkflowHandle> {
3111        options.validate()?;
3112        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3113        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3114        let body = self.with_observability_context(json!({
3115            "workflow_id": workflow_id,
3116            "workflow_type": workflow_type,
3117            "task_queue": task_queue,
3118            "input": input_envelope,
3119            "execution_timeout_seconds": options.execution_timeout_seconds,
3120            "run_timeout_seconds": options.run_timeout_seconds
3121        }));
3122
3123        let data: Value = self
3124            .request_json(
3125                reqwest::Method::POST,
3126                "/workflows",
3127                RequestProtocol::ControlPlane,
3128                Some(&body),
3129            )
3130            .await?;
3131
3132        Ok(WorkflowHandle {
3133            client: self.clone(),
3134            workflow_id: data
3135                .get("workflow_id")
3136                .and_then(Value::as_str)
3137                .unwrap_or(workflow_id)
3138                .to_string(),
3139            run_id: data
3140                .get("run_id")
3141                .and_then(Value::as_str)
3142                .map(str::to_string),
3143            workflow_type: data
3144                .get("workflow_type")
3145                .and_then(Value::as_str)
3146                .unwrap_or(workflow_type)
3147                .to_string(),
3148        })
3149    }
3150
3151    /// Send a signal with an SDK-generated caller command key.
3152    ///
3153    /// The key is sent as the `request_id` body field and is present in the
3154    /// returned receipt's `request_id`. A Server that already retains the key
3155    /// for the same signal intent returns the original receipt with
3156    /// `retained: true`; a different intent is refused with
3157    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3158    /// [`Client::signal_workflow_with_request_id`] when the application must be
3159    /// able to retry the same logical signal after a transport failure.
3160    pub async fn signal_workflow<T: Serialize>(
3161        &self,
3162        workflow_id: &str,
3163        signal_name: &str,
3164        input: T,
3165    ) -> Result<Value> {
3166        let request_id = Self::generate_signal_request_id();
3167        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3168            .await
3169    }
3170
3171    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3172    ///
3173    /// Resend the identical signal with the same key after an uncertain
3174    /// outcome: the Server returns the retained receipt instead of admitting a
3175    /// second signal, for as long as the retained run's details are kept.
3176    pub async fn signal_workflow_with_request_id<T: Serialize>(
3177        &self,
3178        workflow_id: &str,
3179        signal_name: &str,
3180        input: T,
3181        request_id: &str,
3182    ) -> Result<Value> {
3183        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3184            .await
3185    }
3186
3187    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3188    ///
3189    /// Methods without an explicit key generate one of these per call. Obtain it
3190    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3191    /// transport failure does not lose the key needed for a safe retry.
3192    pub fn generate_signal_request_id() -> String {
3193        generated_request_id("signal")
3194    }
3195
3196    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3197    ///
3198    /// [`Client::update_workflow`] generates one of these when `request_id` is
3199    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3200    /// does not lose the key needed for a safe retry.
3201    pub fn generate_update_request_id() -> String {
3202        generated_request_id("update")
3203    }
3204
3205    /// Append one idempotently identified item to an instance-scoped input stream.
3206    pub async fn append_message_stream<T: Serialize>(
3207        &self,
3208        workflow_id: &str,
3209        stream_name: &str,
3210        message_id: &str,
3211        input: T,
3212    ) -> Result<Value> {
3213        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3214        let body = json!({
3215            "message_id": message_id,
3216            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3217        });
3218        self.request_json(
3219            reqwest::Method::POST,
3220            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
3221            RequestProtocol::ControlPlane,
3222            Some(&body),
3223        )
3224        .await
3225    }
3226
3227    /// Signal only if `run_id` is still the current run for this instance,
3228    /// with an SDK-generated caller command key.
3229    pub async fn signal_workflow_run<T: Serialize>(
3230        &self,
3231        workflow_id: &str,
3232        run_id: &str,
3233        signal_name: &str,
3234        input: T,
3235    ) -> Result<Value> {
3236        let request_id = Self::generate_signal_request_id();
3237        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3238            .await
3239    }
3240
3241    /// Signal only if `run_id` is still the current run for this instance,
3242    /// with an explicit caller command key (1 to 255 Unicode characters).
3243    ///
3244    /// The selected run is part of the signal's intent: retrying with the same
3245    /// key and a different run target is a `request_id_conflict` refusal.
3246    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3247        &self,
3248        workflow_id: &str,
3249        run_id: &str,
3250        signal_name: &str,
3251        input: T,
3252        request_id: &str,
3253    ) -> Result<Value> {
3254        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3255            .await
3256    }
3257
3258    async fn signal_workflow_target<T: Serialize>(
3259        &self,
3260        workflow_id: &str,
3261        run_id: Option<&str>,
3262        signal_name: &str,
3263        input: T,
3264        request_id: &str,
3265    ) -> Result<Value> {
3266        validate_user_signal_name(signal_name)?;
3267        validate_request_id(request_id)?;
3268        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3269        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3270        let body = self.with_observability_context(json!({
3271            "input": input_envelope,
3272            "request_id": request_id,
3273        }));
3274        let path = match run_id {
3275            Some(run_id) => {
3276                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3277            }
3278            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3279        };
3280        let receipt = self
3281            .request_json(
3282                reqwest::Method::POST,
3283                &path,
3284                RequestProtocol::ControlPlane,
3285                Some(&body),
3286            )
3287            .await?;
3288        Ok(with_request_id(receipt, request_id))
3289    }
3290
3291    /// Close the current run as cancelled immediately.
3292    ///
3293    /// Server revokes open tasks and timers without resuming workflow code for
3294    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3295    /// request on a supporting runtime and opted-in worker.
3296    pub async fn cancel_workflow(
3297        &self,
3298        workflow_id: &str,
3299        options: WorkflowCommandOptions,
3300    ) -> Result<WorkflowCommandResult> {
3301        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3302            .await
3303    }
3304
3305    /// Close the selected run as cancelled, only if `run_id` is still current.
3306    pub async fn cancel_workflow_run(
3307        &self,
3308        workflow_id: &str,
3309        run_id: &str,
3310        options: WorkflowCommandOptions,
3311    ) -> Result<WorkflowCommandResult> {
3312        self.workflow_command(
3313            workflow_id,
3314            Some(run_id),
3315            WorkflowCommandKind::Cancel,
3316            options,
3317        )
3318        .await
3319    }
3320
3321    /// Forcefully terminate the current run for an instance.
3322    pub async fn terminate_workflow(
3323        &self,
3324        workflow_id: &str,
3325        options: WorkflowCommandOptions,
3326    ) -> Result<WorkflowCommandResult> {
3327        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3328            .await
3329    }
3330
3331    /// Forcefully terminate only if `run_id` is still current.
3332    pub async fn terminate_workflow_run(
3333        &self,
3334        workflow_id: &str,
3335        run_id: &str,
3336        options: WorkflowCommandOptions,
3337    ) -> Result<WorkflowCommandResult> {
3338        self.workflow_command(
3339            workflow_id,
3340            Some(run_id),
3341            WorkflowCommandKind::Terminate,
3342            options,
3343        )
3344        .await
3345    }
3346
3347    /// Continue a failed run from its recorded activity failure boundary.
3348    pub async fn redrive_workflow_run(
3349        &self,
3350        workflow_id: &str,
3351        failed_run_id: &str,
3352        request_id: Option<&str>,
3353    ) -> Result<WorkflowRedriveResult> {
3354        let body = request_id
3355            .map(|id| json!({"request_id": id}))
3356            .unwrap_or_else(|| json!({}));
3357        let data: Value = self
3358            .request_json(
3359                reqwest::Method::POST,
3360                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3361                RequestProtocol::ControlPlane,
3362                Some(&body),
3363            )
3364            .await?;
3365        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3366            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3367        {
3368            return Err(Error::Codec(
3369                "redrive response was not accepted".to_string(),
3370            ));
3371        }
3372        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3373            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3374        {
3375            return Err(Error::Codec(
3376                "redrive response does not match the requested source run".to_string(),
3377            ));
3378        }
3379        let run_id = data
3380            .get("run_id")
3381            .and_then(Value::as_str)
3382            .filter(|id| !id.is_empty() && *id != failed_run_id)
3383            .ok_or_else(|| {
3384                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3385            })?;
3386        let resume_step_sequence = data
3387            .get("resume_step_sequence")
3388            .and_then(Value::as_u64)
3389            .filter(|sequence| *sequence > 0)
3390            .ok_or_else(|| {
3391                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3392            })?;
3393        Ok(WorkflowRedriveResult {
3394            workflow_id: workflow_id.to_string(),
3395            source_run_id: failed_run_id.to_string(),
3396            run_id: run_id.to_string(),
3397            resume_step_sequence,
3398            raw: data,
3399        })
3400    }
3401
3402    async fn workflow_command(
3403        &self,
3404        workflow_id: &str,
3405        run_id: Option<&str>,
3406        command: WorkflowCommandKind,
3407        options: WorkflowCommandOptions,
3408    ) -> Result<WorkflowCommandResult> {
3409        #[cfg(feature = "telemetry")]
3410        let body = if command == WorkflowCommandKind::Cancel {
3411            self.with_observability_context(serde_json::to_value(&options)?)
3412        } else {
3413            serde_json::to_value(&options)?
3414        };
3415        #[cfg(not(feature = "telemetry"))]
3416        let body = &options;
3417        let path = match run_id {
3418            Some(run_id) => format!(
3419                "/workflows/{workflow_id}/runs/{run_id}/{}",
3420                command.as_str()
3421            ),
3422            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3423        };
3424        let data = match self
3425            .request_json(
3426                reqwest::Method::POST,
3427                &path,
3428                RequestProtocol::ControlPlane,
3429                Some(&body),
3430            )
3431            .await
3432        {
3433            Ok(data) => data,
3434            Err(Error::Http { status, body }) => {
3435                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3436                    command,
3437                    status,
3438                    body,
3439                    workflow_id,
3440                    run_id,
3441                )));
3442            }
3443            Err(error) => return Err(error),
3444        };
3445
3446        Ok(workflow_command_result(command, data, workflow_id, run_id))
3447    }
3448
3449    /// Execute a named, read-only query against a running or completed workflow.
3450    ///
3451    /// Arguments and results use the platform payload envelope. Server and
3452    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3453    /// reason, HTTP status, and original response body.
3454    pub async fn query_workflow<T: Serialize>(
3455        &self,
3456        workflow_id: &str,
3457        query_name: &str,
3458        input: T,
3459    ) -> Result<Value> {
3460        self.query_workflow_target(workflow_id, None, query_name, input)
3461            .await
3462    }
3463
3464    /// Query only if `run_id` is still current, preventing accidental retargeting.
3465    pub async fn query_workflow_run<T: Serialize>(
3466        &self,
3467        workflow_id: &str,
3468        run_id: &str,
3469        query_name: &str,
3470        input: T,
3471    ) -> Result<Value> {
3472        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3473            .await
3474    }
3475
3476    /// Query a workflow and return the lossless fixed Avro Value result.
3477    pub async fn query_workflow_avro_value<T: Serialize>(
3478        &self,
3479        workflow_id: &str,
3480        query_name: &str,
3481        input: T,
3482    ) -> Result<AvroValue> {
3483        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3484            .await
3485    }
3486
3487    /// Query a selected run and return the lossless fixed Avro Value result.
3488    pub async fn query_workflow_run_avro_value<T: Serialize>(
3489        &self,
3490        workflow_id: &str,
3491        run_id: &str,
3492        query_name: &str,
3493        input: T,
3494    ) -> Result<AvroValue> {
3495        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3496            .await
3497    }
3498
3499    async fn query_workflow_avro_value_target<T: Serialize>(
3500        &self,
3501        workflow_id: &str,
3502        run_id: Option<&str>,
3503        query_name: &str,
3504        input: T,
3505    ) -> Result<AvroValue> {
3506        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3507        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3508        let path = match run_id {
3509            Some(run_id) => {
3510                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3511            }
3512            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3513        };
3514        let response: Value = match self
3515            .request_json(
3516                reqwest::Method::POST,
3517                &path,
3518                RequestProtocol::ControlPlane,
3519                Some(&body),
3520            )
3521            .await
3522        {
3523            Ok(response) => response,
3524            Err(Error::Http { status, body }) => {
3525                return Err(Error::QueryFailed(query_failure(status, body)));
3526            }
3527            Err(error) => return Err(error),
3528        };
3529
3530        let envelope = response
3531            .get("result_envelope")
3532            .filter(|envelope| !envelope.is_null())
3533            .ok_or_else(|| {
3534                Error::Codec(
3535                    "missing_payload_envelope: typed query result requires result_envelope"
3536                        .to_string(),
3537                )
3538            })?;
3539        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3540    }
3541
3542    async fn query_workflow_target<T: Serialize>(
3543        &self,
3544        workflow_id: &str,
3545        run_id: Option<&str>,
3546        query_name: &str,
3547        input: T,
3548    ) -> Result<Value> {
3549        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3550        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3551        let body = json!({
3552            "input": input_envelope
3553        });
3554        let path = match run_id {
3555            Some(run_id) => {
3556                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3557            }
3558            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3559        };
3560        let response: Value = match self
3561            .request_json(
3562                reqwest::Method::POST,
3563                &path,
3564                RequestProtocol::ControlPlane,
3565                Some(&body),
3566            )
3567            .await
3568        {
3569            Ok(response) => response,
3570            Err(Error::Http { status, body }) => {
3571                return Err(Error::QueryFailed(query_failure(status, body)));
3572            }
3573            Err(error) => return Err(error),
3574        };
3575
3576        if let Some(envelope) = response
3577            .get("result_envelope")
3578            .filter(|envelope| !envelope.is_null())
3579        {
3580            return decode_wire_value(envelope, DEFAULT_CODEC);
3581        }
3582
3583        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3584    }
3585
3586    /// Send a synchronous update using fixed Avro Value arguments.
3587    ///
3588    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
3589    /// `request_id` body field; `None` generates one with
3590    /// [`Client::generate_update_request_id`]. A Server that already retains the
3591    /// key for the same update intent returns the original update's receipt and
3592    /// result instead of admitting a second update; a different intent is
3593    /// refused with [`Error::is_request_id_conflict`].
3594    pub async fn update_workflow<T: Serialize>(
3595        &self,
3596        workflow_id: &str,
3597        update_name: &str,
3598        input: T,
3599        request_id: Option<&str>,
3600    ) -> Result<Value> {
3601        let response = self
3602            .update_workflow_response(workflow_id, update_name, input, request_id)
3603            .await?;
3604        if let Some(envelope) = response
3605            .get("result_envelope")
3606            .filter(|envelope| !envelope.is_null())
3607        {
3608            return decode_wire_value(envelope, DEFAULT_CODEC);
3609        }
3610        Ok(response.get("result").cloned().unwrap_or(response))
3611    }
3612
3613    /// Send a synchronous update and retain a bytes-capable Avro result.
3614    pub async fn update_workflow_avro_value<T: Serialize>(
3615        &self,
3616        workflow_id: &str,
3617        update_name: &str,
3618        input: T,
3619        request_id: Option<&str>,
3620    ) -> Result<AvroValue> {
3621        let response = self
3622            .update_workflow_response(workflow_id, update_name, input, request_id)
3623            .await?;
3624        let envelope = response
3625            .get("result_envelope")
3626            .filter(|envelope| !envelope.is_null())
3627            .ok_or_else(|| {
3628                Error::Codec(
3629                    "missing_payload_envelope: typed update result requires result_envelope"
3630                        .to_string(),
3631                )
3632            })?;
3633        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3634    }
3635
3636    async fn update_workflow_response<T: Serialize>(
3637        &self,
3638        workflow_id: &str,
3639        update_name: &str,
3640        input: T,
3641        request_id: Option<&str>,
3642    ) -> Result<Value> {
3643        let request_id = match request_id {
3644            Some(request_id) => {
3645                validate_request_id(request_id)?;
3646                request_id.to_string()
3647            }
3648            None => Self::generate_update_request_id(),
3649        };
3650        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3651        let body = self.with_observability_context(json!({
3652            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3653            "wait_for": "completed",
3654            "request_id": request_id,
3655        }));
3656        let receipt = self
3657            .request_json(
3658                reqwest::Method::POST,
3659                &format!("/workflows/{workflow_id}/update/{update_name}"),
3660                RequestProtocol::ControlPlane,
3661                Some(&body),
3662            )
3663            .await?;
3664        Ok(with_request_id(receipt, &request_id))
3665    }
3666
3667    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3668        let path = format!("/workflows/{workflow_id}");
3669        let mut data: WorkflowDescription = self
3670            .request_json(
3671                reqwest::Method::GET,
3672                &path,
3673                RequestProtocol::ControlPlane,
3674                Option::<&Value>::None,
3675            )
3676            .await?;
3677        data.decode_payloads()?;
3678        Ok(data)
3679    }
3680
3681    /// Describe one selected run, including historical terminal runs.
3682    pub async fn describe_workflow_run(
3683        &self,
3684        workflow_id: &str,
3685        run_id: &str,
3686    ) -> Result<WorkflowDescription> {
3687        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3688        let mut data: WorkflowDescription = self
3689            .request_json(
3690                reqwest::Method::GET,
3691                &path,
3692                RequestProtocol::ControlPlane,
3693                Option::<&Value>::None,
3694            )
3695            .await?;
3696        data.decode_payloads()?;
3697        Ok(data)
3698    }
3699
3700    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3701        let mut path = format!(
3702            "/workflows/{}/runs/{}/streams",
3703            percent_encode_path_segment(workflow_id),
3704            percent_encode_path_segment(run_id),
3705        );
3706        if let Some(stream_name) = stream_name {
3707            path.push('/');
3708            path.push_str(&percent_encode_path_segment(stream_name));
3709        }
3710        path
3711    }
3712
3713    /// List the run-scoped output streams already opened by a workflow.
3714    pub async fn list_workflow_streams(
3715        &self,
3716        workflow_id: &str,
3717        run_id: &str,
3718    ) -> Result<Vec<WorkflowStreamDescription>> {
3719        let response: WorkflowStreamListResponse = self
3720            .request_json(
3721                reqwest::Method::GET,
3722                &Self::workflow_stream_path(workflow_id, run_id, None),
3723                RequestProtocol::ControlPlane,
3724                Option::<&Value>::None,
3725            )
3726            .await?;
3727        Ok(response.streams)
3728    }
3729
3730    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3731    pub async fn describe_workflow_stream(
3732        &self,
3733        workflow_id: &str,
3734        run_id: &str,
3735        stream_name: &str,
3736    ) -> Result<WorkflowStreamDescription> {
3737        let response: WorkflowStreamDescriptionResponse = self
3738            .request_json(
3739                reqwest::Method::GET,
3740                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3741                RequestProtocol::ControlPlane,
3742                Option::<&Value>::None,
3743            )
3744            .await?;
3745        Ok(response.stream)
3746    }
3747
3748    /// Read one bounded page beginning at a zero-based offset.
3749    ///
3750    /// Delivery is at least once: persist `next_offset` only after processing
3751    /// the page. The future is cancellation-safe; dropping it cancels the
3752    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3753    /// service contract.
3754    pub async fn subscribe_workflow_stream(
3755        &self,
3756        workflow_id: &str,
3757        run_id: &str,
3758        stream_name: &str,
3759        from_offset: u64,
3760        max_items: usize,
3761        wait: Duration,
3762    ) -> Result<WorkflowStreamPage> {
3763        let max_items = max_items.clamp(1, 500);
3764        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3765        let path = format!(
3766            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3767            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3768        );
3769        let response: WorkflowStreamPageResponse = self
3770            .request_json_with_timeout(
3771                reqwest::Method::GET,
3772                &path,
3773                RequestProtocol::ControlPlane,
3774                Option::<&Value>::None,
3775                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3776            )
3777            .await?;
3778
3779        let items = response
3780            .items
3781            .into_iter()
3782            .map(|raw| {
3783                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3784                let envelope = raw.get("payload").cloned();
3785                let payload = envelope
3786                    .as_ref()
3787                    .filter(|value| value.get("blob").is_some())
3788                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3789                    .transpose()?
3790                    .map(AvroValue::into_json)
3791                    .transpose()?;
3792                Ok(WorkflowStreamItem {
3793                    offset,
3794                    payload,
3795                    payload_envelope: envelope,
3796                    payload_reference: raw
3797                        .get("payload_reference")
3798                        .and_then(Value::as_str)
3799                        .map(str::to_string),
3800                    payload_codec: raw
3801                        .get("payload_codec")
3802                        .and_then(Value::as_str)
3803                        .map(str::to_string),
3804                    idempotency_key: raw
3805                        .get("idempotency_key")
3806                        .and_then(Value::as_str)
3807                        .map(str::to_string),
3808                    item_type: raw
3809                        .get("item_type")
3810                        .and_then(Value::as_str)
3811                        .map(str::to_string),
3812                    content_type: raw
3813                        .get("content_type")
3814                        .and_then(Value::as_str)
3815                        .map(str::to_string),
3816                    origin: raw
3817                        .get("origin")
3818                        .and_then(Value::as_str)
3819                        .map(str::to_string),
3820                    origin_reference: raw
3821                        .get("origin_reference")
3822                        .and_then(Value::as_str)
3823                        .map(str::to_string),
3824                    emitted_at: raw
3825                        .get("emitted_at")
3826                        .and_then(Value::as_str)
3827                        .map(str::to_string),
3828                    raw,
3829                })
3830            })
3831            .collect::<Result<Vec<_>>>()?;
3832        Ok(WorkflowStreamPage {
3833            stream: response.stream,
3834            items,
3835            next_offset: response.next_offset,
3836            terminal: response.terminal,
3837        })
3838    }
3839
3840    /// Append inline Avro envelopes or opaque external payload references.
3841    pub async fn append_workflow_stream(
3842        &self,
3843        workflow_id: &str,
3844        run_id: &str,
3845        stream_name: &str,
3846        items: &[WorkflowStreamAppendItem],
3847        max_pending_items: Option<u64>,
3848    ) -> Result<WorkflowStreamAppendResult> {
3849        if items.is_empty() {
3850            return Err(Error::Codec(
3851                "workflow_stream_items_empty: append requires at least one item".to_string(),
3852            ));
3853        }
3854        let mut body = json!({
3855            "items": items
3856                .iter()
3857                .map(|item| item.wire_value(None))
3858                .collect::<Vec<_>>(),
3859        });
3860        if let Some(max_pending_items) = max_pending_items {
3861            if max_pending_items == 0 {
3862                return Err(Error::Codec(
3863                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3864                        .to_string(),
3865                ));
3866            }
3867            body["max_pending_items"] = json!(max_pending_items);
3868        }
3869        let response: WorkflowStreamAppendResponse = self
3870            .request_json(
3871                reqwest::Method::POST,
3872                &format!(
3873                    "{}/items",
3874                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3875                ),
3876                RequestProtocol::ControlPlane,
3877                Some(&body),
3878            )
3879            .await?;
3880        Ok(WorkflowStreamAppendResult {
3881            stream: response.stream,
3882            accepted_offsets: response.accepted_offsets,
3883            accepted: response.accepted,
3884            deduped: response.deduped,
3885        })
3886    }
3887
3888    /// Close a stream, or mark it errored when `error_reason` is supplied.
3889    pub async fn close_workflow_stream(
3890        &self,
3891        workflow_id: &str,
3892        run_id: &str,
3893        stream_name: &str,
3894        error_reason: Option<&str>,
3895        retention_seconds: Option<u64>,
3896    ) -> Result<WorkflowStreamDescription> {
3897        let mut body = json!({});
3898        if let Some(error_reason) = error_reason {
3899            body["error_reason"] = json!(error_reason);
3900        }
3901        if let Some(retention_seconds) = retention_seconds {
3902            if retention_seconds == 0 {
3903                return Err(Error::Codec(
3904                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3905                        .to_string(),
3906                ));
3907            }
3908            body["retention_seconds"] = json!(retention_seconds);
3909        }
3910        let response: WorkflowStreamDescriptionResponse = self
3911            .request_json(
3912                reqwest::Method::POST,
3913                &format!(
3914                    "{}/close",
3915                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3916                ),
3917                RequestProtocol::ControlPlane,
3918                Some(&body),
3919            )
3920            .await?;
3921        Ok(response.stream)
3922    }
3923
3924    pub async fn register_worker(
3925        &self,
3926        worker_id: &str,
3927        task_queue: &str,
3928        supported_workflow_types: Vec<String>,
3929        supported_activity_types: Vec<String>,
3930        max_concurrent_workflow_tasks: usize,
3931        max_concurrent_activity_tasks: usize,
3932    ) -> Result<RegisterWorkerResponse> {
3933        self.register_worker_with_capabilities(
3934            worker_id,
3935            task_queue,
3936            supported_workflow_types,
3937            supported_activity_types,
3938            max_concurrent_workflow_tasks,
3939            max_concurrent_activity_tasks,
3940            Vec::new(),
3941        )
3942        .await
3943    }
3944
3945    /// Register a worker and explicitly advertise additive worker capabilities.
3946    pub async fn register_worker_with_capabilities(
3947        &self,
3948        worker_id: &str,
3949        task_queue: &str,
3950        supported_workflow_types: Vec<String>,
3951        supported_activity_types: Vec<String>,
3952        max_concurrent_workflow_tasks: usize,
3953        max_concurrent_activity_tasks: usize,
3954        capabilities: Vec<String>,
3955    ) -> Result<RegisterWorkerResponse> {
3956        self.register_worker_with_command_contracts(
3957            worker_id,
3958            task_queue,
3959            supported_workflow_types,
3960            supported_activity_types,
3961            max_concurrent_workflow_tasks,
3962            max_concurrent_activity_tasks,
3963            capabilities,
3964            Value::Object(serde_json::Map::new()),
3965        )
3966        .await
3967    }
3968
3969    /// Register a worker and advertise its named query and update handlers.
3970    ///
3971    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3972    /// so a workflow contract with a non-empty or malformed
3973    /// `update_validators` declaration returns
3974    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3975    #[allow(clippy::too_many_arguments)]
3976    pub async fn register_worker_with_command_contracts(
3977        &self,
3978        worker_id: &str,
3979        task_queue: &str,
3980        supported_workflow_types: Vec<String>,
3981        supported_activity_types: Vec<String>,
3982        max_concurrent_workflow_tasks: usize,
3983        max_concurrent_activity_tasks: usize,
3984        capabilities: Vec<String>,
3985        workflow_command_contracts: Value,
3986    ) -> Result<RegisterWorkerResponse> {
3987        self.register_worker_with_definition_fingerprints(
3988            worker_id,
3989            task_queue,
3990            supported_workflow_types,
3991            supported_activity_types,
3992            max_concurrent_workflow_tasks,
3993            max_concurrent_activity_tasks,
3994            capabilities,
3995            workflow_command_contracts,
3996            None,
3997        )
3998        .await
3999    }
4000
4001    #[allow(clippy::too_many_arguments)]
4002    async fn register_worker_with_definition_fingerprints(
4003        &self,
4004        worker_id: &str,
4005        task_queue: &str,
4006        supported_workflow_types: Vec<String>,
4007        supported_activity_types: Vec<String>,
4008        max_concurrent_workflow_tasks: usize,
4009        max_concurrent_activity_tasks: usize,
4010        capabilities: Vec<String>,
4011        workflow_command_contracts: Value,
4012        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
4013    ) -> Result<RegisterWorkerResponse> {
4014        if let Some(contracts) = workflow_command_contracts.as_object() {
4015            for (workflow_type, contract) in contracts {
4016                let Some(update_validators) = contract.get("update_validators") else {
4017                    continue;
4018                };
4019                if !update_validators
4020                    .as_array()
4021                    .is_some_and(|validators| validators.is_empty())
4022                {
4023                    return Err(Error::UnsupportedUpdateValidators {
4024                        workflow_type: workflow_type.clone(),
4025                    });
4026                }
4027            }
4028        }
4029
4030        let mut body = json!({
4031            "worker_id": worker_id,
4032            "task_queue": task_queue,
4033            "runtime": "rust",
4034            "sdk_version": SDK_VERSION,
4035            "supported_workflow_types": supported_workflow_types,
4036            "supported_activity_types": supported_activity_types,
4037            "capabilities": capabilities,
4038            "capability_manifest": portable_worker_affinity_capability_manifest(),
4039            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4040            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4041        });
4042        if capabilities
4043            .iter()
4044            .any(|capability| capability == "nexus_cooperative_cancellation")
4045        {
4046            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4047                "supported":true, "minimum_protocol_version":"1.20",
4048                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4049            });
4050        }
4051        if let Some(build_id) = &self.worker_build_id {
4052            if build_id.is_empty() || build_id.len() > 255 {
4053                return Err(Error::WorkerLoop(
4054                    "worker build ID must contain 1 to 255 bytes".into(),
4055                ));
4056            }
4057            body["build_id"] = json!(build_id);
4058        }
4059        if self.sticky_cache.is_some() {
4060            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4061                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4062                "implementation":"bounded_durable_history_cache"});
4063        }
4064        if self.local_activities_enabled {
4065            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4066                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4067        }
4068        if self.worker_sessions_enabled {
4069            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4070                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4071            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4072        }
4073        if workflow_command_contracts
4074            .as_object()
4075            .is_some_and(|contracts| !contracts.is_empty())
4076        {
4077            body["workflow_command_contracts"] = workflow_command_contracts;
4078        }
4079        if let Some(fingerprints) = workflow_definition_fingerprints {
4080            body["workflow_definition_fingerprints"] = json!(fingerprints);
4081        }
4082
4083        let response: Value = self
4084            .request_json(
4085                reqwest::Method::POST,
4086                "/worker/register",
4087                RequestProtocol::DefaultWorker,
4088                Some(&body),
4089            )
4090            .await?;
4091        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4092            self.observe_activity_lease_capabilities(&response["server_capabilities"]);
4093        }
4094        if self.sticky_cache.is_some() {
4095            self.confirm_sticky_registration(&response, worker_id, task_queue)
4096                .await?;
4097        }
4098        if self.local_activities_enabled || self.worker_sessions_enabled {
4099            let compatible = response["registered"].as_bool() == Some(true)
4100                && response["worker_id"].as_str() == Some(worker_id)
4101                && response["namespace"].as_str() == Some(self.namespace.as_str())
4102                && response["task_queue"].as_str() == Some(task_queue)
4103                && response["protocol_version"]
4104                    .as_str()
4105                    .and_then(|version| version.strip_prefix("1."))
4106                    .and_then(|minor| minor.parse::<u64>().ok())
4107                    .is_some_and(|minor| minor >= 18)
4108                && (!self.local_activities_enabled
4109                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4110                        == Some(true))
4111                && (!self.worker_sessions_enabled
4112                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4113                        == Some(true)
4114                        && response["capabilities"].as_array().is_some_and(|accepted| {
4115                            capabilities.iter().all(|capability| {
4116                                accepted
4117                                    .iter()
4118                                    .any(|value| value.as_str() == Some(capability.as_str()))
4119                            })
4120                        })));
4121            if !compatible {
4122                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4123                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4124                } else {
4125                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4126                });
4127                if response["registered"] == true
4128                    && response["worker_id"].as_str() == Some(worker_id)
4129                {
4130                    if let Err(deregistration) =
4131                        self.deregister_worker_registration(worker_id).await
4132                    {
4133                        return Err(Error::WorkerShutdown {
4134                            primary: Box::new(error),
4135                            deregistration: Box::new(deregistration),
4136                        });
4137                    }
4138                }
4139                return Err(error);
4140            }
4141        }
4142        if self.cooperative_worker_protocol {
4143            let compatible = response["registered"].as_bool() == Some(true)
4144                && response["worker_id"].as_str() == Some(worker_id)
4145                && response["namespace"].as_str() == Some(self.namespace.as_str())
4146                && response["task_queue"].as_str() == Some(task_queue)
4147                && response["protocol_version"]
4148                    .as_str()
4149                    .is_some_and(cooperative_cancellation::supports_protocol)
4150                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4151                    == Some(true)
4152                && (!capabilities
4153                    .iter()
4154                    .any(|capability| capability == "nexus_cooperative_cancellation")
4155                    || nexus::installed_cooperation(&response["server_capabilities"]))
4156                && response["capabilities"].as_array().is_some_and(|accepted| {
4157                    capabilities.iter().all(|capability| {
4158                        accepted
4159                            .iter()
4160                            .any(|value| value.as_str() == Some(capability.as_str()))
4161                    })
4162                });
4163            if !compatible {
4164                let error = Error::CooperativeCancellationUnavailable(
4165                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4166                );
4167                if response["registered"].as_bool() == Some(true)
4168                    && response["worker_id"].as_str() == Some(worker_id)
4169                {
4170                    if let Err(deregistration) =
4171                        self.deregister_worker_registration(worker_id).await
4172                    {
4173                        return Err(Error::WorkerShutdown {
4174                            primary: Box::new(error),
4175                            deregistration: Box::new(deregistration),
4176                        });
4177                    }
4178                }
4179                return Err(error);
4180            }
4181        }
4182        Ok(serde_json::from_value(response)?)
4183    }
4184
4185    /// Gracefully remove one worker's registration through the worker plane.
4186    ///
4187    /// This operation is separate from operator-facing worker management. It
4188    /// uses worker-protocol authentication and returns the server's lease
4189    /// recovery result.
4190    pub async fn deregister_worker_registration(
4191        &self,
4192        worker_id: &str,
4193    ) -> Result<WorkerDeregistrationEnvelope> {
4194        let path = format!(
4195            "/worker/registrations/{}",
4196            percent_encode_path_segment(worker_id)
4197        );
4198        self.request_json(
4199            reqwest::Method::DELETE,
4200            &path,
4201            RequestProtocol::DefaultWorker,
4202            Option::<&Value>::None,
4203        )
4204        .await
4205    }
4206
4207    /// Long-poll for an ephemeral, read-only workflow query task.
4208    pub async fn poll_query_task(
4209        &self,
4210        worker_id: &str,
4211        task_queue: &str,
4212        timeout: Duration,
4213    ) -> Result<Option<QueryTask>> {
4214        Ok(self
4215            .poll_query_task_response(worker_id, task_queue, timeout)
4216            .await?
4217            .task)
4218    }
4219
4220    /// Poll a query task while preserving server stop and drain metadata.
4221    pub async fn poll_query_task_response(
4222        &self,
4223        worker_id: &str,
4224        task_queue: &str,
4225        timeout: Duration,
4226    ) -> Result<PollQueryTaskResponse> {
4227        let poll_request_id = unique_request_id("rust-query-poll");
4228        self.poll_query_task_response_with_request_id(
4229            worker_id,
4230            task_queue,
4231            timeout,
4232            &poll_request_id,
4233            1,
4234        )
4235        .await
4236    }
4237
4238    async fn poll_query_task_response_with_request_id(
4239        &self,
4240        worker_id: &str,
4241        task_queue: &str,
4242        timeout: Duration,
4243        poll_request_id: &str,
4244        transport_retries: usize,
4245    ) -> Result<PollQueryTaskResponse> {
4246        let timeout_seconds = long_poll_timeout_seconds(timeout);
4247        let body = json!({
4248            "worker_id": worker_id,
4249            "task_queue": task_queue,
4250            "poll_request_id": poll_request_id,
4251            "timeout_seconds": timeout_seconds,
4252        });
4253        self.poll_request_json(
4254            "/worker/query-tasks/poll",
4255            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4256            &body,
4257            timeout + Duration::from_secs(5),
4258            transport_retries,
4259        )
4260        .await
4261    }
4262
4263    /// Complete a query task without appending workflow history.
4264    pub async fn complete_query_task<T: Serialize>(
4265        &self,
4266        query_task_id: &str,
4267        lease_owner: &str,
4268        query_task_attempt: u64,
4269        result: T,
4270        codec: &str,
4271    ) -> Result<Value> {
4272        let typed_result = AvroValue::from_serialize(&result)?;
4273        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4274        self.complete_query_task_with_envelope(
4275            query_task_id,
4276            lease_owner,
4277            query_task_attempt,
4278            typed_result.into_json()?,
4279            result_envelope,
4280        )
4281        .await
4282    }
4283
4284    async fn complete_query_task_with_envelope(
4285        &self,
4286        query_task_id: &str,
4287        lease_owner: &str,
4288        query_task_attempt: u64,
4289        result: Value,
4290        result_envelope: Value,
4291    ) -> Result<Value> {
4292        let body = json!({
4293            "lease_owner": lease_owner,
4294            "query_task_attempt": query_task_attempt,
4295            "result": result,
4296            "result_envelope": result_envelope,
4297        });
4298        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4299        let response = self
4300            .request_json(
4301                reqwest::Method::POST,
4302                &path,
4303                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4304                Some(&body),
4305            )
4306            .await;
4307        query_task_response(response)
4308    }
4309
4310    /// Report a stable machine-readable query-task failure.
4311    pub async fn fail_query_task(
4312        &self,
4313        query_task_id: &str,
4314        lease_owner: &str,
4315        query_task_attempt: u64,
4316        message: impl Into<String>,
4317        reason: impl Into<String>,
4318        failure_type: impl Into<String>,
4319    ) -> Result<Value> {
4320        let body = json!({
4321            "lease_owner": lease_owner,
4322            "query_task_attempt": query_task_attempt,
4323            "failure": {
4324                "message": message.into(),
4325                "reason": reason.into(),
4326                "type": failure_type.into(),
4327            }
4328        });
4329        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4330        let response = self
4331            .request_json(
4332                reqwest::Method::POST,
4333                &path,
4334                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4335                Some(&body),
4336            )
4337            .await;
4338        query_task_response(response)
4339    }
4340
4341    pub async fn heartbeat_worker(
4342        &self,
4343        worker_id: &str,
4344        workflow_available: usize,
4345        activity_available: usize,
4346    ) -> Result<Value> {
4347        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4348            .await
4349    }
4350
4351    async fn heartbeat_worker_with_sessions(
4352        &self,
4353        worker_id: &str,
4354        workflow_available: usize,
4355        activity_available: usize,
4356        session_available: Option<usize>,
4357    ) -> Result<Value> {
4358        let mut body = json!({
4359            "worker_id": worker_id,
4360            "task_slots": {
4361                "workflow_available": workflow_available,
4362                "activity_available": activity_available
4363            },
4364            "process_metrics": {
4365                "process_id": std::process::id(),
4366                "process_uptime_seconds": 0
4367            }
4368        });
4369
4370        if let Some(available) = session_available {
4371            body["task_slots"]["session_available"] = json!(available);
4372        }
4373
4374        self.request_json(
4375            reqwest::Method::POST,
4376            "/worker/heartbeat",
4377            RequestProtocol::DefaultWorker,
4378            Some(&body),
4379        )
4380        .await
4381    }
4382
4383    pub async fn poll_workflow_task(
4384        &self,
4385        worker_id: &str,
4386        task_queue: &str,
4387        timeout: Duration,
4388    ) -> Result<Option<WorkflowTask>> {
4389        Ok(self
4390            .poll_workflow_task_response(worker_id, task_queue, timeout)
4391            .await?
4392            .task)
4393    }
4394
4395    pub async fn poll_workflow_task_response(
4396        &self,
4397        worker_id: &str,
4398        task_queue: &str,
4399        timeout: Duration,
4400    ) -> Result<PollWorkflowTaskResponse> {
4401        let poll_request_id = unique_request_id("rust-workflow-poll");
4402        self.poll_workflow_task_response_with_request_id(
4403            worker_id,
4404            task_queue,
4405            timeout,
4406            &poll_request_id,
4407            1,
4408        )
4409        .await
4410    }
4411
4412    async fn poll_workflow_task_response_with_request_id(
4413        &self,
4414        worker_id: &str,
4415        task_queue: &str,
4416        timeout: Duration,
4417        poll_request_id: &str,
4418        transport_retries: usize,
4419    ) -> Result<PollWorkflowTaskResponse> {
4420        let body = json!({
4421            "worker_id": worker_id,
4422            "task_queue": task_queue,
4423            "poll_request_id": poll_request_id,
4424            "timeout_seconds": long_poll_timeout_seconds(timeout),
4425            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4426        });
4427        let mut wire: Value = self
4428            .poll_request_json_unresolved(
4429                "/worker/workflow-tasks/poll",
4430                RequestProtocol::DefaultWorker,
4431                &body,
4432                timeout + Duration::from_secs(5),
4433                transport_retries,
4434            )
4435            .await?;
4436        let claim =
4437            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4438        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4439            self.resolve_runtime_payloads(
4440                &mut wire,
4441                "/worker/workflow-tasks/poll",
4442                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4443            )
4444            .await?;
4445            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4446            if let Some(task) = data.task.as_mut() {
4447                self.fetch_remaining_workflow_history(worker_id, task)
4448                    .await?;
4449            }
4450            Ok(data)
4451        })
4452        .await?;
4453        Ok(data)
4454    }
4455
4456    async fn fetch_remaining_workflow_history(
4457        &self,
4458        worker_id: &str,
4459        task: &mut WorkflowTask,
4460    ) -> Result<()> {
4461        let mut next_token = task.next_history_page_token.clone();
4462        let mut seen = BTreeSet::new();
4463
4464        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4465            if seen.len() >= 128 || !seen.insert(token.clone()) {
4466                return Err(Error::Codec(
4467                    "workflow history pagination exceeded its page bound or repeated a token"
4468                        .into(),
4469                ));
4470            }
4471            let lease_owner = task
4472                .lease_owner
4473                .clone()
4474                .unwrap_or_else(|| worker_id.to_string());
4475            let page = self
4476                .workflow_task_history_page(
4477                    &task.task_id,
4478                    &lease_owner,
4479                    task.workflow_task_attempt,
4480                    &token,
4481                )
4482                .await?;
4483
4484            task.append_history_page(page);
4485
4486            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4487                return Err(Error::Codec(
4488                    "workflow history pagination returned the same page token".to_string(),
4489                ));
4490            }
4491
4492            next_token = task.next_history_page_token.clone();
4493        }
4494
4495        Ok(())
4496    }
4497
4498    async fn workflow_task_history_page(
4499        &self,
4500        task_id: &str,
4501        lease_owner: &str,
4502        workflow_task_attempt: u64,
4503        next_history_page_token: &str,
4504    ) -> Result<WorkflowTaskHistoryPage> {
4505        let body = json!({
4506            "lease_owner": lease_owner,
4507            "workflow_task_attempt": workflow_task_attempt,
4508            "next_history_page_token": next_history_page_token
4509        });
4510        let path = format!("/worker/workflow-tasks/{task_id}/history");
4511
4512        self.request_json(
4513            reqwest::Method::POST,
4514            &path,
4515            RequestProtocol::DefaultWorker,
4516            Some(&body),
4517        )
4518        .await
4519    }
4520
4521    pub async fn complete_workflow_task(
4522        &self,
4523        task_id: &str,
4524        lease_owner: &str,
4525        workflow_task_attempt: u64,
4526        commands: Vec<Value>,
4527    ) -> Result<Value> {
4528        self.complete_workflow_task_with_message_streams(
4529            task_id,
4530            lease_owner,
4531            workflow_task_attempt,
4532            commands,
4533            Vec::new(),
4534            Vec::new(),
4535            None,
4536        )
4537        .await
4538    }
4539
4540    #[allow(clippy::too_many_arguments)]
4541    async fn complete_workflow_task_with_message_streams(
4542        &self,
4543        task_id: &str,
4544        lease_owner: &str,
4545        workflow_task_attempt: u64,
4546        commands: Vec<Value>,
4547        message_stream_cursors: Vec<Value>,
4548        message_stream_waits: Vec<Value>,
4549        sticky_cache: Option<Value>,
4550    ) -> Result<Value> {
4551        validate_workflow_task_commands(&commands)?;
4552        let has_message_stream_metadata =
4553            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4554        if has_message_stream_metadata
4555            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4556        {
4557            return Err(Error::Codec(
4558                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4559                    .to_string(),
4560            ));
4561        }
4562        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4563            &commands,
4564            has_message_stream_metadata,
4565        );
4566        let protocol_version = if sticky_cache.is_some()
4567            && protocol_version
4568                .strip_prefix("1.")
4569                .and_then(|minor| minor.parse::<u64>().ok())
4570                .is_some_and(|minor| minor < 18)
4571        {
4572            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4573        } else {
4574            protocol_version
4575        };
4576        let mut body = json!({
4577            "lease_owner": lease_owner,
4578            "workflow_task_attempt": workflow_task_attempt,
4579            "commands": commands
4580        });
4581        #[cfg(feature = "telemetry")]
4582        if self.observability_context_supported.load(Ordering::SeqCst)
4583            && opentelemetry::Context::current()
4584                .get::<telemetry::ExecutionFields>()
4585                .is_some()
4586        {
4587            if let Some(commands) = body["commands"].as_array_mut() {
4588                for command in commands {
4589                    if command.get("observability_context").is_none()
4590                        && matches!(
4591                            command["type"].as_str(),
4592                            Some("start_child_workflow" | "continue_as_new")
4593                        )
4594                    {
4595                        *command = self.with_observability_context(command.take());
4596                    }
4597                }
4598            }
4599        }
4600        if !message_stream_cursors.is_empty() {
4601            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4602        }
4603        if !message_stream_waits.is_empty() {
4604            body["message_stream_waits"] = Value::Array(message_stream_waits);
4605        }
4606        if let Some(claim) = sticky_cache {
4607            body["sticky_cache"] = claim;
4608        }
4609        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4610        self.request_json(
4611            reqwest::Method::POST,
4612            &path,
4613            RequestProtocol::Worker(protocol_version),
4614            Some(&body),
4615        )
4616        .await
4617    }
4618
4619    pub async fn fail_workflow_task(
4620        &self,
4621        task_id: &str,
4622        lease_owner: &str,
4623        workflow_task_attempt: u64,
4624        message: impl Into<String>,
4625    ) -> Result<Value> {
4626        self.fail_workflow_task_with_type(
4627            task_id,
4628            lease_owner,
4629            workflow_task_attempt,
4630            message,
4631            "RustWorkflowTaskFailure",
4632        )
4633        .await
4634    }
4635
4636    async fn fail_workflow_task_with_type(
4637        &self,
4638        task_id: &str,
4639        lease_owner: &str,
4640        workflow_task_attempt: u64,
4641        message: impl Into<String>,
4642        failure_type: &str,
4643    ) -> Result<Value> {
4644        self.fail_workflow_task_with_failure(
4645            task_id,
4646            lease_owner,
4647            workflow_task_attempt,
4648            json!({"message": message.into(), "type": failure_type}),
4649        )
4650        .await
4651    }
4652
4653    async fn fail_workflow_task_with_failure(
4654        &self,
4655        task_id: &str,
4656        lease_owner: &str,
4657        workflow_task_attempt: u64,
4658        failure: Value,
4659    ) -> Result<Value> {
4660        let body = json!({
4661            "lease_owner": lease_owner,
4662            "workflow_task_attempt": workflow_task_attempt,
4663            "failure": failure,
4664        });
4665        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4666        self.request_json(
4667            reqwest::Method::POST,
4668            &path,
4669            RequestProtocol::DefaultWorker,
4670            Some(&body),
4671        )
4672        .await
4673    }
4674
4675    pub async fn poll_activity_task(
4676        &self,
4677        worker_id: &str,
4678        task_queue: &str,
4679        timeout: Duration,
4680    ) -> Result<Option<ActivityTask>> {
4681        Ok(self
4682            .poll_activity_task_response(worker_id, task_queue, timeout)
4683            .await?
4684            .task)
4685    }
4686
4687    /// Poll an activity task while preserving server stop and drain metadata.
4688    pub async fn poll_activity_task_response(
4689        &self,
4690        worker_id: &str,
4691        task_queue: &str,
4692        timeout: Duration,
4693    ) -> Result<PollActivityTaskResponse> {
4694        let poll_request_id = unique_request_id("rust-activity-poll");
4695        self.poll_activity_task_response_with_request_id(
4696            worker_id,
4697            task_queue,
4698            timeout,
4699            &poll_request_id,
4700            1,
4701        )
4702        .await
4703        .map(worker_session::SessionPollResponse::ordinary)
4704    }
4705
4706    async fn poll_activity_task_response_with_request_id(
4707        &self,
4708        worker_id: &str,
4709        task_queue: &str,
4710        timeout: Duration,
4711        poll_request_id: &str,
4712        transport_retries: usize,
4713    ) -> Result<worker_session::SessionPollResponse> {
4714        let body = json!({
4715            "worker_id": worker_id,
4716            "task_queue": task_queue,
4717            "poll_request_id": poll_request_id,
4718            "timeout_seconds": long_poll_timeout_seconds(timeout),
4719        });
4720        let mut wire: Value = self
4721            .poll_request_json_unresolved(
4722                "/worker/activity-tasks/poll",
4723                RequestProtocol::DefaultWorker,
4724                &body,
4725                timeout + Duration::from_secs(5),
4726                transport_retries,
4727            )
4728            .await?;
4729        let lease =
4730            activity_lease::authority::Lease::confirm(self, &wire, worker_id, task_queue).await?;
4731        let observed = self.with_activity_lease_authority(
4732            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
4733        );
4734        let claim = if lease.is_none() {
4735            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
4736        } else {
4737            None
4738        };
4739        let loading = async {
4740            observed
4741                .resolve_runtime_payloads(
4742                    &mut wire,
4743                    "/worker/activity-tasks/poll",
4744                    RequestProtocol::DefaultWorker,
4745                )
4746                .await?;
4747            if let Some(lease) = &lease {
4748                lease
4749                    .authority
4750                    .refresh_delivery_session(&mut wire["task"])?;
4751            }
4752            Ok(serde_json::from_value(wire)?)
4753        };
4754        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
4755            Some(lease) => lease.authority.protect(loading).await?,
4756            None => {
4757                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
4758            }
4759        };
4760        if let Some(task) = data.task.as_mut() {
4761            task.hydration_claim = claim;
4762            task.activity_lease = lease;
4763        }
4764        Ok(data)
4765    }
4766
4767    pub async fn complete_activity_task<T: Serialize>(
4768        &self,
4769        task_id: &str,
4770        activity_attempt_id: &str,
4771        lease_owner: &str,
4772        result: T,
4773        codec: &str,
4774    ) -> Result<Value> {
4775        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4776        let body = json!({
4777            "activity_attempt_id": activity_attempt_id,
4778            "lease_owner": lease_owner,
4779            "result": result
4780        });
4781        let path = format!("/worker/activity-tasks/{task_id}/complete");
4782        activity_task_response(
4783            self.request_json(
4784                reqwest::Method::POST,
4785                &path,
4786                RequestProtocol::DefaultWorker,
4787                Some(&body),
4788            )
4789            .await,
4790            "complete",
4791            task_id,
4792            activity_attempt_id,
4793        )
4794    }
4795
4796    pub async fn fail_activity_task(
4797        &self,
4798        task_id: &str,
4799        activity_attempt_id: &str,
4800        lease_owner: &str,
4801        message: impl Into<String>,
4802        non_retryable: bool,
4803    ) -> Result<Value> {
4804        self.fail_activity_task_with_error(
4805            task_id,
4806            activity_attempt_id,
4807            lease_owner,
4808            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
4809        )
4810        .await
4811    }
4812
4813    /// Report an activity's application-defined failure type and retry marker.
4814    pub async fn fail_activity_task_with_error(
4815        &self,
4816        task_id: &str,
4817        activity_attempt_id: &str,
4818        lease_owner: &str,
4819        error: &ActivityError,
4820    ) -> Result<Value> {
4821        let error = error.validated();
4822        let body = json!({
4823            "activity_attempt_id": activity_attempt_id,
4824            "lease_owner": lease_owner,
4825            "failure": {
4826                "message": error.message,
4827                "type": error.exception_type,
4828                "non_retryable": error.non_retryable
4829            }
4830        });
4831        let path = format!("/worker/activity-tasks/{task_id}/fail");
4832        activity_task_response(
4833            self.request_json(
4834                reqwest::Method::POST,
4835                &path,
4836                RequestProtocol::DefaultWorker,
4837                Some(&body),
4838            )
4839            .await,
4840            "fail",
4841            task_id,
4842            activity_attempt_id,
4843        )
4844    }
4845
4846    /// Record a flat map of scalar/null activity progress metadata.
4847    ///
4848    /// Heartbeat details use the Server's bounded JSON progress contract.
4849    /// They are not workflow payload envelopes.
4850    pub async fn heartbeat_activity_task<T: Serialize>(
4851        &self,
4852        task_id: &str,
4853        activity_attempt_id: &str,
4854        lease_owner: &str,
4855        details: T,
4856    ) -> Result<ActivityHeartbeatResponse> {
4857        serde_json::from_value(
4858            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4859                .await?,
4860        )
4861        .map_err(Error::from)
4862    }
4863
4864    async fn heartbeat_activity_task_value<T: Serialize>(
4865        &self,
4866        task_id: &str,
4867        activity_attempt_id: &str,
4868        lease_owner: &str,
4869        details: T,
4870    ) -> Result<Value> {
4871        let details = AvroValue::from_serialize(&details)?.into_json()?;
4872        let body = json!({
4873            "activity_attempt_id": activity_attempt_id,
4874            "lease_owner": lease_owner,
4875            "details": details
4876        });
4877        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4878        let started = tokio::time::Instant::now();
4879        let response = activity_task_response(
4880            self.request_json(
4881                reqwest::Method::POST,
4882                &path,
4883                RequestProtocol::DefaultWorker,
4884                Some(&body),
4885            )
4886            .await,
4887            "heartbeat",
4888            task_id,
4889            activity_attempt_id,
4890        )?;
4891        if let Some(authority) = &self.activity_lease_authority {
4892            authority.progress(&response, started)?;
4893        }
4894        Ok(response)
4895    }
4896
4897    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4898        &self,
4899        method: reqwest::Method,
4900        path: &str,
4901        protocol: RequestProtocol,
4902        body: Option<&B>,
4903    ) -> Result<T> {
4904        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4905            .await
4906    }
4907
4908    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4909        &self,
4910        method: reqwest::Method,
4911        path: &str,
4912        protocol: RequestProtocol,
4913        body: Option<&B>,
4914        timeout: Duration,
4915    ) -> Result<T> {
4916        let mut value: Value = self
4917            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4918            .await?;
4919        let protocol = match protocol {
4920            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4921                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4922            }
4923            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4924        };
4925        self.resolve_runtime_payloads(&mut value, path, protocol)
4926            .await?;
4927        Ok(serde_json::from_value(value)?)
4928    }
4929
4930    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
4931        Ok(match protocol {
4932            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4933                let selected = self.worker_protocol_version.as_str();
4934                if self.cooperative_worker_protocol
4935                    && !cooperative_cancellation::supports_protocol(selected)
4936                {
4937                    return Err(Error::CooperativeCancellationUnavailable(
4938                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4939                    ));
4940                }
4941                if let RequestProtocol::Worker(minimum) = protocol {
4942                    let supported = minimum
4943                        .strip_prefix("1.")
4944                        .and_then(|minor| minor.parse::<u64>().ok())
4945                        .zip(
4946                            selected
4947                                .strip_prefix("1.")
4948                                .and_then(|minor| minor.parse::<u64>().ok()),
4949                        )
4950                        .is_some_and(|(minimum, selected)| selected >= minimum);
4951                    if !supported {
4952                        return Err(Error::WorkerLoop(format!(
4953                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4954                        )));
4955                    }
4956                }
4957                RequestProtocol::Worker(selected)
4958            }
4959            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4960        })
4961    }
4962
4963    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
4964        match &self.activity_lease_authority {
4965            Some(authority) => authority.check(path, body),
4966            None => Ok(()),
4967        }
4968    }
4969
4970    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4971        &self,
4972        method: reqwest::Method,
4973        path: &str,
4974        protocol: RequestProtocol,
4975        body: Option<&B>,
4976        timeout: Duration,
4977    ) -> Result<T> {
4978        #[cfg(feature = "telemetry")]
4979        self.begin_observability_discovery(&method, path);
4980        let protocol = self.worker_request_protocol(protocol)?;
4981        let auth_token = self.auth_token(protocol)?;
4982        let mut request = self
4983            .http
4984            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4985            .timeout(timeout)
4986            .header(reqwest::header::ACCEPT, "application/json")
4987            .header(reqwest::header::CONTENT_TYPE, "application/json")
4988            .header("X-Namespace", &self.namespace);
4989
4990        match protocol {
4991            RequestProtocol::DefaultWorker => {
4992                request = request.header(
4993                    "X-Durable-Workflow-Protocol-Version",
4994                    self.worker_protocol_version.as_str(),
4995                );
4996            }
4997            RequestProtocol::Worker(version) => {
4998                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4999            }
5000            RequestProtocol::ControlPlane => {
5001                request = request.header(
5002                    "X-Durable-Workflow-Control-Plane-Version",
5003                    CONTROL_PLANE_VERSION,
5004                );
5005            }
5006        }
5007
5008        if let Some(token) = auth_token {
5009            request = request.bearer_auth(token);
5010        }
5011
5012        if let Some(body) = body {
5013            let mut body = serde_json::to_value(body)?;
5014            if matches!(
5015                method,
5016                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5017            ) {
5018                self.check_activity_lease_request(path, Some(&body))?;
5019                self.externalize_runtime_payloads(&mut body, path, protocol)
5020                    .await?;
5021                self.check_activity_lease_request(path, Some(&body))?;
5022            }
5023            request = request.json(&body);
5024        }
5025
5026        let request = request.build()?;
5027        let request_body = request
5028            .body()
5029            .and_then(reqwest::Body::as_bytes)
5030            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5031        let poll_request_id = path.ends_with("/poll").then(|| {
5032            request_body
5033                .as_ref()
5034                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5035                .unwrap_or_default()
5036        });
5037        let mut storage_retries = 0_usize;
5038        let mut deferred_workflow_completion = false;
5039
5040        loop {
5041            // Keep the serialized body and lease/poll identity across admission pauses.
5042            self.check_activity_lease_request(path, request_body.as_ref())?;
5043            let receive = async {
5044                let response = self
5045                    .http
5046                    .execute(request.try_clone().ok_or_else(|| {
5047                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5048                    })?)
5049                    .await?;
5050                let status = response.status();
5051                Ok::<_, Error>((status, response.bytes().await?))
5052            };
5053            let retry_deadline = self
5054                .worker_storage_admission
5055                .as_ref()
5056                .and_then(|admission| admission.workflow_completion_retry_deadline);
5057            if deferred_workflow_completion
5058                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5059            {
5060                return Err(Error::Timeout);
5061            }
5062            let received = async {
5063                match retry_deadline.filter(|_| deferred_workflow_completion) {
5064                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5065                        .await
5066                        .map_err(|_| Error::Timeout)?,
5067                    None => receive.await,
5068                }
5069            };
5070            let (status, bytes) = match self
5071                .activity_lease_authority
5072                .as_ref()
5073                .filter(|authority| authority.governs(path))
5074            {
5075                Some(authority) => authority.protect(received).await?,
5076                None => received.await?,
5077            };
5078
5079            if !status.is_success() {
5080                let body = String::from_utf8_lossy(&bytes).to_string();
5081                if let Some(protocol) = protocol_failure(status, &body) {
5082                    return Err(Error::Protocol(protocol));
5083                }
5084                let error = Error::Http { status, body };
5085                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5086                    &error,
5087                    path,
5088                    request_body.as_ref(),
5089                )
5090                .is_some();
5091                if self
5092                    .wait_for_storage_admission(
5093                        &error,
5094                        protocol,
5095                        Some(path),
5096                        poll_request_id.as_deref(),
5097                        request_body.as_ref(),
5098                        &mut storage_retries,
5099                    )
5100                    .await
5101                {
5102                    continue;
5103                }
5104                return Err(error);
5105            }
5106
5107            if bytes.is_empty() {
5108                return Ok(serde_json::from_value(Value::Null)?);
5109            }
5110
5111            #[cfg(feature = "telemetry")]
5112            return self.decode_observability_response(
5113                &method,
5114                path,
5115                request_body.as_ref(),
5116                &bytes,
5117            );
5118
5119            #[cfg(not(feature = "telemetry"))]
5120            return Ok(serde_json::from_slice(&bytes)?);
5121        }
5122    }
5123
5124    #[cfg(feature = "telemetry")]
5125    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5126        if *method == reqwest::Method::GET && path == "/cluster/info" {
5127            self.observability_context_supported
5128                .store(false, Ordering::SeqCst);
5129        }
5130    }
5131
5132    #[cfg(feature = "telemetry")]
5133    fn decode_observability_response<T: DeserializeOwned>(
5134        &self,
5135        method: &reqwest::Method,
5136        path: &str,
5137        request_body: Option<&Value>,
5138        bytes: &[u8],
5139    ) -> Result<T> {
5140        if *method == reqwest::Method::POST
5141            && self.execution_telemetry.is_some()
5142            && matches!(
5143                path,
5144                "/worker/workflow-tasks/poll"
5145                    | "/worker/activity-tasks/poll"
5146                    | "/worker/query-tasks/poll"
5147            )
5148        {
5149            let mut wire: Value = serde_json::from_slice(bytes)?;
5150            telemetry::carrier::retain_poll_observations(
5151                &mut wire,
5152                request_body.unwrap_or(&Value::Null),
5153                path,
5154                &self.namespace,
5155            );
5156            return Ok(serde_json::from_value(wire)?);
5157        }
5158        if *method == reqwest::Method::GET && path == "/cluster/info" {
5159            let info: Value = serde_json::from_slice(bytes)?;
5160            self.observability_context_supported
5161                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5162            return Ok(serde_json::from_value(info)?);
5163        }
5164        Ok(serde_json::from_slice(bytes)?)
5165    }
5166
5167    async fn wait_for_storage_admission(
5168        &self,
5169        error: &Error,
5170        protocol: RequestProtocol,
5171        path: Option<&str>,
5172        poll_request_id: Option<&str>,
5173        request_body: Option<&Value>,
5174        retries: &mut usize,
5175    ) -> bool {
5176        let Some(admission) = self
5177            .worker_storage_admission
5178            .as_ref()
5179            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5180        else {
5181            return false;
5182        };
5183        let completion_deferred = path.and_then(|path| {
5184            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5185        });
5186        let Some(advertised_delay) = completion_deferred
5187            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5188            .or_else(|| {
5189                path.and_then(|path| {
5190                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5191                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5192                })
5193            })
5194        else {
5195            return false;
5196        };
5197        *retries = retries.saturating_add(1);
5198        let delay = worker_retry_delay(admission.policy, *retries)
5199            .max(advertised_delay)
5200            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
5201        let delay = if completion_deferred.is_some() {
5202            delay.max(advertised_delay)
5203        } else {
5204            delay
5205        };
5206        let wait_deadline = tokio::time::Instant::now() + delay;
5207        loop {
5208            if admission.stop.load(Ordering::SeqCst) {
5209                return false;
5210            }
5211            let now = tokio::time::Instant::now();
5212            if admission
5213                .workflow_completion_retry_deadline
5214                .is_some_and(|deadline| now >= deadline)
5215            {
5216                return false;
5217            }
5218            let remaining = wait_deadline.saturating_duration_since(now);
5219            if remaining.is_zero() {
5220                return true;
5221            }
5222            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
5223        }
5224    }
5225
5226    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5227        &self,
5228        path: &str,
5229        protocol: RequestProtocol,
5230        body: &B,
5231        timeout: Duration,
5232        max_retries: usize,
5233    ) -> Result<T> {
5234        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
5235            .await
5236    }
5237
5238    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
5239        &self,
5240        path: &str,
5241        protocol: RequestProtocol,
5242        body: &B,
5243        timeout: Duration,
5244        max_retries: usize,
5245    ) -> Result<T> {
5246        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
5247            .await
5248    }
5249
5250    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
5251        &self,
5252        path: &str,
5253        protocol: RequestProtocol,
5254        body: &B,
5255        timeout: Duration,
5256        max_retries: usize,
5257        resolve: bool,
5258    ) -> Result<T> {
5259        let mut retries = 0;
5260
5261        loop {
5262            let response: Result<Value> = if resolve {
5263                self.request_json_with_timeout(
5264                    reqwest::Method::POST,
5265                    path,
5266                    protocol,
5267                    Some(body),
5268                    timeout,
5269                )
5270                .await
5271            } else {
5272                self.request_json_unresolved_with_timeout(
5273                    reqwest::Method::POST,
5274                    path,
5275                    protocol,
5276                    Some(body),
5277                    timeout,
5278                )
5279                .await
5280            };
5281
5282            match response {
5283                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
5284                response => {
5285                    let value = worker_poll_response(response)?;
5286                    if value.get("task").is_some_and(|task| !task.is_null()) {
5287                        if let Some(slot) = &self.worker_task_slot {
5288                            slot.claimed();
5289                        }
5290                    }
5291                    return Ok(serde_json::from_value(value)?);
5292                }
5293            }
5294        }
5295    }
5296
5297    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
5298        match protocol {
5299            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5300                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
5301                    return Ok(Some(token));
5302                }
5303                if self.control_token.is_some() {
5304                    return Err(Error::MissingRoleCredentials {
5305                        role: "worker",
5306                        opposite_role: "control",
5307                    });
5308                }
5309                Ok(None)
5310            }
5311            RequestProtocol::ControlPlane => {
5312                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
5313                    return Ok(Some(token));
5314                }
5315                if self.worker_token.is_some() {
5316                    return Err(Error::MissingRoleCredentials {
5317                        role: "control",
5318                        opposite_role: "worker",
5319                    });
5320                }
5321                Ok(None)
5322            }
5323        }
5324    }
5325}
5326
5327fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
5328    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5329    let reason = body
5330        .get("reason")
5331        .and_then(Value::as_str)
5332        .unwrap_or("query_rejected")
5333        .to_string();
5334    let message = body
5335        .get("message")
5336        .or_else(|| body.get("error"))
5337        .and_then(Value::as_str)
5338        .unwrap_or("workflow query was rejected")
5339        .to_string();
5340
5341    QueryFailure {
5342        status: status.as_u16(),
5343        reason,
5344        message,
5345        body,
5346    }
5347}
5348
5349fn workflow_command_result(
5350    command: WorkflowCommandKind,
5351    data: Value,
5352    workflow_id: &str,
5353    run_id: Option<&str>,
5354) -> WorkflowCommandResult {
5355    WorkflowCommandResult {
5356        command,
5357        workflow_id: data
5358            .get("workflow_id")
5359            .and_then(Value::as_str)
5360            .unwrap_or(workflow_id)
5361            .to_string(),
5362        run_id: data
5363            .get("run_id")
5364            .and_then(Value::as_str)
5365            .or(run_id)
5366            .map(str::to_string),
5367        outcome: data
5368            .get("outcome")
5369            .and_then(Value::as_str)
5370            .map(str::to_string),
5371        reason: data
5372            .get("reason")
5373            .and_then(Value::as_str)
5374            .map(str::to_string),
5375        command_status: data
5376            .get("command_status")
5377            .and_then(Value::as_str)
5378            .map(str::to_string),
5379        raw: data,
5380    }
5381}
5382
5383fn workflow_command_rejection(
5384    command: WorkflowCommandKind,
5385    status: reqwest::StatusCode,
5386    raw_body: String,
5387    workflow_id: &str,
5388    run_id: Option<&str>,
5389) -> WorkflowCommandRejection {
5390    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5391    WorkflowCommandRejection {
5392        command,
5393        status: status.as_u16(),
5394        reason: body
5395            .get("reason")
5396            .and_then(Value::as_str)
5397            .unwrap_or("workflow_command_rejected")
5398            .to_string(),
5399        message: body
5400            .get("message")
5401            .or_else(|| body.get("error"))
5402            .and_then(Value::as_str)
5403            .unwrap_or("workflow lifecycle command was rejected")
5404            .to_string(),
5405        workflow_id: body
5406            .get("workflow_id")
5407            .and_then(Value::as_str)
5408            .unwrap_or(workflow_id)
5409            .to_string(),
5410        run_id: body
5411            .get("run_id")
5412            .and_then(Value::as_str)
5413            .or(run_id)
5414            .map(str::to_string),
5415        target_scope: body
5416            .get("target_scope")
5417            .and_then(Value::as_str)
5418            .map(str::to_string),
5419        body,
5420    }
5421}
5422
5423fn query_task_response(response: Result<Value>) -> Result<Value> {
5424    match response {
5425        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
5426        response => response,
5427    }
5428}
5429
5430fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
5431    match response {
5432        Err(Error::Http { status, body })
5433            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5434        {
5435            Ok(serde_json::from_str(&body)?)
5436        }
5437        response => response,
5438    }
5439}
5440
5441fn worker_poll_body_is_stop(body: &str) -> bool {
5442    serde_json::from_str::<Value>(body)
5443        .ok()
5444        .is_some_and(|body| {
5445            worker_poll_is_stop(
5446                body.get("poll_status").and_then(Value::as_str),
5447                body.get("reason").and_then(Value::as_str),
5448            )
5449        })
5450}
5451
5452fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5453    matches!(poll_status, Some("draining" | "stopped"))
5454        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5455}
5456
5457fn query_task_rejection_is_final(error: &Error) -> bool {
5458    matches!(
5459        error,
5460        Error::QueryFailed(failure)
5461            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5462    )
5463}
5464
5465fn activity_task_response<T>(
5466    response: Result<T>,
5467    operation: &str,
5468    task_id: &str,
5469    activity_attempt_id: &str,
5470) -> Result<T> {
5471    match response {
5472        Err(Error::Http { status, body }) => {
5473            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5474            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5475                operation: operation.to_string(),
5476                status: status.as_u16(),
5477                reason: body
5478                    .get("reason")
5479                    .and_then(Value::as_str)
5480                    .unwrap_or("activity_task_rejected")
5481                    .to_string(),
5482                task_id: body
5483                    .get("task_id")
5484                    .and_then(Value::as_str)
5485                    .unwrap_or(task_id)
5486                    .to_string(),
5487                activity_attempt_id: body
5488                    .get("activity_attempt_id")
5489                    .and_then(Value::as_str)
5490                    .unwrap_or(activity_attempt_id)
5491                    .to_string(),
5492                cancel_requested: body
5493                    .get("cancel_requested")
5494                    .and_then(Value::as_bool)
5495                    .unwrap_or(false),
5496                can_continue: body.get("can_continue").and_then(Value::as_bool),
5497                run_closed_reason: body
5498                    .get("run_closed_reason")
5499                    .and_then(Value::as_str)
5500                    .map(str::to_string),
5501                body,
5502            }))
5503        }
5504        response => response,
5505    }
5506}
5507
5508fn activity_task_rejection_is_final(error: &Error) -> bool {
5509    matches!(
5510        error,
5511        Error::ActivityTaskRejected(rejection)
5512            if matches!(
5513                rejection.reason.as_str(),
5514                "run_cancelled"
5515                    | "run_terminated"
5516                    | "attempt_closed"
5517                    | "stale_attempt"
5518                    | "activity_cancelled"
5519                    | "task_cancelled"
5520                    | "run_closed"
5521                    | "activity_not_running"
5522                    | "attempt_not_found"
5523            )
5524    )
5525}
5526
5527fn workflow_task_completion_is_terminal_timeout(
5528    error: &Error,
5529    task_id: &str,
5530    workflow_task_attempt: u64,
5531    run_id: Option<&str>,
5532) -> bool {
5533    let Error::Http { status, body } = error else {
5534        return false;
5535    };
5536    if *status != reqwest::StatusCode::CONFLICT {
5537        return false;
5538    }
5539
5540    let Some(run_id) = run_id else {
5541        return false;
5542    };
5543    let Ok(body) = serde_json::from_str::<Value>(body) else {
5544        return false;
5545    };
5546
5547    body.get("recorded").and_then(Value::as_bool) == Some(false)
5548        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5549        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5550        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5551        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5552        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5553}
5554
5555fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5556    let body: Value = serde_json::from_str(raw_body).ok()?;
5557    let reason = body.get("reason")?.as_str()?;
5558    if !matches!(
5559        reason,
5560        "missing_protocol_version"
5561            | "unsupported_protocol_version"
5562            | "missing_control_plane_version"
5563            | "unsupported_control_plane_version"
5564    ) {
5565        return None;
5566    }
5567
5568    Some(ProtocolFailure {
5569        status: status.as_u16(),
5570        reason: reason.to_string(),
5571        message: body
5572            .get("message")
5573            .or_else(|| body.get("error"))
5574            .and_then(Value::as_str)
5575            .unwrap_or("protocol version rejected")
5576            .to_string(),
5577        supported_version: body
5578            .get("supported_version")
5579            .and_then(Value::as_str)
5580            .map(str::to_string),
5581        requested_version: body
5582            .get("requested_version")
5583            .and_then(Value::as_str)
5584            .map(str::to_string),
5585        body,
5586    })
5587}
5588
5589fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5590    timeout
5591        .as_secs()
5592        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5593        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5594}
5595
5596fn worker_operation_is_retryable(error: &Error) -> bool {
5597    if worker_poll_capacity_retry_after(error).is_some()
5598        || worker_storage_admission_body(error).is_some()
5599        || worker_backend_unavailable_body(error).is_some()
5600        || worker_operation_is_explicitly_non_retryable(error)
5601    {
5602        return false;
5603    }
5604
5605    match error {
5606        Error::Transport(error) => {
5607            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5608        }
5609        Error::Http { status, .. } => {
5610            matches!(
5611                *status,
5612                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5613            ) || status.is_server_error()
5614        }
5615        _ => false,
5616    }
5617}
5618
5619fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5620    let body: Value = match error {
5621        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5622        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5623        _ => return None,
5624    };
5625    matches!(
5626        body.get("reason").and_then(Value::as_str),
5627        Some("storage_pressure" | "storage_admission_unavailable")
5628    )
5629    .then_some(body)
5630}
5631
5632fn worker_storage_admission_retry_after(
5633    error: &Error,
5634    poll_request_id: Option<&str>,
5635) -> Option<Duration> {
5636    let Error::Http { status, .. } = error else {
5637        return None;
5638    };
5639    let body = worker_storage_admission_body(error)?;
5640    let delay = body.get("retry_after_seconds")?.as_u64()?;
5641    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5642        || delay == 0
5643        || body.get("retryable") != Some(&Value::Bool(true))
5644        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5645        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5646        || body
5647            .get("request_admitted")
5648            .is_some_and(|admitted| admitted != &Value::Bool(false))
5649    {
5650        return None;
5651    }
5652    match poll_request_id {
5653        Some(id) => {
5654            if id.is_empty()
5655                || body.get("task") != Some(&Value::Null)
5656                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5657                || body.get("poll_status") != body.get("reason")
5658                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5659                || body.get("claim_admitted") != Some(&Value::Bool(false))
5660            {
5661                return None;
5662            }
5663        }
5664        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5665        None => {}
5666    }
5667    Some(Duration::from_secs(delay))
5668}
5669
5670fn worker_backend_unavailable_retry_after(
5671    error: &Error,
5672    path: &str,
5673    poll_request_id: Option<&str>,
5674) -> Option<Duration> {
5675    let operation = match path {
5676        "/worker/register" => "register_worker",
5677        "/worker/heartbeat" => "heartbeat_worker",
5678        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5679        "/worker/activity-tasks/poll" => "poll_activity_task",
5680        "/worker/query-tasks/poll" => "poll_query_task",
5681        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5682        _ => return None,
5683    };
5684    let body = worker_backend_unavailable_body(error)?;
5685    let delay = body.get("retry_after_seconds")?.as_u64()?;
5686    if delay == 0
5687        || body.get("operation")?.as_str()? != operation
5688        || body.get("outcome")?.as_str()? != "unknown"
5689        || body.get("retryable") != Some(&Value::Bool(true))
5690        || body.get("worker_id")?.as_str()?.is_empty()
5691    {
5692        return None;
5693    }
5694    if let Some(id) = poll_request_id {
5695        if id.is_empty()
5696            || body.get("task") != Some(&Value::Null)
5697            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5698            || body.get("poll_request_id")?.as_str()? != id
5699            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5700        {
5701            return None;
5702        }
5703    } else if path.ends_with("/poll") {
5704        return None;
5705    }
5706    Some(Duration::from_secs(delay))
5707}
5708
5709fn worker_fenced_completion_retry_after(
5710    error: &Error,
5711    path: &str,
5712    request_body: Option<&Value>,
5713) -> Option<Duration> {
5714    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5715        .strip_prefix("/worker/workflow-tasks/")
5716        .and_then(|tail| tail.strip_suffix("/complete"))
5717    {
5718        ("complete_workflow_task", task_id, "workflow_task_attempt")
5719    } else if let Some(task_id) = path
5720        .strip_prefix("/worker/activity-tasks/")
5721        .and_then(|tail| tail.strip_suffix("/complete"))
5722    {
5723        ("complete_activity_task", task_id, "activity_attempt_id")
5724    } else {
5725        return None;
5726    };
5727    if task_id.is_empty() || task_id.contains('/') {
5728        return None;
5729    }
5730
5731    let request = request_body?.as_object()?;
5732    let lease_owner = request.get("lease_owner")?.as_str()?;
5733    if lease_owner.is_empty() {
5734        return None;
5735    }
5736    let attempt = request.get(attempt_field)?;
5737    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5738        || (attempt_field == "activity_attempt_id"
5739            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5740    {
5741        return None;
5742    }
5743
5744    let body = worker_backend_unavailable_body(error)?;
5745    let delay = body.get("retry_after_seconds")?.as_u64()?;
5746    if delay == 0
5747        || body.get("operation")?.as_str()? != operation
5748        || body.get("outcome")?.as_str()? != "unknown"
5749        || body.get("retryable") != Some(&Value::Bool(true))
5750        || body.get("worker_id")?.as_str()? != lease_owner
5751        || body.get("task_queue") != Some(&Value::Null)
5752        || body.get("task_id")?.as_str()? != task_id
5753        || body.get("lease_owner")?.as_str()? != lease_owner
5754        || body.get(attempt_field) != Some(attempt)
5755    {
5756        return None;
5757    }
5758
5759    Some(Duration::from_secs(delay))
5760}
5761
5762fn worker_deferred_workflow_completion_retry_after(
5763    error: &Error,
5764    path: &str,
5765    request_body: Option<&Value>,
5766) -> Option<Duration> {
5767    let task_id = path
5768        .strip_prefix("/worker/workflow-tasks/")?
5769        .strip_suffix("/complete")?;
5770    if task_id.is_empty() || task_id.contains('/') {
5771        return None;
5772    }
5773    let request = request_body?.as_object()?;
5774    let owner = request.get("lease_owner")?.as_str()?;
5775    let attempt = request.get("workflow_task_attempt")?;
5776    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5777        return None;
5778    }
5779    let Error::Http { status, body } = error else {
5780        return None;
5781    };
5782    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5783        return None;
5784    }
5785    let body: Value = serde_json::from_str(body).ok()?;
5786    let delay = body.get("retry_after_seconds")?.as_u64()?;
5787    if !(1..=5).contains(&delay)
5788        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5789        || body.get("operation")?.as_str()? != "complete_workflow_task"
5790        || body.get("outcome")?.as_str()? != "deferred"
5791        || body.get("recorded") != Some(&Value::Bool(false))
5792        || body.get("retryable") != Some(&Value::Bool(true))
5793        || body.get("task_id")?.as_str()? != task_id
5794        || body.get("lease_owner")?.as_str()? != owner
5795        || body.get("workflow_task_attempt") != Some(attempt)
5796        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5797    {
5798        return None;
5799    }
5800    Some(Duration::from_secs(delay))
5801}
5802
5803fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5804    let Error::Http { status, body } = error else {
5805        return None;
5806    };
5807    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5808        return None;
5809    }
5810    let body: Value = serde_json::from_str(body).ok()?;
5811    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5812}
5813
5814fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5815    let Error::Http { body, .. } = error else {
5816        return false;
5817    };
5818
5819    serde_json::from_str::<Value>(body)
5820        .ok()
5821        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5822        == Some(false)
5823}
5824
5825fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5826    let Error::Http { status, body } = error else {
5827        return None;
5828    };
5829    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5830        return None;
5831    }
5832
5833    let body = serde_json::from_str::<Value>(body).ok()?;
5834    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5835        == Some("long_poll_capacity_exhausted")
5836        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5837    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5838        return None;
5839    }
5840
5841    Some(Duration::from_secs(
5842        body.get("retry_after_seconds")
5843            .and_then(Value::as_u64)
5844            .unwrap_or_default(),
5845    ))
5846}
5847
5848fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5849    let exponent = retry.saturating_sub(1).min(31) as u32;
5850    policy
5851        .initial_backoff
5852        .saturating_mul(1_u32 << exponent)
5853        .min(policy.max_backoff)
5854}
5855
5856#[derive(Debug)]
5857pub struct ClientBuilder {
5858    base_url: String,
5859    token: Option<String>,
5860    control_token: Option<String>,
5861    worker_token: Option<String>,
5862    namespace: String,
5863    timeout: Duration,
5864    max_external_payload_bytes: usize,
5865    worker_protocol_version: WorkerProtocolVersion,
5866    additional_root_certificates: Vec<reqwest::Certificate>,
5867}
5868
5869impl ClientBuilder {
5870    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5871    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5872        self.worker_protocol_version = version;
5873        self
5874    }
5875
5876    pub fn token(mut self, token: Option<String>) -> Self {
5877        self.token = token;
5878        self
5879    }
5880
5881    pub fn control_token(mut self, token: Option<String>) -> Self {
5882        self.control_token = token;
5883        self
5884    }
5885
5886    pub fn worker_token(mut self, token: Option<String>) -> Self {
5887        self.worker_token = token;
5888        self
5889    }
5890
5891    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5892        self.namespace = namespace.into();
5893        self
5894    }
5895
5896    pub fn timeout(mut self, timeout: Duration) -> Self {
5897        self.timeout = timeout;
5898        self
5899    }
5900
5901    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5902    /// References are fetched only from this client's authenticated runtime.
5903    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5904        self.max_external_payload_bytes = bytes;
5905        self
5906    }
5907
5908    pub fn build(self) -> Result<Client> {
5909        let base_url = self.base_url.trim_end_matches('/').to_string();
5910        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5911            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5912            .unwrap_or_else(|_| base_url.ends_with("/api"));
5913
5914        if has_sdk_api_suffix {
5915            return Err(Error::InvalidBaseUrl);
5916        }
5917
5918        let mut http = reqwest::Client::builder()
5919            .timeout(self.timeout)
5920            .redirect(reqwest::redirect::Policy::none());
5921        for certificate in self.additional_root_certificates {
5922            http = http.add_root_certificate(certificate);
5923        }
5924        Ok(Client {
5925            http: http.build()?,
5926            hydration_timeout: self.timeout,
5927            base_url,
5928            token: self.token,
5929            control_token: self.control_token,
5930            worker_token: self.worker_token,
5931            namespace: self.namespace,
5932            max_external_payload_bytes: self.max_external_payload_bytes,
5933            worker_storage_admission: None,
5934            worker_task_slot: None,
5935            cooperative_worker_protocol: false,
5936            worker_protocol_version: self.worker_protocol_version,
5937            local_activities_enabled: false,
5938            worker_sessions_enabled: false,
5939            max_concurrent_worker_sessions: 10,
5940            worker_build_id: None,
5941            sticky_cache: None,
5942            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5943            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
5944            activity_lease_authority: None,
5945            #[cfg(feature = "telemetry")]
5946            execution_telemetry: None,
5947            #[cfg(feature = "telemetry")]
5948            observability_context_supported: Arc::new(AtomicBool::new(false)),
5949        })
5950    }
5951}
5952
5953#[derive(Clone, Debug)]
5954pub struct WorkflowHandle {
5955    client: Client,
5956    pub workflow_id: String,
5957    pub run_id: Option<String>,
5958    pub workflow_type: String,
5959}
5960
5961impl WorkflowHandle {
5962    /// Describe whichever run is current for this stable workflow instance.
5963    pub async fn describe(&self) -> Result<WorkflowDescription> {
5964        self.client.describe_workflow(&self.workflow_id).await
5965    }
5966
5967    /// Describe the run identity originally selected by this handle.
5968    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5969        let run_id = self.run_id.as_deref().ok_or_else(|| {
5970            Error::Codec("run_id is required for selected-run description".to_string())
5971        })?;
5972        self.client
5973            .describe_workflow_run(&self.workflow_id, run_id)
5974            .await
5975    }
5976
5977    /// Signal this workflow with an SDK-generated caller command key.
5978    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5979        self.client
5980            .signal_workflow(&self.workflow_id, signal_name, input)
5981            .await
5982    }
5983
5984    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
5985    pub async fn signal_with_request_id<T: Serialize>(
5986        &self,
5987        signal_name: &str,
5988        input: T,
5989        request_id: &str,
5990    ) -> Result<Value> {
5991        self.client
5992            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
5993            .await
5994    }
5995
5996    pub async fn append_message<T: Serialize>(
5997        &self,
5998        stream_name: &str,
5999        message_id: &str,
6000        input: T,
6001    ) -> Result<Value> {
6002        self.client
6003            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
6004            .await
6005    }
6006
6007    /// Signal only if this handle's selected run is still current, with an
6008    /// SDK-generated caller command key.
6009    pub async fn signal_selected_run<T: Serialize>(
6010        &self,
6011        signal_name: &str,
6012        input: T,
6013    ) -> Result<Value> {
6014        let run_id = self.run_id.as_deref().ok_or_else(|| {
6015            Error::Codec("run_id is required for selected-run signaling".to_string())
6016        })?;
6017        self.client
6018            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
6019            .await
6020    }
6021
6022    /// Signal only if this handle's selected run is still current, with an
6023    /// explicit caller command key (1 to 255 Unicode characters).
6024    pub async fn signal_selected_run_with_request_id<T: Serialize>(
6025        &self,
6026        signal_name: &str,
6027        input: T,
6028        request_id: &str,
6029    ) -> Result<Value> {
6030        let run_id = self.run_id.as_deref().ok_or_else(|| {
6031            Error::Codec("run_id is required for selected-run signaling".to_string())
6032        })?;
6033        self.client
6034            .signal_workflow_run_with_request_id(
6035                &self.workflow_id,
6036                run_id,
6037                signal_name,
6038                input,
6039                request_id,
6040            )
6041            .await
6042    }
6043
6044    /// Close whichever run is current as cancelled, without workflow cleanup.
6045    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
6046        self.client
6047            .cancel_workflow(&self.workflow_id, options)
6048            .await
6049    }
6050
6051    /// Request cancellation only if this handle's selected run is still current.
6052    pub async fn cancel_selected_run(
6053        &self,
6054        options: WorkflowCommandOptions,
6055    ) -> Result<WorkflowCommandResult> {
6056        let run_id = self.run_id.as_deref().ok_or_else(|| {
6057            Error::Codec("run_id is required for selected-run cancellation".to_string())
6058        })?;
6059        self.client
6060            .cancel_workflow_run(&self.workflow_id, run_id, options)
6061            .await
6062    }
6063
6064    /// Forcefully terminate whichever run is current.
6065    pub async fn terminate(
6066        &self,
6067        options: WorkflowCommandOptions,
6068    ) -> Result<WorkflowCommandResult> {
6069        self.client
6070            .terminate_workflow(&self.workflow_id, options)
6071            .await
6072    }
6073
6074    /// Terminate only if this handle's selected run is still current.
6075    pub async fn terminate_selected_run(
6076        &self,
6077        options: WorkflowCommandOptions,
6078    ) -> Result<WorkflowCommandResult> {
6079        let run_id = self.run_id.as_deref().ok_or_else(|| {
6080            Error::Codec("run_id is required for selected-run termination".to_string())
6081        })?;
6082        self.client
6083            .terminate_workflow_run(&self.workflow_id, run_id, options)
6084            .await
6085    }
6086
6087    /// Continue this handle's failed run without repeating completed activities.
6088    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
6089        let run_id = self
6090            .run_id
6091            .as_deref()
6092            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
6093        self.client
6094            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
6095            .await
6096    }
6097
6098    /// Execute a named, read-only query against this workflow.
6099    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
6100        self.client
6101            .query_workflow(&self.workflow_id, query_name, input)
6102            .await
6103    }
6104
6105    pub async fn query_avro_value<T: Serialize>(
6106        &self,
6107        query_name: &str,
6108        input: T,
6109    ) -> Result<AvroValue> {
6110        self.client
6111            .query_workflow_avro_value(&self.workflow_id, query_name, input)
6112            .await
6113    }
6114
6115    pub async fn update<T: Serialize>(
6116        &self,
6117        update_name: &str,
6118        input: T,
6119        request_id: Option<&str>,
6120    ) -> Result<Value> {
6121        self.client
6122            .update_workflow(&self.workflow_id, update_name, input, request_id)
6123            .await
6124    }
6125
6126    pub async fn update_avro_value<T: Serialize>(
6127        &self,
6128        update_name: &str,
6129        input: T,
6130        request_id: Option<&str>,
6131    ) -> Result<AvroValue> {
6132        self.client
6133            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
6134            .await
6135    }
6136
6137    /// Query only if this handle's selected run is still current.
6138    pub async fn query_selected_run<T: Serialize>(
6139        &self,
6140        query_name: &str,
6141        input: T,
6142    ) -> Result<Value> {
6143        let run_id = self
6144            .run_id
6145            .as_deref()
6146            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
6147        self.client
6148            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
6149            .await
6150    }
6151
6152    /// Await the final terminal outcome of the current continue-as-new chain.
6153    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
6154        self.result_target(options, None).await
6155    }
6156
6157    /// Await the final result without projecting Avro bytes through JSON.
6158    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
6159        self.result_avro_value_target(options, None).await
6160    }
6161
6162    /// Await the final result and decode it into a Serde application type.
6163    pub async fn result_typed<T: DeserializeOwned>(
6164        &self,
6165        options: WorkflowResultOptions,
6166    ) -> Result<T> {
6167        let result = self.result_avro_value(options).await?;
6168        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6169    }
6170
6171    /// Await only the run identity originally selected by this handle.
6172    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
6173        let run_id = self.run_id.as_deref().ok_or_else(|| {
6174            Error::Codec("run_id is required for selected-run result".to_string())
6175        })?;
6176        self.result_target(options, Some(run_id)).await
6177    }
6178
6179    /// Await the selected run's result on the lossless Avro Value surface.
6180    pub async fn result_selected_run_avro_value(
6181        &self,
6182        options: WorkflowResultOptions,
6183    ) -> Result<AvroValue> {
6184        let run_id = self.run_id.as_deref().ok_or_else(|| {
6185            Error::Codec("run_id is required for selected-run result".to_string())
6186        })?;
6187        self.result_avro_value_target(options, Some(run_id)).await
6188    }
6189
6190    /// Await the selected run and decode its result into a Serde type.
6191    pub async fn result_selected_run_typed<T: DeserializeOwned>(
6192        &self,
6193        options: WorkflowResultOptions,
6194    ) -> Result<T> {
6195        let result = self.result_selected_run_avro_value(options).await?;
6196        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6197    }
6198
6199    async fn result_avro_value_target(
6200        &self,
6201        options: WorkflowResultOptions,
6202        selected_run_id: Option<&str>,
6203    ) -> Result<AvroValue> {
6204        let started = Instant::now();
6205
6206        loop {
6207            let description = match selected_run_id {
6208                Some(run_id) => {
6209                    self.client
6210                        .describe_workflow_run(&self.workflow_id, run_id)
6211                        .await?
6212                }
6213                None => self.describe().await?,
6214            };
6215            if description.is_completed() {
6216                return description.output_avro_value.ok_or_else(|| {
6217                    Error::Codec(
6218                        "missing_payload_envelope: typed workflow result requires output_envelope"
6219                            .to_string(),
6220                    )
6221                });
6222            }
6223            if description.is_terminal() {
6224                let outcome =
6225                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6226                return Err(match outcome.kind {
6227                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6228                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6229                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6230                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6231                });
6232            }
6233            if started.elapsed() >= options.timeout {
6234                return Err(Error::Timeout);
6235            }
6236            tokio::time::sleep(options.poll_interval).await;
6237        }
6238    }
6239
6240    async fn result_target(
6241        &self,
6242        options: WorkflowResultOptions,
6243        selected_run_id: Option<&str>,
6244    ) -> Result<Value> {
6245        let started = Instant::now();
6246
6247        loop {
6248            let description = match selected_run_id {
6249                Some(run_id) => {
6250                    self.client
6251                        .describe_workflow_run(&self.workflow_id, run_id)
6252                        .await?
6253                }
6254                None => self.describe().await?,
6255            };
6256            if description.is_completed() {
6257                return Ok(description.output.unwrap_or(Value::Null));
6258            }
6259
6260            if description.is_terminal() {
6261                let outcome =
6262                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6263                return Err(match outcome.kind {
6264                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6265                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6266                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6267                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6268                });
6269            }
6270
6271            if started.elapsed() >= options.timeout {
6272                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
6273                    kind: WorkflowTerminalKind::TimedOut,
6274                    workflow_id: description
6275                        .workflow_id
6276                        .clone()
6277                        .unwrap_or_else(|| self.workflow_id.clone()),
6278                    run_id: description
6279                        .run_id
6280                        .clone()
6281                        .or_else(|| selected_run_id.map(str::to_string)),
6282                    reason: "result_wait_timeout".to_string(),
6283                    failure_category: Some("client_timeout".to_string()),
6284                    failure_id: None,
6285                    exception_type: None,
6286                    exception_class: None,
6287                    non_retryable: None,
6288                    message: Some(format!(
6289                        "workflow result was not terminal within {:?}",
6290                        options.timeout
6291                    )),
6292                    exception: None,
6293                    raw: description.raw_value(),
6294                }));
6295            }
6296
6297            tokio::time::sleep(options.poll_interval).await;
6298        }
6299    }
6300}
6301
6302#[derive(Clone, Copy, Debug)]
6303pub struct WorkflowResultOptions {
6304    pub poll_interval: Duration,
6305    pub timeout: Duration,
6306}
6307
6308impl Default for WorkflowResultOptions {
6309    fn default() -> Self {
6310        Self {
6311            poll_interval: Duration::from_millis(500),
6312            timeout: Duration::from_secs(30),
6313        }
6314    }
6315}
6316
6317#[derive(Clone, Debug, Deserialize)]
6318pub struct WorkflowDescription {
6319    pub workflow_id: Option<String>,
6320    pub run_id: Option<String>,
6321    pub workflow_type: Option<String>,
6322    pub status: Option<String>,
6323    #[serde(default)]
6324    pub closed_reason: Option<String>,
6325    #[serde(default)]
6326    pub error: Option<String>,
6327    #[serde(default)]
6328    pub failure: Option<Value>,
6329    #[serde(default)]
6330    pub exception: Option<Value>,
6331    #[serde(default)]
6332    pub failures: Vec<Value>,
6333    #[serde(default)]
6334    pub output: Option<Value>,
6335    #[serde(default)]
6336    pub output_envelope: Option<Value>,
6337    #[serde(skip)]
6338    pub output_avro_value: Option<AvroValue>,
6339    #[serde(flatten)]
6340    pub raw: HashMap<String, Value>,
6341}
6342
6343/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
6344#[derive(Clone, Debug, Deserialize)]
6345pub struct WorkflowStreamDescription {
6346    pub stream_name: String,
6347    pub status: String,
6348    pub last_offset: i64,
6349    pub total_items: u64,
6350    pub pending_items: u64,
6351    #[serde(default)]
6352    pub opened_at: Option<String>,
6353    #[serde(default)]
6354    pub last_appended_at: Option<String>,
6355    #[serde(default)]
6356    pub closed_at: Option<String>,
6357    #[serde(default)]
6358    pub error_reason: Option<String>,
6359    #[serde(default)]
6360    pub retention_seconds: Option<u64>,
6361    #[serde(flatten)]
6362    pub raw: HashMap<String, Value>,
6363}
6364
6365impl WorkflowStreamDescription {
6366    pub fn is_terminal(&self) -> bool {
6367        matches!(self.status.as_str(), "closed" | "errored")
6368    }
6369}
6370
6371/// One item for direct or replay-safe append.
6372#[derive(Clone, Debug, Default)]
6373pub struct WorkflowStreamAppendItem {
6374    pub payload_envelope: Option<Value>,
6375    pub payload_reference: Option<String>,
6376    pub item_type: Option<String>,
6377    pub content_type: Option<String>,
6378    pub idempotency_key: Option<String>,
6379}
6380
6381impl WorkflowStreamAppendItem {
6382    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
6383    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
6384        let value = AvroValue::from_serialize(&payload)?;
6385        Ok(Self {
6386            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
6387            ..Self::default()
6388        })
6389    }
6390
6391    /// Preserve an external payload URI as an opaque service-contract reference.
6392    pub fn from_reference(reference: impl Into<String>) -> Self {
6393        Self {
6394            payload_reference: Some(reference.into()),
6395            ..Self::default()
6396        }
6397    }
6398
6399    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
6400        self.item_type = Some(item_type.into());
6401        self
6402    }
6403
6404    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
6405        self.content_type = Some(content_type.into());
6406        self
6407    }
6408
6409    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
6410        self.idempotency_key = Some(idempotency_key.into());
6411        self
6412    }
6413
6414    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
6415        let mut item = serde_json::Map::new();
6416        if let Some(payload) = &self.payload_envelope {
6417            item.insert("payload".to_string(), payload.clone());
6418            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
6419        }
6420        if let Some(reference) = &self.payload_reference {
6421            item.insert("payload_reference".to_string(), json!(reference));
6422        }
6423        if let Some(item_type) = &self.item_type {
6424            item.insert("item_type".to_string(), json!(item_type));
6425        }
6426        if let Some(content_type) = &self.content_type {
6427            item.insert("content_type".to_string(), json!(content_type));
6428        }
6429        if let Some(key) = derived_idempotency_key
6430            .as_ref()
6431            .or(self.idempotency_key.as_ref())
6432        {
6433            item.insert("idempotency_key".to_string(), json!(key));
6434        }
6435        Value::Object(item)
6436    }
6437}
6438
6439/// One durable item at its stable zero-based offset.
6440#[derive(Clone, Debug)]
6441pub struct WorkflowStreamItem {
6442    pub offset: u64,
6443    pub payload: Option<Value>,
6444    pub payload_envelope: Option<Value>,
6445    pub payload_reference: Option<String>,
6446    pub payload_codec: Option<String>,
6447    pub idempotency_key: Option<String>,
6448    pub item_type: Option<String>,
6449    pub content_type: Option<String>,
6450    pub origin: Option<String>,
6451    pub origin_reference: Option<String>,
6452    pub emitted_at: Option<String>,
6453    pub raw: Value,
6454}
6455
6456/// One bounded at-least-once subscription page.
6457#[derive(Clone, Debug)]
6458pub struct WorkflowStreamPage {
6459    pub stream: WorkflowStreamDescription,
6460    pub items: Vec<WorkflowStreamItem>,
6461    pub next_offset: u64,
6462    pub terminal: bool,
6463}
6464
6465/// Durable acceptance and deduplication outcome for an append request.
6466#[derive(Clone, Debug)]
6467pub struct WorkflowStreamAppendResult {
6468    pub stream: WorkflowStreamDescription,
6469    pub accepted_offsets: Vec<u64>,
6470    pub accepted: u64,
6471    pub deduped: u64,
6472}
6473
6474#[derive(Deserialize)]
6475struct WorkflowStreamListResponse {
6476    #[serde(default)]
6477    streams: Vec<WorkflowStreamDescription>,
6478}
6479
6480#[derive(Deserialize)]
6481struct WorkflowStreamDescriptionResponse {
6482    stream: WorkflowStreamDescription,
6483}
6484
6485#[derive(Deserialize)]
6486struct WorkflowStreamPageResponse {
6487    stream: WorkflowStreamDescription,
6488    #[serde(default)]
6489    items: Vec<Value>,
6490    next_offset: u64,
6491    terminal: bool,
6492}
6493
6494#[derive(Deserialize)]
6495struct WorkflowStreamAppendResponse {
6496    stream: WorkflowStreamDescription,
6497    #[serde(default)]
6498    accepted_offsets: Vec<u64>,
6499    accepted: u64,
6500    deduped: u64,
6501}
6502
6503impl WorkflowDescription {
6504    pub fn is_completed(&self) -> bool {
6505        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6506    }
6507
6508    pub fn is_terminal(&self) -> bool {
6509        matches!(
6510            self.status.as_deref(),
6511            Some(
6512                "completed"
6513                    | "Completed"
6514                    | "failed"
6515                    | "Failed"
6516                    | "cancelled"
6517                    | "Cancelled"
6518                    | "terminated"
6519                    | "Terminated"
6520                    | "timed_out"
6521                    | "TimedOut",
6522            )
6523        )
6524    }
6525
6526    fn decode_payloads(&mut self) -> Result<()> {
6527        if let Some(envelope) = &self.output_envelope {
6528            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6529            self.output = Some(value.clone().into_json()?);
6530            self.output_avro_value = Some(value);
6531        }
6532
6533        Ok(())
6534    }
6535
6536    fn raw_value(&self) -> Value {
6537        let mut data = self.raw.clone();
6538        data.insert(
6539            "workflow_id".to_string(),
6540            self.workflow_id
6541                .clone()
6542                .map(Value::String)
6543                .unwrap_or(Value::Null),
6544        );
6545        data.insert(
6546            "run_id".to_string(),
6547            self.run_id
6548                .clone()
6549                .map(Value::String)
6550                .unwrap_or(Value::Null),
6551        );
6552        data.insert(
6553            "workflow_type".to_string(),
6554            self.workflow_type
6555                .clone()
6556                .map(Value::String)
6557                .unwrap_or(Value::Null),
6558        );
6559        data.insert(
6560            "status".to_string(),
6561            self.status
6562                .clone()
6563                .map(Value::String)
6564                .unwrap_or(Value::Null),
6565        );
6566        data.insert(
6567            "closed_reason".to_string(),
6568            self.closed_reason
6569                .clone()
6570                .map(Value::String)
6571                .unwrap_or(Value::Null),
6572        );
6573        if let Some(failure) = &self.failure {
6574            data.insert("failure".to_string(), failure.clone());
6575        }
6576        if let Some(exception) = &self.exception {
6577            data.insert("exception".to_string(), exception.clone());
6578        }
6579        Value::Object(data.into_iter().collect())
6580    }
6581}
6582
6583fn workflow_terminal_outcome(
6584    description: &WorkflowDescription,
6585    workflow_id: &str,
6586    run_id: Option<&str>,
6587) -> WorkflowTerminalOutcome {
6588    let terminal_kind = description
6589        .closed_reason
6590        .as_deref()
6591        .or(description.status.as_deref())
6592        .unwrap_or("failed")
6593        .to_ascii_lowercase();
6594    let kind = match terminal_kind.as_str() {
6595        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6596        "terminated" => WorkflowTerminalKind::Terminated,
6597        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6598        _ => WorkflowTerminalKind::Failed,
6599    };
6600    let default_reason = match kind {
6601        WorkflowTerminalKind::Failed => "workflow_failed",
6602        WorkflowTerminalKind::Cancelled => "cancelled",
6603        WorkflowTerminalKind::Terminated => "terminated",
6604        WorkflowTerminalKind::TimedOut => "timed_out",
6605    };
6606    let failure = description
6607        .failure
6608        .as_ref()
6609        .filter(|value| value.is_object());
6610    let nested_failure = failure
6611        .and_then(|value| value.get("failures"))
6612        .and_then(Value::as_array)
6613        .and_then(|failures| failures.last())
6614        .or_else(|| description.failures.last());
6615    let exception = description
6616        .exception
6617        .clone()
6618        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6619        .or_else(|| {
6620            nested_failure
6621                .and_then(|value| value.get("exception_payload"))
6622                .cloned()
6623        });
6624    let string_field = |name: &str| {
6625        failure
6626            .and_then(|value| value.get(name))
6627            .and_then(Value::as_str)
6628            .or_else(|| {
6629                nested_failure
6630                    .and_then(|value| value.get(name))
6631                    .and_then(Value::as_str)
6632            })
6633            .map(str::to_string)
6634    };
6635    let exception_field = |name: &str| {
6636        exception
6637            .as_ref()
6638            .and_then(|value| value.get(name))
6639            .and_then(Value::as_str)
6640            .map(str::to_string)
6641    };
6642    let message = description
6643        .error
6644        .clone()
6645        .or_else(|| string_field("message"))
6646        .or_else(|| exception_field("message"));
6647    let reason = description
6648        .raw
6649        .get("reason")
6650        .and_then(Value::as_str)
6651        .map(str::to_string)
6652        .or_else(|| {
6653            failure
6654                .and_then(|value| value.get("reason"))
6655                .and_then(Value::as_str)
6656                .map(str::to_string)
6657        })
6658        .or_else(|| description.closed_reason.clone())
6659        .unwrap_or_else(|| default_reason.to_string());
6660    let failure_id = string_field("failure_id").or_else(|| {
6661        nested_failure
6662            .and_then(|value| value.get("id"))
6663            .and_then(Value::as_str)
6664            .map(str::to_string)
6665    });
6666
6667    WorkflowTerminalOutcome {
6668        kind,
6669        workflow_id: description
6670            .workflow_id
6671            .clone()
6672            .unwrap_or_else(|| workflow_id.to_string()),
6673        run_id: description
6674            .run_id
6675            .clone()
6676            .or_else(|| run_id.map(str::to_string)),
6677        reason,
6678        failure_category: string_field("failure_category")
6679            .or_else(|| Some(default_reason.to_string())),
6680        failure_id,
6681        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6682        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6683        non_retryable: failure
6684            .and_then(|value| value.get("non_retryable"))
6685            .and_then(Value::as_bool)
6686            .or_else(|| {
6687                nested_failure
6688                    .and_then(|value| value.get("non_retryable"))
6689                    .and_then(Value::as_bool)
6690            }),
6691        message,
6692        exception,
6693        raw: description.raw_value(),
6694    }
6695}
6696
6697#[derive(Clone, Debug, Deserialize)]
6698pub struct RegisterWorkerResponse {
6699    pub worker_id: String,
6700    pub registered: bool,
6701    #[serde(default)]
6702    pub heartbeat_interval_seconds: Option<u64>,
6703    #[serde(default)]
6704    pub protocol_version: Option<String>,
6705    #[serde(default)]
6706    pub server_capabilities: Option<Value>,
6707}
6708
6709/// Result of gracefully removing a worker-plane registration.
6710#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6711pub struct WorkerDeregistrationEnvelope {
6712    pub worker_id: String,
6713    pub outcome: String,
6714    pub recovered_workflow_task_count: u64,
6715}
6716
6717#[derive(Clone, Debug, Deserialize)]
6718pub struct PollWorkflowTaskResponse {
6719    #[serde(default)]
6720    pub task: Option<WorkflowTask>,
6721    #[serde(default)]
6722    pub poll_status: Option<String>,
6723    #[serde(default)]
6724    pub reason: Option<String>,
6725    #[serde(default)]
6726    pub protocol_version: Option<String>,
6727    #[serde(default)]
6728    pub server_capabilities: Option<Value>,
6729}
6730
6731impl PollWorkflowTaskResponse {
6732    /// Classify this response without parsing server display text.
6733    pub fn outcome(&self) -> WorkerPollOutcome {
6734        worker_poll_outcome(
6735            self.task.is_some(),
6736            self.poll_status.as_deref(),
6737            self.reason.as_deref(),
6738        )
6739    }
6740}
6741
6742fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6743    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6744        return false;
6745    };
6746    let supported = capabilities
6747        .get("workflow_memo_updates")
6748        .and_then(Value::as_object)
6749        .and_then(|memo| memo.get("supported"))
6750        .and_then(Value::as_bool)
6751        == Some(true);
6752    let command_advertised = capabilities
6753        .get("supported_workflow_task_commands")
6754        .and_then(Value::as_array)
6755        .is_some_and(|commands| {
6756            commands
6757                .iter()
6758                .any(|command| command.as_str() == Some("upsert_memo"))
6759        });
6760    supported && command_advertised
6761}
6762
6763fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6764    commands
6765        .iter()
6766        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6767}
6768
6769#[derive(Clone, Debug, Deserialize)]
6770pub struct PollActivityTaskResponse {
6771    #[serde(default)]
6772    pub task: Option<ActivityTask>,
6773    #[serde(default)]
6774    pub poll_status: Option<String>,
6775    #[serde(default)]
6776    pub reason: Option<String>,
6777}
6778
6779impl PollActivityTaskResponse {
6780    /// Classify this response without parsing server display text.
6781    pub fn outcome(&self) -> WorkerPollOutcome {
6782        worker_poll_outcome(
6783            self.task.is_some(),
6784            self.poll_status.as_deref(),
6785            self.reason.as_deref(),
6786        )
6787    }
6788}
6789
6790#[derive(Clone, Debug, Deserialize)]
6791pub struct PollQueryTaskResponse {
6792    #[serde(default)]
6793    pub task: Option<QueryTask>,
6794    #[serde(default)]
6795    pub poll_status: Option<String>,
6796    #[serde(default)]
6797    pub reason: Option<String>,
6798}
6799
6800impl PollQueryTaskResponse {
6801    /// Classify this response without parsing server display text.
6802    pub fn outcome(&self) -> WorkerPollOutcome {
6803        worker_poll_outcome(
6804            self.task.is_some(),
6805            self.poll_status.as_deref(),
6806            self.reason.as_deref(),
6807        )
6808    }
6809}
6810
6811/// Stable classification for worker poll responses.
6812#[derive(Clone, Debug, PartialEq, Eq)]
6813pub enum WorkerPollOutcome {
6814    /// A task was leased and is available on the response.
6815    Task,
6816    /// No task was leased, but the worker should continue polling.
6817    Idle {
6818        poll_status: Option<String>,
6819        reason: Option<String>,
6820    },
6821    /// The server asked this worker to stop claiming new work.
6822    Stop {
6823        poll_status: Option<String>,
6824        reason: Option<String>,
6825    },
6826}
6827
6828impl WorkerPollOutcome {
6829    pub fn should_stop(&self) -> bool {
6830        matches!(self, Self::Stop { .. })
6831    }
6832}
6833
6834fn worker_poll_outcome(
6835    has_task: bool,
6836    poll_status: Option<&str>,
6837    reason: Option<&str>,
6838) -> WorkerPollOutcome {
6839    if worker_poll_is_stop(poll_status, reason) {
6840        return WorkerPollOutcome::Stop {
6841            poll_status: poll_status.map(str::to_string),
6842            reason: reason.map(str::to_string),
6843        };
6844    }
6845
6846    if has_task {
6847        WorkerPollOutcome::Task
6848    } else {
6849        WorkerPollOutcome::Idle {
6850            poll_status: poll_status.map(str::to_string),
6851            reason: reason.map(str::to_string),
6852        }
6853    }
6854}
6855
6856/// An ephemeral server-routed query task.
6857#[derive(Clone, Debug, Deserialize)]
6858pub struct QueryTask {
6859    pub query_task_id: String,
6860    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6861    #[serde(default)]
6862    pub observability_context: Option<Value>,
6863    #[serde(default)]
6864    pub dispatch_observability_context: Option<Value>,
6865    #[serde(default)]
6866    pub observability_links: Option<Value>,
6867    #[serde(default = "default_workflow_task_attempt")]
6868    pub query_task_attempt: u64,
6869    #[serde(default)]
6870    pub lease_owner: Option<String>,
6871    #[serde(default)]
6872    pub workflow_id: Option<String>,
6873    #[serde(default)]
6874    pub run_id: Option<String>,
6875    pub workflow_type: String,
6876    pub query_name: String,
6877    #[serde(
6878        default = "missing_task_payload_codec",
6879        deserialize_with = "deserialize_task_payload_codec"
6880    )]
6881    pub payload_codec: String,
6882    #[serde(default)]
6883    pub workflow_arguments: Option<Value>,
6884    #[serde(default)]
6885    pub query_arguments: Option<Value>,
6886    #[serde(default)]
6887    pub history_events: Vec<HistoryEvent>,
6888    #[serde(default)]
6889    pub history_export: Option<Value>,
6890    #[serde(default)]
6891    pub run_status: Option<String>,
6892}
6893
6894#[derive(Clone, Debug, Deserialize)]
6895pub struct WorkflowTask {
6896    pub task_id: String,
6897    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6898    #[serde(default)]
6899    pub observability_context: Option<Value>,
6900    #[serde(default)]
6901    pub dispatch_observability_context: Option<Value>,
6902    #[serde(default)]
6903    pub observability_links: Option<Value>,
6904    #[serde(default)]
6905    pub workflow_command_id: Option<String>,
6906    #[serde(default)]
6907    pub workflow_id: Option<String>,
6908    #[serde(default)]
6909    pub run_id: Option<String>,
6910    pub workflow_type: String,
6911    #[serde(default)]
6912    pub cancel_requested: bool,
6913    #[serde(
6914        default = "missing_task_payload_codec",
6915        deserialize_with = "deserialize_task_payload_codec"
6916    )]
6917    pub payload_codec: String,
6918    #[serde(default)]
6919    pub arguments: Option<Value>,
6920    #[serde(default)]
6921    pub history_events: Vec<HistoryEvent>,
6922    #[serde(default)]
6923    pub total_history_events: Option<u64>,
6924    #[serde(default)]
6925    pub history_size_bytes: Option<u64>,
6926    #[serde(default)]
6927    pub continue_as_new_recommended: Option<bool>,
6928    #[serde(default)]
6929    pub history_budget_pressure: Option<String>,
6930    #[serde(default)]
6931    pub next_history_page_token: Option<String>,
6932    #[serde(default = "default_workflow_task_attempt")]
6933    pub workflow_task_attempt: u64,
6934    #[serde(default)]
6935    pub workflow_signal_id: Option<String>,
6936    #[serde(default)]
6937    pub signal_name: Option<String>,
6938    #[serde(default)]
6939    pub signal_arguments: Option<Value>,
6940    #[serde(default)]
6941    pub workflow_update_id: Option<String>,
6942    #[serde(default)]
6943    pub update_name: Option<String>,
6944    #[serde(default)]
6945    pub lease_owner: Option<String>,
6946}
6947
6948impl WorkflowTask {
6949    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6950        self.history_events.extend(page.history_events);
6951
6952        if page.total_history_events.is_some() {
6953            self.total_history_events = page.total_history_events;
6954        }
6955
6956        self.next_history_page_token = page
6957            .next_history_page_token
6958            .filter(|token| !token.is_empty());
6959    }
6960}
6961
6962#[derive(Clone, Debug, Deserialize)]
6963struct WorkflowTaskHistoryPage {
6964    #[serde(default)]
6965    history_events: Vec<HistoryEvent>,
6966    #[serde(default)]
6967    total_history_events: Option<u64>,
6968    #[serde(default)]
6969    next_history_page_token: Option<String>,
6970}
6971
6972#[derive(Clone, Debug, Deserialize)]
6973pub struct ActivityTask {
6974    pub task_id: String,
6975    #[serde(default)]
6976    pub workflow_id: Option<String>,
6977    #[serde(default)]
6978    pub run_id: Option<String>,
6979    #[serde(default)]
6980    pub activity_execution_id: Option<String>,
6981    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6982    #[serde(default)]
6983    pub observability_context: Option<Value>,
6984    #[serde(default)]
6985    pub dispatch_observability_context: Option<Value>,
6986    #[serde(default)]
6987    pub observability_links: Option<Value>,
6988    #[serde(default)]
6989    pub activity_attempt_id: Option<String>,
6990    #[serde(default)]
6991    pub attempt_id: Option<String>,
6992    pub activity_type: String,
6993    #[serde(
6994        default = "missing_task_payload_codec",
6995        deserialize_with = "deserialize_task_payload_codec"
6996    )]
6997    pub payload_codec: String,
6998    #[serde(default)]
6999    pub arguments: Option<Value>,
7000    #[serde(default = "default_attempt_number")]
7001    pub attempt_number: u64,
7002    #[serde(default)]
7003    pub lease_owner: Option<String>,
7004}
7005
7006#[derive(Clone, Debug, Serialize, Deserialize)]
7007pub struct HistoryEvent {
7008    #[serde(alias = "type")]
7009    pub event_type: String,
7010    #[serde(default)]
7011    pub payload: Value,
7012    #[serde(flatten)]
7013    pub raw: HashMap<String, Value>,
7014}
7015
7016/// One decoded signal in the committed workflow-history snapshot.
7017#[derive(Clone, Debug, PartialEq)]
7018pub struct QuerySignal {
7019    pub id: Option<String>,
7020    pub name: String,
7021    pub arguments: Vec<Value>,
7022    avro_arguments: Vec<AvroValue>,
7023    pub workflow_sequence: Option<u64>,
7024}
7025
7026impl QuerySignal {
7027    /// Lossless fixed Avro Value arguments for this committed signal.
7028    pub fn arguments_avro_value(&self) -> &[AvroValue] {
7029        &self.avro_arguments
7030    }
7031}
7032
7033/// Immutable state supplied to a registered query handler.
7034///
7035/// This context intentionally exposes no activity, signal-wait, or command
7036/// APIs. Query handlers inspect committed history and return a value; query
7037/// completion does not append an event or advance deterministic execution.
7038#[derive(Clone, Debug)]
7039pub struct QueryContext {
7040    pub workflow_id: Option<String>,
7041    pub run_id: Option<String>,
7042    pub workflow_type: String,
7043    pub run_status: Option<String>,
7044    workflow_input: Value,
7045    workflow_input_avro_value: AvroValue,
7046    history_events: Arc<Vec<HistoryEvent>>,
7047    signal_events: Arc<Vec<QuerySignal>>,
7048}
7049
7050impl QueryContext {
7051    /// The normalized argument list used to start the workflow.
7052    pub fn workflow_input(&self) -> &Value {
7053        &self.workflow_input
7054    }
7055
7056    /// The lossless fixed Avro Value argument list used to start the workflow.
7057    pub fn workflow_input_avro_value(&self) -> &AvroValue {
7058        &self.workflow_input_avro_value
7059    }
7060
7061    /// The immutable committed history used for this query snapshot.
7062    pub fn history_events(&self) -> &[HistoryEvent] {
7063        self.history_events.as_slice()
7064    }
7065
7066    /// All decoded signals in committed workflow order.
7067    pub fn signal_events(&self) -> &[QuerySignal] {
7068        self.signal_events.as_slice()
7069    }
7070
7071    /// Decoded argument lists for each committed signal with `signal_name`.
7072    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
7073        self.signal_events
7074            .iter()
7075            .filter(|signal| signal.name == signal_name)
7076            .map(|signal| signal.arguments.clone())
7077            .collect()
7078    }
7079
7080    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
7081    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
7082        self.signal_events
7083            .iter()
7084            .filter(|signal| signal.name == signal_name)
7085            .map(|signal| signal.avro_arguments.clone())
7086            .collect()
7087    }
7088}
7089
7090#[derive(Clone, Debug, Deserialize)]
7091pub struct ActivityHeartbeatResponse {
7092    #[serde(default)]
7093    pub cancel_requested: bool,
7094    #[serde(default)]
7095    pub heartbeat_recorded: bool,
7096    #[serde(default)]
7097    pub can_continue: Option<bool>,
7098    #[serde(default)]
7099    pub reason: Option<String>,
7100    #[serde(default)]
7101    pub run_closed_reason: Option<String>,
7102    #[serde(default)]
7103    pub run_closed_at: Option<String>,
7104    #[serde(default)]
7105    pub lease_expires_at: Option<String>,
7106    #[serde(default)]
7107    pub last_heartbeat_at: Option<String>,
7108}
7109
7110impl ActivityHeartbeatResponse {
7111    /// Whether the activity should stop instead of attempting completion.
7112    pub fn should_stop(&self) -> bool {
7113        self.cancel_requested || self.can_continue == Some(false)
7114    }
7115}
7116
7117fn missing_task_payload_codec() -> String {
7118    MISSING_TASK_PAYLOAD_CODEC.to_string()
7119}
7120
7121fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
7122where
7123    D: Deserializer<'de>,
7124{
7125    Ok(match Value::deserialize(deserializer)? {
7126        Value::String(codec) => codec,
7127        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
7128        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
7129    })
7130}
7131
7132fn default_workflow_task_attempt() -> u64 {
7133    1
7134}
7135
7136fn default_attempt_number() -> u64 {
7137    1
7138}
7139
7140type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7141type WorkflowHandler =
7142    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
7143type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
7144type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
7145type ReplayedWorkflowHandler =
7146    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
7147type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7148type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
7149type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7150type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7151type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7152type ReplayedQueryHandler = Arc<
7153    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
7154        + Send
7155        + Sync,
7156>;
7157type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
7158
7159struct ReplayedWorkflowInvocation {
7160    future: WorkflowFuture,
7161    snapshot: WorkflowStateSnapshot,
7162}
7163
7164#[derive(Clone)]
7165struct RegisteredWorkflow {
7166    execute: WorkflowHandler,
7167    replay: Option<ReplayedWorkflowHandler>,
7168    state_type: Option<TypeId>,
7169    definition_fingerprint: Option<String>,
7170}
7171
7172fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
7173    names
7174        .iter()
7175        .map(|name| {
7176            json!({
7177                "name": name,
7178                "parameters": [{
7179                    "name": "args",
7180                    "position": 0,
7181                    "required": false,
7182                    "variadic": true,
7183                    "type": null,
7184                    "allows_null": true,
7185                    "default_available": false,
7186                    "default": null,
7187                }],
7188            })
7189        })
7190        .collect()
7191}
7192
7193#[derive(Debug)]
7194struct WorkflowTaskDecision {
7195    commands: Vec<Value>,
7196    message_stream_cursors: Vec<Value>,
7197    message_stream_waits: Vec<Value>,
7198    cancellation_delivery: Option<CancellationDelivery>,
7199    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
7200    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
7201}
7202
7203enum PreparedWorkflowTask {
7204    Decision(WorkflowTaskDecision),
7205    Execution {
7206        task: WorkflowTask,
7207        context: WorkflowContext,
7208        future: WorkflowFuture,
7209    },
7210}
7211
7212impl WorkflowTaskDecision {
7213    fn without_message_streams(commands: Vec<Value>) -> Self {
7214        Self {
7215            commands,
7216            message_stream_cursors: Vec::new(),
7217            message_stream_waits: Vec::new(),
7218            cancellation_delivery: None,
7219            cancellation_scope_opening: None,
7220            cancellation_scope_delivery: None,
7221        }
7222    }
7223}
7224
7225#[derive(Clone)]
7226enum RegisteredQuery {
7227    Snapshot(QueryHandler),
7228    Replayed {
7229        state_type: TypeId,
7230        handler: ReplayedQueryHandler,
7231    },
7232}
7233
7234#[derive(Clone, Debug)]
7235pub struct WorkerHeartbeatObservation {
7236    pub worker_id: String,
7237    pub task_queue: String,
7238    pub acknowledged_at_unix_millis: u64,
7239    pub acknowledgement: Value,
7240}
7241
7242/// Bounded retry policy for worker poll acquisition and worker heartbeats.
7243///
7244/// Expected empty long polls and explicit Server capacity backpressure are
7245/// normal worker states. Capacity backpressure honors the advertised retry
7246/// delay without consuming this retry budget. Other transport failures,
7247/// retryable HTTP 408/429 responses, and server errors are retried with capped
7248/// exponential backoff. Authentication, protocol, codec, and handler failures
7249/// are never retried by the worker.
7250/// Explicit storage admission pauses also preserve the already-serialized worker
7251/// request without consuming this budget or rerunning its handler. The delay is
7252/// capped by `max_backoff`, except an explicit completion deferral must honor
7253/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
7254/// completion retries remain bounded by the original cleanup deadline.
7255/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
7256/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
7257/// and `max_retries = 0` disables ordinary retries in either mode.
7258#[derive(Clone, Copy, Debug)]
7259pub struct WorkerRetryPolicy {
7260    /// Number of retries after the initial request fails.
7261    pub max_retries: usize,
7262    /// Delay before the first retry.
7263    pub initial_backoff: Duration,
7264    /// Maximum delay between retries.
7265    pub max_backoff: Duration,
7266}
7267
7268impl Default for WorkerRetryPolicy {
7269    fn default() -> Self {
7270        Self {
7271            max_retries: 5,
7272            initial_backoff: Duration::from_millis(100),
7273            max_backoff: Duration::from_secs(5),
7274        }
7275    }
7276}
7277
7278#[derive(Clone, Debug)]
7279struct WorkerStorageAdmission {
7280    policy: WorkerRetryPolicy,
7281    stop: Arc<AtomicBool>,
7282    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
7283}
7284
7285struct StopWorkerOnDrop(Arc<AtomicBool>);
7286
7287impl Drop for StopWorkerOnDrop {
7288    fn drop(&mut self) {
7289        self.0.store(true, Ordering::SeqCst);
7290    }
7291}
7292
7293async fn wait_for_worker_stop(stop: &AtomicBool) {
7294    while !stop.load(Ordering::SeqCst) {
7295        tokio::time::sleep(Duration::from_millis(100)).await;
7296    }
7297}
7298
7299#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7300enum ManagedPollOutcome {
7301    Idle,
7302    Handled,
7303    Stop,
7304}
7305
7306#[derive(Clone)]
7307pub struct Worker {
7308    #[cfg(feature = "telemetry")]
7309    telemetry: Option<telemetry::ExecutionTelemetry>,
7310    client: Client,
7311    worker_id: String,
7312    task_queue: String,
7313    workflows: HashMap<String, RegisteredWorkflow>,
7314    activities: HashMap<String, ActivityHandler>,
7315    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
7316    signals: HashMap<String, Vec<String>>,
7317    updates: HashMap<String, HashMap<String, UpdateHandler>>,
7318    registration_definitions:
7319        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
7320    registration_error: Option<DuplicateRegistrationError>,
7321    max_concurrent_workflow_tasks: usize,
7322    max_concurrent_activity_tasks: usize,
7323    workflow_capacity: Arc<worker_capacity::TaskCapacity>,
7324    activity_capacity: Arc<worker_capacity::TaskCapacity>,
7325    poll_timeout: Duration,
7326    heartbeat_interval: Duration,
7327    retry_policy: WorkerRetryPolicy,
7328    recover_transient_outages: bool,
7329    run_stop: Option<Arc<AtomicBool>>,
7330    heartbeat_observer: Option<WorkerHeartbeatObserver>,
7331    cooperative_cancellation_enabled: bool,
7332    nexus_cooperative_cancellation_enabled: bool,
7333    allow_cancellation_scope_authoring: bool,
7334    allow_cancellation_scope_delivery: bool,
7335    cooperative_registration_confirmed: Arc<AtomicBool>,
7336    nexus_registration_confirmed: Arc<AtomicBool>,
7337    local_registration_confirmed: Arc<AtomicBool>,
7338    session_registration_confirmed: Arc<AtomicBool>,
7339    sticky_registration_confirmed: Arc<AtomicBool>,
7340    require_query_task_authority: bool,
7341    query_authority_confirmed: Arc<AtomicBool>,
7342    resource_capabilities: Vec<String>,
7343    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
7344}
7345
7346impl Worker {
7347    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
7348        Self {
7349            #[cfg(feature = "telemetry")]
7350            telemetry: None,
7351            client,
7352            worker_id: default_worker_id(),
7353            task_queue: task_queue.into(),
7354            workflows: HashMap::new(),
7355            activities: HashMap::new(),
7356            queries: HashMap::new(),
7357            signals: HashMap::new(),
7358            updates: HashMap::new(),
7359            registration_definitions: HashMap::new(),
7360            registration_error: None,
7361            max_concurrent_workflow_tasks: 10,
7362            max_concurrent_activity_tasks: 10,
7363            workflow_capacity: worker_capacity::TaskCapacity::new(10),
7364            activity_capacity: worker_capacity::TaskCapacity::new(10),
7365            poll_timeout: Duration::from_secs(30),
7366            heartbeat_interval: Duration::from_secs(60),
7367            retry_policy: WorkerRetryPolicy::default(),
7368            recover_transient_outages: false,
7369            run_stop: None,
7370            heartbeat_observer: None,
7371            cooperative_cancellation_enabled: false,
7372            nexus_cooperative_cancellation_enabled: false,
7373            allow_cancellation_scope_authoring: false,
7374            allow_cancellation_scope_delivery: false,
7375            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
7376            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
7377            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
7378            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
7379            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
7380            require_query_task_authority: false,
7381            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
7382            resource_capabilities: Vec::new(),
7383            sessions: Arc::new(Mutex::new(HashMap::new())),
7384        }
7385    }
7386
7387    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
7388        self.worker_id = worker_id.into();
7389        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7390        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7391        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7392        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
7393        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
7394        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
7395        self.client.reset_sticky_cache();
7396        self.sessions = Arc::new(Mutex::new(HashMap::new()));
7397        self
7398    }
7399
7400    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
7401        self.poll_timeout = timeout;
7402        self
7403    }
7404
7405    /// Opt in to execution spans using application-owned OpenTelemetry providers.
7406    /// No exporter, logging bridge, global provider or Server carrier is installed.
7407    #[cfg(feature = "telemetry")]
7408    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
7409        self.client.execution_telemetry = Some(telemetry.clone());
7410        self.telemetry = Some(telemetry);
7411        self
7412    }
7413
7414    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
7415        self.heartbeat_interval = interval;
7416        self
7417    }
7418
7419    /// Require original query timing and non-renewing runtime observation.
7420    ///
7421    /// Registration refuses before creating a Worker unless protocol 1.20 and
7422    /// the runtime's `query_task_authority` capability are available. By default,
7423    /// older Servers retain their weaker, disclosed local-timing behavior.
7424    pub fn require_query_task_authority(mut self, required: bool) -> Self {
7425        self.require_query_task_authority = required;
7426        self
7427    }
7428
7429    /// Explicitly enable inline local activities in this workflow worker.
7430    ///
7431    /// The worker advertises the capability to Server only when enabled.
7432    /// These callbacks must yield to Tokio and have idempotent side effects.
7433    /// Cooperative prepared local supervision is a separate capability.
7434    pub fn local_activities(mut self, enabled: bool) -> Self {
7435        self.client.local_activities_enabled = enabled;
7436        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7437        self
7438    }
7439
7440    /// Opt in to separate cooperative workflow cancellation requests.
7441    ///
7442    /// Registration requires the Server to acknowledge this exact worker,
7443    /// namespace, queue and capabilities with compatible protocol 1.20. Task
7444    /// processing uses canonical delivery and activity ownership fences.
7445    /// Existing terminal cancel and terminate operations remain terminal.
7446    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
7447    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
7448    /// and [`Worker::run_until`] register automatically.
7449    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
7450        self.cooperative_cancellation_enabled = enabled;
7451        self.client.cooperative_worker_protocol = enabled;
7452        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7453        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7454        if !enabled {
7455            self.nexus_cooperative_cancellation_enabled = false;
7456        }
7457        self
7458    }
7459
7460    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
7461    ///
7462    /// This also enables ordinary cooperative cancellation. Registration checks
7463    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
7464    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
7465        let mut worker = if enabled {
7466            self.cooperative_cancellation(true)
7467        } else {
7468            self
7469        };
7470        worker.nexus_cooperative_cancellation_enabled = enabled;
7471        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7472        worker
7473    }
7474
7475    /// Enable candidate scope authoring without advertising scoped execution.
7476    #[doc(hidden)]
7477    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
7478        self.allow_cancellation_scope_authoring = enabled;
7479        self
7480    }
7481
7482    /// Enable the candidate scoped call consumer with canonical authoring.
7483    #[doc(hidden)]
7484    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
7485        self.allow_cancellation_scope_delivery = enabled;
7486        self
7487    }
7488
7489    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
7490    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
7491        self.retry_policy = policy;
7492        self
7493    }
7494
7495    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7496    ///
7497    /// Retries preserve the poll request identity and use capped exponential
7498    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7499    /// An in-flight poll is allowed to finish so leased work is not discarded.
7500    /// Authentication, protocol, codec, handler and task settlement failures
7501    /// remain errors. Registration and deregistration are not retried here.
7502    ///
7503    /// The default is disabled, preserving the bounded retry contract.
7504    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7505    /// even when this option is enabled.
7506    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7507        self.recover_transient_outages = enabled;
7508        self
7509    }
7510
7511    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7512    where
7513        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7514    {
7515        self.heartbeat_observer = Some(Arc::new(observer));
7516        self
7517    }
7518
7519    /// Bound simultaneous claimed workflow tasks, including loading and settlement.
7520    /// Defaults to 10. Use 1 for serial workflow-task execution.
7521    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7522        self.max_concurrent_workflow_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7523        self.workflow_capacity =
7524            worker_capacity::TaskCapacity::new(self.max_concurrent_workflow_tasks);
7525        self
7526    }
7527
7528    /// Bound simultaneous remote activity tasks, including loading and settlement.
7529    /// Defaults to 10. Use 1 for serial activity-task execution.
7530    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7531        self.max_concurrent_activity_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7532        self.activity_capacity =
7533            worker_capacity::TaskCapacity::new(self.max_concurrent_activity_tasks);
7534        self
7535    }
7536
7537    /// Validate local handler admission without making a Server request.
7538    ///
7539    /// Registration methods retain their existing signatures. A duplicate keeps
7540    /// the original handler and makes this Worker invalid, including its clones.
7541    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7542    /// any network request. Build a new Worker to correct an invalid configuration.
7543    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7544        match &self.registration_error {
7545            Some(error) => Err(error.clone()),
7546            None => Ok(()),
7547        }
7548    }
7549
7550    #[track_caller]
7551    fn admit_registration<F>(
7552        &mut self,
7553        handler_kind: RegistrationKind,
7554        workflow_type: Option<&str>,
7555        handler_name: &str,
7556        method: &'static str,
7557    ) -> bool {
7558        let location = std::panic::Location::caller();
7559        let definition = HandlerRegistration {
7560            method,
7561            handler_type: type_name::<F>(),
7562            file: location.file(),
7563            line: location.line(),
7564            column: location.column(),
7565        };
7566        let key = (
7567            handler_kind,
7568            workflow_type.map(str::to_owned),
7569            handler_name.to_owned(),
7570        );
7571        if let Some(first_definition) = self.registration_definitions.get(&key) {
7572            if self.registration_error.is_none() {
7573                self.registration_error = Some(DuplicateRegistrationError {
7574                    handler_kind,
7575                    workflow_type: key.1.clone(),
7576                    handler_name: key.2.clone(),
7577                    first_definition: first_definition.clone(),
7578                    second_definition: definition,
7579                });
7580            }
7581            return false;
7582        }
7583        self.registration_definitions.insert(key, definition);
7584        true
7585    }
7586
7587    /// Register a workflow handler.
7588    ///
7589    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7590    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7591    /// while acquiring or decoding a worker task remain worker-operation
7592    /// failures and do not get converted into workflow outcomes.
7593    #[track_caller]
7594    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7595    where
7596        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7597        Fut: Future<Output = Result<Value>> + Send + 'static,
7598    {
7599        let workflow_type = workflow_type.into();
7600        if !self.admit_registration::<F>(
7601            RegistrationKind::Workflow,
7602            None,
7603            &workflow_type,
7604            "register_workflow",
7605        ) {
7606            return;
7607        }
7608        let handler = Arc::new(handler);
7609        self.workflows.insert(
7610            workflow_type,
7611            RegisteredWorkflow {
7612                execute: Arc::new(move |ctx, input| {
7613                    let handler = Arc::clone(&handler);
7614                    Ok(Box::pin(async move {
7615                        let result = handler(ctx, input.into_json()?).await?;
7616                        AvroValue::from_serialize(&result)
7617                    }))
7618                }),
7619                replay: None,
7620                state_type: None,
7621                definition_fingerprint: None,
7622            },
7623        );
7624    }
7625
7626    /// Register a workflow with one Serde request value and a Serde result.
7627    ///
7628    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7629    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7630    /// workflow-specific schema. A task must contain zero arguments for a unit
7631    /// request or exactly one argument for every other request type.
7632    ///
7633    /// See the runnable
7634    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7635    /// for typed workflow and activity contracts with retry and timeout policy.
7636    #[track_caller]
7637    pub fn register_typed_workflow<I, O, F, Fut>(
7638        &mut self,
7639        workflow_type: impl Into<String>,
7640        handler: F,
7641    ) where
7642        I: DeserializeOwned + Send + 'static,
7643        O: Serialize + Send + 'static,
7644        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7645        Fut: Future<Output = Result<O>> + Send + 'static,
7646    {
7647        let workflow_type = workflow_type.into();
7648        if !self.admit_registration::<F>(
7649            RegistrationKind::Workflow,
7650            None,
7651            &workflow_type,
7652            "register_typed_workflow",
7653        ) {
7654            return;
7655        }
7656        let handler_name = workflow_type.clone();
7657        let handler = Arc::new(handler);
7658        self.workflows.insert(
7659            workflow_type,
7660            RegisteredWorkflow {
7661                execute: Arc::new(move |ctx, input| {
7662                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7663                    let handler = Arc::clone(&handler);
7664                    let handler_name = handler_name.clone();
7665                    Ok(Box::pin(async move {
7666                        let result = handler(ctx, input).await?;
7667                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7668                    }))
7669                }),
7670                replay: None,
7671                state_type: None,
7672                definition_fingerprint: None,
7673            },
7674        );
7675    }
7676
7677    /// Register a workflow on the lossless fixed Avro Value surface.
7678    #[track_caller]
7679    pub fn register_workflow_avro_value<F, Fut>(
7680        &mut self,
7681        workflow_type: impl Into<String>,
7682        handler: F,
7683    ) where
7684        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7685        Fut: Future<Output = Result<AvroValue>> + 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_workflow_avro_value",
7693        ) {
7694            return;
7695        }
7696        self.workflows.insert(
7697            workflow_type,
7698            RegisteredWorkflow {
7699                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7700                replay: None,
7701                state_type: None,
7702                definition_fingerprint: None,
7703            },
7704        );
7705    }
7706
7707    /// Register a workflow whose typed instance state can be reconstructed for queries.
7708    ///
7709    /// `state_factory` creates a fresh instance for every normal workflow task and
7710    /// query replay. The workflow handler is the single source of truth for state
7711    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7712    /// resolve. Query replay runs this same handler over committed history and
7713    /// discards any commands it would emit.
7714    #[track_caller]
7715    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7716        &mut self,
7717        workflow_type: impl Into<String>,
7718        state_factory: Factory,
7719        handler: F,
7720    ) where
7721        S: Clone + Send + Sync + 'static,
7722        Factory: Fn() -> S + Send + Sync + 'static,
7723        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7724        Fut: Future<Output = Result<Value>> + Send + 'static,
7725    {
7726        let workflow_type = workflow_type.into();
7727        if !self.admit_registration::<F>(
7728            RegistrationKind::Workflow,
7729            None,
7730            &workflow_type,
7731            "register_replayed_workflow",
7732        ) {
7733            return;
7734        }
7735        let state_factory = Arc::new(state_factory);
7736        let handler = Arc::new(handler);
7737
7738        let execute_factory = Arc::clone(&state_factory);
7739        let execute_handler = Arc::clone(&handler);
7740        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7741            let state = WorkflowInstance::new(execute_factory());
7742            let handler = Arc::clone(&execute_handler);
7743            Ok(Box::pin(async move {
7744                let result = handler(ctx, input.into_json()?, state).await?;
7745                AvroValue::from_serialize(&result)
7746            }) as WorkflowFuture)
7747        });
7748
7749        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7750            let state = WorkflowInstance::new(state_factory());
7751            let snapshot_state = state.clone();
7752            let snapshot: WorkflowStateSnapshot =
7753                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7754            let replay_handler = Arc::clone(&handler);
7755            let future = async move {
7756                let result = replay_handler(ctx, input.into_json()?, state).await?;
7757                AvroValue::from_serialize(&result)
7758            };
7759            Ok(ReplayedWorkflowInvocation {
7760                future: Box::pin(future),
7761                snapshot,
7762            })
7763        });
7764
7765        self.workflows.insert(
7766            workflow_type,
7767            RegisteredWorkflow {
7768                execute,
7769                replay: Some(replay),
7770                state_type: Some(TypeId::of::<S>()),
7771                definition_fingerprint: None,
7772            },
7773        );
7774    }
7775
7776    /// Register a replayable workflow with one Serde request value and result.
7777    ///
7778    /// Normal task execution and instance-state query replay both decode and
7779    /// encode through the fixed Avro Value codec. The state factory and handler
7780    /// otherwise follow [`Worker::register_replayed_workflow`].
7781    #[track_caller]
7782    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7783        &mut self,
7784        workflow_type: impl Into<String>,
7785        state_factory: Factory,
7786        handler: F,
7787    ) where
7788        I: DeserializeOwned + Send + 'static,
7789        O: Serialize + Send + 'static,
7790        S: Clone + Send + Sync + 'static,
7791        Factory: Fn() -> S + Send + Sync + 'static,
7792        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7793        Fut: Future<Output = Result<O>> + Send + 'static,
7794    {
7795        let workflow_type = workflow_type.into();
7796        if !self.admit_registration::<F>(
7797            RegistrationKind::Workflow,
7798            None,
7799            &workflow_type,
7800            "register_typed_replayed_workflow",
7801        ) {
7802            return;
7803        }
7804        let state_factory = Arc::new(state_factory);
7805        let handler = Arc::new(handler);
7806
7807        let execute_name = workflow_type.clone();
7808        let execute_factory = Arc::clone(&state_factory);
7809        let execute_handler = Arc::clone(&handler);
7810        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7811            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7812            let state = WorkflowInstance::new(execute_factory());
7813            let handler = Arc::clone(&execute_handler);
7814            let handler_name = execute_name.clone();
7815            Ok(Box::pin(async move {
7816                let result = handler(ctx, input, state).await?;
7817                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7818            }) as WorkflowFuture)
7819        });
7820
7821        let replay_name = workflow_type.clone();
7822        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7823            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7824            let state = WorkflowInstance::new(state_factory());
7825            let snapshot_state = state.clone();
7826            let snapshot: WorkflowStateSnapshot =
7827                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7828            let handler = Arc::clone(&handler);
7829            let handler_name = replay_name.clone();
7830            let future = async move {
7831                let result = handler(ctx, input, state).await?;
7832                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7833            };
7834            Ok(ReplayedWorkflowInvocation {
7835                future: Box::pin(future),
7836                snapshot,
7837            })
7838        });
7839
7840        self.workflows.insert(
7841            workflow_type,
7842            RegisteredWorkflow {
7843                execute,
7844                replay: Some(replay),
7845                state_type: Some(TypeId::of::<S>()),
7846                definition_fingerprint: None,
7847            },
7848        );
7849    }
7850
7851    /// Declare the signal names consumed by a registered workflow.
7852    ///
7853    /// Call this after registering the workflow and before starting the worker.
7854    /// Names read through `wait_signal` or `signals` need a declaration for
7855    /// Server command admission. Arguments remain arbitrary positional values,
7856    /// including lossless Avro values. This replaces the previous declaration;
7857    /// an empty slice declares no signals. Names are sorted and deduplicated.
7858    /// Existing runs retain the declarations captured when they started.
7859    pub fn declare_workflow_signals(
7860        &mut self,
7861        workflow_type: &str,
7862        signal_names: &[&str],
7863    ) -> Result<()> {
7864        if !self.workflows.contains_key(workflow_type) {
7865            return Err(Error::Codec(format!(
7866                "workflow type {workflow_type:?} is not registered"
7867            )));
7868        }
7869        if signal_names
7870            .iter()
7871            .any(|name| name.is_empty() || *name != name.trim())
7872        {
7873            return Err(Error::Codec(
7874                "signal names must be non-empty and have no surrounding whitespace".into(),
7875            ));
7876        }
7877        let mut names = signal_names
7878            .iter()
7879            .map(|name| (*name).to_string())
7880            .collect::<Vec<_>>();
7881        names.sort();
7882        names.dedup();
7883        self.signals.insert(workflow_type.to_string(), names);
7884        Ok(())
7885    }
7886
7887    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7888    ///
7889    /// Supply `include_str!` values for the workflow body and every helper whose
7890    /// behavior can affect replay. Register the workflow once, then set its
7891    /// identity before starting the worker. Duplicate registrations are invalid. The server
7892    /// rejects reusing a worker ID when its prior fingerprint disappears.
7893    /// Workflows without source identity remain runnable but cannot be safely redriven.
7894    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7895    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7896    pub fn set_workflow_definition_sources(
7897        &mut self,
7898        workflow_type: &str,
7899        sources: &[&str],
7900    ) -> Result<()> {
7901        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7902            return Err(Error::Codec(
7903                "workflow definition sources must be non-empty".to_string(),
7904            ));
7905        }
7906        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7907            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7908        })?;
7909        let mut hasher = Sha256::new();
7910        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7911        hasher.update((workflow_type.len() as u64).to_be_bytes());
7912        hasher.update(workflow_type.as_bytes());
7913        for source in sources {
7914            hasher.update((source.len() as u64).to_be_bytes());
7915            hasher.update(source.as_bytes());
7916        }
7917        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7918        Ok(())
7919    }
7920
7921    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7922    #[track_caller]
7923    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7924        &mut self,
7925        workflow_type: impl Into<String>,
7926        state_factory: Factory,
7927        handler: F,
7928    ) where
7929        S: Clone + Send + Sync + 'static,
7930        Factory: Fn() -> S + Send + Sync + 'static,
7931        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7932        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7933    {
7934        let workflow_type = workflow_type.into();
7935        if !self.admit_registration::<F>(
7936            RegistrationKind::Workflow,
7937            None,
7938            &workflow_type,
7939            "register_replayed_workflow_avro_value",
7940        ) {
7941            return;
7942        }
7943        let state_factory = Arc::new(state_factory);
7944        let handler = Arc::new(handler);
7945
7946        let execute_factory = Arc::clone(&state_factory);
7947        let execute_handler = Arc::clone(&handler);
7948        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7949            let state = WorkflowInstance::new(execute_factory());
7950            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7951        });
7952
7953        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7954            let state = WorkflowInstance::new(state_factory());
7955            let snapshot_state = state.clone();
7956            let snapshot: WorkflowStateSnapshot =
7957                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7958            Ok(ReplayedWorkflowInvocation {
7959                future: Box::pin(handler(ctx, input, state)),
7960                snapshot,
7961            })
7962        });
7963
7964        self.workflows.insert(
7965            workflow_type,
7966            RegisteredWorkflow {
7967                execute,
7968                replay: Some(replay),
7969                state_type: Some(TypeId::of::<S>()),
7970                definition_fingerprint: None,
7971            },
7972        );
7973    }
7974
7975    #[track_caller]
7976    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7977    where
7978        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7979        Fut: Future<Output = Result<Value>> + Send + 'static,
7980    {
7981        let activity_type = activity_type.into();
7982        if !self.admit_registration::<F>(
7983            RegistrationKind::Activity,
7984            None,
7985            &activity_type,
7986            "register_activity",
7987        ) {
7988            return;
7989        }
7990        let handler = Arc::new(handler);
7991        self.activities.insert(
7992            activity_type,
7993            Arc::new(move |ctx, args| {
7994                let handler = Arc::clone(&handler);
7995                Box::pin(async move {
7996                    let result = handler(ctx, args.into_json()?).await?;
7997                    AvroValue::from_serialize(&result)
7998                })
7999            }),
8000        );
8001    }
8002
8003    /// Register an activity with one Serde request value and a Serde result.
8004    ///
8005    /// Inputs and results use the platform's fixed Avro Value schema. Shape
8006    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
8007    /// with the activity name and Rust type.
8008    #[track_caller]
8009    pub fn register_typed_activity<I, O, F, Fut>(
8010        &mut self,
8011        activity_type: impl Into<String>,
8012        handler: F,
8013    ) where
8014        I: DeserializeOwned + Send + 'static,
8015        O: Serialize + Send + 'static,
8016        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
8017        Fut: Future<Output = Result<O>> + Send + 'static,
8018    {
8019        let activity_type = activity_type.into();
8020        if !self.admit_registration::<F>(
8021            RegistrationKind::Activity,
8022            None,
8023            &activity_type,
8024            "register_typed_activity",
8025        ) {
8026            return;
8027        }
8028        let handler_name = activity_type.clone();
8029        let handler = Arc::new(handler);
8030        self.activities.insert(
8031            activity_type,
8032            Arc::new(move |ctx, input| {
8033                let handler = Arc::clone(&handler);
8034                let handler_name = handler_name.clone();
8035                Box::pin(async move {
8036                    let input =
8037                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
8038                    let result = handler(ctx, input).await?;
8039                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
8040                })
8041            }),
8042        );
8043    }
8044
8045    /// Register an activity on the lossless fixed Avro Value surface.
8046    #[track_caller]
8047    pub fn register_activity_avro_value<F, Fut>(
8048        &mut self,
8049        activity_type: impl Into<String>,
8050        handler: F,
8051    ) where
8052        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
8053        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8054    {
8055        let activity_type = activity_type.into();
8056        if !self.admit_registration::<F>(
8057            RegistrationKind::Activity,
8058            None,
8059            &activity_type,
8060            "register_activity_avro_value",
8061        ) {
8062            return;
8063        }
8064        self.activities.insert(
8065            activity_type,
8066            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8067        );
8068    }
8069
8070    /// Register a named, read-only query handler for a workflow type.
8071    ///
8072    /// The workflow type must also be registered with [`Worker::register_workflow`]
8073    /// before the worker runs. The handler receives only an immutable committed
8074    /// state snapshot and normalized query arguments.
8075    #[track_caller]
8076    pub fn register_query<F, Fut>(
8077        &mut self,
8078        workflow_type: impl Into<String>,
8079        query_name: impl Into<String>,
8080        handler: F,
8081    ) where
8082        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8083        Fut: Future<Output = Result<Value>> + Send + 'static,
8084    {
8085        let workflow_type = workflow_type.into();
8086        let query_name = query_name.into();
8087        if !self.admit_registration::<F>(
8088            RegistrationKind::Query,
8089            Some(&workflow_type),
8090            &query_name,
8091            "register_query",
8092        ) {
8093            return;
8094        }
8095        let handler = Arc::new(handler);
8096        self.queries.entry(workflow_type).or_default().insert(
8097            query_name,
8098            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
8099                let handler = Arc::clone(&handler);
8100                Box::pin(async move {
8101                    let result = handler(ctx, args.into_json()?).await?;
8102                    AvroValue::from_serialize(&result)
8103                })
8104            })),
8105        );
8106    }
8107
8108    /// Register a query handler on the lossless fixed Avro Value surface.
8109    #[track_caller]
8110    pub fn register_query_avro_value<F, Fut>(
8111        &mut self,
8112        workflow_type: impl Into<String>,
8113        query_name: impl Into<String>,
8114        handler: F,
8115    ) where
8116        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8117        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8118    {
8119        let workflow_type = workflow_type.into();
8120        let query_name = query_name.into();
8121        if !self.admit_registration::<F>(
8122            RegistrationKind::Query,
8123            Some(&workflow_type),
8124            &query_name,
8125            "register_query_avro_value",
8126        ) {
8127            return;
8128        }
8129        self.queries.entry(workflow_type).or_default().insert(
8130            query_name,
8131            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
8132        );
8133    }
8134
8135    /// Register a named query against deterministically replayed instance state.
8136    ///
8137    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
8138    /// same state type `S`. The handler receives an immutable, detached state
8139    /// clone, so successful and failed queries cannot affect workflow execution
8140    /// or the state reconstructed by a later query.
8141    #[track_caller]
8142    pub fn register_replayed_query<S, F, Fut>(
8143        &mut self,
8144        workflow_type: impl Into<String>,
8145        query_name: impl Into<String>,
8146        handler: F,
8147    ) where
8148        S: Clone + Send + Sync + 'static,
8149        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
8150        Fut: Future<Output = Result<Value>> + Send + 'static,
8151    {
8152        let workflow_type = workflow_type.into();
8153        let query_name = query_name.into();
8154        if !self.admit_registration::<F>(
8155            RegistrationKind::Query,
8156            Some(&workflow_type),
8157            &query_name,
8158            "register_replayed_query",
8159        ) {
8160            return;
8161        }
8162        let handler = Arc::new(handler);
8163        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8164            let state = state.downcast::<S>().map_err(|_| {
8165                "registered query state type does not match the replayed workflow state".to_string()
8166            })?;
8167            let handler = Arc::clone(&handler);
8168            Ok(Box::pin(async move {
8169                let result = handler(ctx, state, args.into_json()?).await?;
8170                AvroValue::from_serialize(&result)
8171            }))
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 replayed-state query on the lossless fixed Avro Value surface.
8184    #[track_caller]
8185    pub fn register_replayed_query_avro_value<S, F, Fut>(
8186        &mut self,
8187        workflow_type: impl Into<String>,
8188        query_name: impl Into<String>,
8189        handler: F,
8190    ) where
8191        S: Clone + Send + Sync + 'static,
8192        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
8193        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8194    {
8195        let workflow_type = workflow_type.into();
8196        let query_name = query_name.into();
8197        if !self.admit_registration::<F>(
8198            RegistrationKind::Query,
8199            Some(&workflow_type),
8200            &query_name,
8201            "register_replayed_query_avro_value",
8202        ) {
8203            return;
8204        }
8205        let handler = Arc::new(handler);
8206        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8207            let state = state.downcast::<S>().map_err(|_| {
8208                "registered query state type does not match the replayed workflow state".to_string()
8209            })?;
8210            Ok(Box::pin(handler(ctx, state, args)))
8211        });
8212
8213        self.queries.entry(workflow_type).or_default().insert(
8214            query_name,
8215            RegisteredQuery::Replayed {
8216                state_type: TypeId::of::<S>(),
8217                handler: erased_handler,
8218            },
8219        );
8220    }
8221
8222    /// Register a synchronous workflow update handler.
8223    #[track_caller]
8224    pub fn register_update<F, Fut>(
8225        &mut self,
8226        workflow_type: impl Into<String>,
8227        update_name: impl Into<String>,
8228        handler: F,
8229    ) where
8230        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8231        Fut: Future<Output = Result<Value>> + Send + 'static,
8232    {
8233        let workflow_type = workflow_type.into();
8234        let update_name = update_name.into();
8235        if !self.admit_registration::<F>(
8236            RegistrationKind::Update,
8237            Some(&workflow_type),
8238            &update_name,
8239            "register_update",
8240        ) {
8241            return;
8242        }
8243        let handler = Arc::new(handler);
8244        self.updates.entry(workflow_type).or_default().insert(
8245            update_name,
8246            Arc::new(move |ctx, args| {
8247                let handler = Arc::clone(&handler);
8248                Box::pin(async move {
8249                    let result = handler(ctx, args.into_json()?).await?;
8250                    AvroValue::from_serialize(&result)
8251                })
8252            }),
8253        );
8254    }
8255
8256    /// Register an update handler on the lossless fixed Avro Value surface.
8257    #[track_caller]
8258    pub fn register_update_avro_value<F, Fut>(
8259        &mut self,
8260        workflow_type: impl Into<String>,
8261        update_name: impl Into<String>,
8262        handler: F,
8263    ) where
8264        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8265        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8266    {
8267        let workflow_type = workflow_type.into();
8268        let update_name = update_name.into();
8269        if !self.admit_registration::<F>(
8270            RegistrationKind::Update,
8271            Some(&workflow_type),
8272            &update_name,
8273            "register_update_avro_value",
8274        ) {
8275            return;
8276        }
8277        self.updates.entry(workflow_type).or_default().insert(
8278            update_name,
8279            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8280        );
8281    }
8282
8283    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
8284        self.validate_registration()?;
8285        self.nexus_registration_confirmed
8286            .store(false, Ordering::SeqCst);
8287        self.query_authority_confirmed
8288            .store(false, Ordering::SeqCst);
8289        if self.nexus_cooperative_cancellation_enabled {
8290            let info: Value = self
8291                .client
8292                .request_json(
8293                    reqwest::Method::GET,
8294                    "/cluster/info",
8295                    RequestProtocol::Worker("1.20"),
8296                    Option::<&Value>::None,
8297                )
8298                .await?;
8299            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
8300                return Err(Error::CooperativeCancellationUnavailable(
8301                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
8302                ));
8303            }
8304        }
8305        if self.require_query_task_authority {
8306            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
8307                return Err(Error::WorkerLoop(
8308                    "query authority requires worker protocol 1.20".into(),
8309                ));
8310            }
8311            // Discovery uses the Worker credential, including worker-only Clients.
8312            let discovery: Value = self
8313                .client
8314                .request_json_unresolved_with_timeout::<Value, Value>(
8315                    reqwest::Method::GET,
8316                    "/cluster/info",
8317                    RequestProtocol::Worker("1.20"),
8318                    None,
8319                    Duration::from_secs(5),
8320                )
8321                .await?;
8322            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
8323                return Err(Error::WorkerLoop(
8324                    "runtime does not advertise query_task_authority".into(),
8325                ));
8326            }
8327        }
8328        self.sticky_registration_confirmed
8329            .store(false, Ordering::SeqCst);
8330        self.session_registration_confirmed
8331            .store(false, Ordering::SeqCst);
8332        for capability in &self.resource_capabilities {
8333            worker_session::validate_resource_capability(capability)?;
8334        }
8335        self.local_registration_confirmed
8336            .store(false, Ordering::SeqCst);
8337        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
8338            return Err(Error::CooperativeCancellationUnavailable(
8339                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
8340            ));
8341        }
8342        let mut command_contracts = serde_json::Map::new();
8343        for workflow_type in self.workflows.keys() {
8344            let mut queries = self
8345                .queries
8346                .get(workflow_type)
8347                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8348                .unwrap_or_default();
8349            queries.sort();
8350            let mut updates = self
8351                .updates
8352                .get(workflow_type)
8353                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8354                .unwrap_or_default();
8355            updates.sort();
8356            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
8357            command_contracts.insert(
8358                workflow_type.clone(),
8359                json!({
8360                    "queries": queries,
8361                    "query_contracts": argument_vector_contracts(&queries),
8362                    "signals": signals,
8363                    "signal_contracts": argument_vector_contracts(&signals),
8364                    "updates": updates,
8365                    "update_contracts": argument_vector_contracts(&updates),
8366                    "update_validators": [],
8367                }),
8368            );
8369        }
8370
8371        self.cooperative_registration_confirmed
8372            .store(false, Ordering::SeqCst);
8373        #[cfg(feature = "telemetry")]
8374        if self
8375            .telemetry
8376            .as_ref()
8377            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
8378            && !self
8379                .client
8380                .observability_context_supported
8381                .load(Ordering::SeqCst)
8382        {
8383            // Optional startup discovery is bounded and cached. Its failure
8384            // cannot refuse registration or add retries to a business command.
8385            let _ = self
8386                .client
8387                .request_json_unresolved_with_timeout::<Value, Value>(
8388                    reqwest::Method::GET,
8389                    "/cluster/info",
8390                    RequestProtocol::DefaultWorker,
8391                    None,
8392                    Duration::from_secs(5),
8393                )
8394                .await;
8395        }
8396        let response = self
8397            .client
8398            .register_worker_with_definition_fingerprints(
8399                &self.worker_id,
8400                &self.task_queue,
8401                self.workflows.keys().cloned().collect(),
8402                self.activities.keys().cloned().collect(),
8403                self.max_concurrent_workflow_tasks,
8404                self.max_concurrent_activity_tasks,
8405                [
8406                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
8407                    Some("workflow_entry_arguments_validation".to_string()),
8408                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
8409                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
8410                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
8411                    self.client
8412                        .local_activities_enabled
8413                        .then(|| "local_activities".to_string()),
8414                    self.client
8415                        .worker_sessions_enabled
8416                        .then(|| "worker_sessions".to_string()),
8417                    self.client
8418                        .sticky_cache
8419                        .is_some()
8420                        .then(|| "sticky_execution".to_string()),
8421                    self.cooperative_cancellation_enabled
8422                        .then(|| "cooperative_cancellation".to_string()),
8423                    self.nexus_cooperative_cancellation_enabled
8424                        .then(|| "nexus_cooperative_cancellation".to_string()),
8425                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
8426                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
8427                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
8428                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
8429                ]
8430                .into_iter()
8431                .flatten()
8432                .chain(self.resource_capabilities.iter().cloned())
8433                .collect(),
8434                Value::Object(command_contracts),
8435                Some(
8436                    self.workflows
8437                        .iter()
8438                        .filter_map(|(workflow_type, workflow)| {
8439                            workflow
8440                                .definition_fingerprint
8441                                .as_ref()
8442                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
8443                        })
8444                        .collect(),
8445                ),
8446            )
8447            .await?;
8448        if self.cooperative_cancellation_enabled && response.registered {
8449            self.cooperative_registration_confirmed
8450                .store(true, Ordering::SeqCst);
8451        }
8452        if self.nexus_cooperative_cancellation_enabled && response.registered {
8453            self.nexus_registration_confirmed
8454                .store(true, Ordering::SeqCst);
8455        }
8456        if self.client.local_activities_enabled && response.registered {
8457            self.local_registration_confirmed
8458                .store(true, Ordering::SeqCst);
8459        }
8460        if self.client.worker_sessions_enabled && response.registered {
8461            self.session_registration_confirmed
8462                .store(true, Ordering::SeqCst);
8463        }
8464        if self.client.sticky_cache.is_some() && response.registered {
8465            self.sticky_registration_confirmed
8466                .store(true, Ordering::SeqCst);
8467        }
8468        self.query_authority_confirmed.store(
8469            response.registered
8470                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
8471                && response
8472                    .server_capabilities
8473                    .as_ref()
8474                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
8475            Ordering::SeqCst,
8476        );
8477        Ok(response)
8478    }
8479
8480    /// Run until shutdown or a terminal worker error occurs.
8481    ///
8482    /// Empty long-poll expirations do not stop the worker. Retryable poll and
8483    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
8484    /// authentication, protocol, and other non-retryable failures are returned.
8485    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
8486    /// poll and heartbeat outages beyond the ordinary retry budget.
8487    pub async fn run(&self) -> Result<()> {
8488        self.run_until(std::future::pending::<()>()).await
8489    }
8490
8491    /// Run until `shutdown` resolves or a terminal worker error occurs.
8492    ///
8493    /// This has the same liveness and terminal-error contract as [`Worker::run`].
8494    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
8495    where
8496        F: Future<Output = ()>,
8497    {
8498        let _clear_cache_on_drop =
8499            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
8500        let stop = Arc::new(AtomicBool::new(false));
8501        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
8502        let mut worker = self.with_storage_admission(Arc::clone(&stop));
8503        worker.run_stop = Some(Arc::clone(&stop));
8504        let run = worker.run_with_storage_admission(Arc::clone(&stop));
8505        tokio::pin!(run);
8506        tokio::pin!(shutdown);
8507        tokio::select! {
8508            result = &mut run => result,
8509            _ = &mut shutdown => {
8510                stop.store(true, Ordering::SeqCst);
8511                run.await
8512            }
8513        }
8514    }
8515
8516    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
8517        let mut worker = self.clone();
8518        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
8519            policy: self.retry_policy,
8520            stop,
8521            workflow_completion_retry_deadline: None,
8522        });
8523        worker
8524    }
8525
8526    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8527        let registration = self.register().await?;
8528        if !registration.registered {
8529            return Err(Error::WorkerLoop(format!(
8530                "worker registration for {:?} was not accepted",
8531                self.worker_id
8532            )));
8533        }
8534        let registered_worker_id = registration.worker_id.clone();
8535        let primary = self.run_registered_until(stop, registration).await;
8536        let primary = match (primary, self.close_worker_sessions().await) {
8537            (Ok(()), result) => result,
8538            (Err(error), Ok(())) => Err(error),
8539            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8540                primary: Box::new(primary),
8541                deregistration: Box::new(close),
8542            }),
8543        };
8544        self.session_registration_confirmed
8545            .store(false, Ordering::SeqCst);
8546        self.cooperative_registration_confirmed
8547            .store(false, Ordering::SeqCst);
8548        self.local_registration_confirmed
8549            .store(false, Ordering::SeqCst);
8550        let deregistration = self
8551            .client
8552            .deregister_worker_registration(&registered_worker_id)
8553            .await;
8554        self.sticky_registration_confirmed
8555            .store(false, Ordering::SeqCst);
8556        self.client.clear_sticky_cache()?;
8557
8558        match (primary, deregistration) {
8559            (Ok(()), Ok(_)) => Ok(()),
8560            (Ok(()), Err(deregistration)) => Err(deregistration),
8561            (Err(primary), Ok(_)) => Err(primary),
8562            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8563                primary: Box::new(primary),
8564                deregistration: Box::new(deregistration),
8565            }),
8566        }
8567    }
8568
8569    async fn run_registered_until(
8570        &self,
8571        stop: Arc<AtomicBool>,
8572        registration: RegisterWorkerResponse,
8573    ) -> Result<()> {
8574        if self.require_query_task_authority
8575            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8576        {
8577            return Err(Error::WorkerLoop(
8578                "registration did not confirm query_task_authority".into(),
8579            ));
8580        }
8581        let heartbeat_interval = Duration::from_secs(
8582            registration
8583                .heartbeat_interval_seconds
8584                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8585        );
8586        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8587        // from the completion of the preceding attempt, including its bounded
8588        // retries. A fixed-epoch interval can leave an already-due tick queued
8589        // while an acknowledgement is slow, producing a catch-up heartbeat as
8590        // soon as that request completes.
8591        let heartbeat = tokio::time::sleep(Duration::ZERO);
8592        tokio::pin!(heartbeat);
8593        // Poll responses may already have leased server-side work by the time
8594        // they become ready, so each poller owns its responses through
8595        // completion or failure instead of racing raw polls in this select.
8596        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
8597            let worker = self.clone();
8598            let stop = Arc::clone(&stop);
8599            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
8600        });
8601        let mut activity_poller = (!self.activities.is_empty()).then(|| {
8602            let worker = self.clone();
8603            let stop = Arc::clone(&stop);
8604            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
8605        });
8606        let mut query_poller = (!self.queries.is_empty()).then(|| {
8607            let worker = self.clone();
8608            let stop = Arc::clone(&stop);
8609            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
8610        });
8611
8612        loop {
8613            tokio::select! {
8614                _ = wait_for_worker_stop(&stop) => {
8615                    stop.store(true, Ordering::SeqCst);
8616                    break;
8617                }
8618                _ = &mut heartbeat => {
8619                    let result = self.retry_worker_operation(|| {
8620                        self.client.heartbeat_worker_with_sessions(
8621                            &self.worker_id,
8622                            self.workflow_capacity.available(),
8623                            self.activity_capacity.available(),
8624                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8625                        )
8626                    }).await;
8627                    heartbeat
8628                        .as_mut()
8629                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8630                    match result {
8631                        Ok(Some(acknowledgement)) => {
8632                            if let Some(observer) = &self.heartbeat_observer {
8633                                observer(&WorkerHeartbeatObservation {
8634                                    worker_id: self.worker_id.clone(),
8635                                    task_queue: self.task_queue.clone(),
8636                                    acknowledged_at_unix_millis: SystemTime::now()
8637                                        .duration_since(UNIX_EPOCH)
8638                                        .unwrap_or_default()
8639                                        .as_millis()
8640                                        .min(u64::MAX as u128)
8641                                        as u64,
8642                                    acknowledgement,
8643                                });
8644                            }
8645                        }
8646                        Ok(None) => break,
8647                        Err(error) => {
8648                            stop.store(true, Ordering::SeqCst);
8649                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8650                            return Err(error);
8651                        }
8652                    }
8653                }
8654                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8655                    workflow_poller = None;
8656                    let stopped_by_server = stop.load(Ordering::SeqCst);
8657                    stop.store(true, Ordering::SeqCst);
8658                    let poller_result = optional_poller_result("workflow", result);
8659                    let join_result =
8660                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8661                    poller_result?;
8662                    join_result?;
8663                    if stopped_by_server {
8664                        return Ok(());
8665                    }
8666                    return Err(Error::WorkerLoop(
8667                        "workflow poller stopped unexpectedly".to_string(),
8668                    ));
8669                }
8670                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8671                    activity_poller = None;
8672                    let stopped_by_server = stop.load(Ordering::SeqCst);
8673                    stop.store(true, Ordering::SeqCst);
8674                    let poller_result = optional_poller_result("activity", result);
8675                    let join_result =
8676                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8677                    poller_result?;
8678                    join_result?;
8679                    if stopped_by_server {
8680                        return Ok(());
8681                    }
8682                    return Err(Error::WorkerLoop(
8683                        "activity poller stopped unexpectedly".to_string(),
8684                    ));
8685                }
8686                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8687                    query_poller = None;
8688                    let stopped_by_server = stop.load(Ordering::SeqCst);
8689                    stop.store(true, Ordering::SeqCst);
8690                    let poller_result = optional_poller_result("query", result);
8691                    let join_result =
8692                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8693                    poller_result?;
8694                    join_result?;
8695                    if stopped_by_server {
8696                        return Ok(());
8697                    }
8698                    return Err(Error::WorkerLoop(
8699                        "query poller stopped unexpectedly".to_string(),
8700                    ));
8701                }
8702            }
8703        }
8704
8705        join_pollers(
8706            workflow_poller.take(),
8707            activity_poller.take(),
8708            query_poller.take(),
8709        )
8710        .await
8711    }
8712
8713    /// Poll and settle at most one task from each enabled task family.
8714    ///
8715    /// A workflow may reach its server-enforced run deadline while this worker
8716    /// holds a task. When the completion endpoint authoritatively rejects that
8717    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8718    /// terminal `run_status=failed`, the workflow tick is considered settled:
8719    /// the late command was not recorded and cannot replace the terminal run.
8720    /// Every other completion rejection remains an error. This worker-level
8721    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8722    /// only bounds how long a client waits for a result.
8723    ///
8724    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8725    /// the original [`Error::Http`] status and response body.
8726    pub async fn run_once(&self) -> Result<usize> {
8727        self.validate_registration()?;
8728        if self.client.worker_sessions_enabled {
8729            self.require_session_registration()?;
8730        }
8731        if self.cooperative_cancellation_enabled
8732            && !self
8733                .cooperative_registration_confirmed
8734                .load(Ordering::SeqCst)
8735        {
8736            return Err(Error::CooperativeCancellationUnavailable(
8737                "register this cooperative worker before polling tasks".into(),
8738            ));
8739        }
8740        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8741        let mut handled = 0;
8742        match worker.poll_workflow_once().await? {
8743            ManagedPollOutcome::Handled => handled += 1,
8744            ManagedPollOutcome::Stop => return Ok(handled),
8745            ManagedPollOutcome::Idle => {}
8746        }
8747        match worker.poll_activity_once().await? {
8748            ManagedPollOutcome::Handled => handled += 1,
8749            ManagedPollOutcome::Stop => return Ok(handled),
8750            ManagedPollOutcome::Idle => {}
8751        }
8752        if !self.queries.is_empty() {
8753            match worker.poll_query_once().await? {
8754                ManagedPollOutcome::Handled => handled += 1,
8755                ManagedPollOutcome::Stop => return Ok(handled),
8756                ManagedPollOutcome::Idle => {}
8757            }
8758        }
8759        Ok(handled)
8760    }
8761
8762    async fn poll_workflow_once_reserved(&self) -> Result<ManagedPollOutcome> {
8763        if self.client.sticky_cache.is_some()
8764            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8765        {
8766            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8767        }
8768        if self.client.local_activities_enabled
8769            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8770        {
8771            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8772        }
8773        if self.cooperative_cancellation_enabled {
8774            return self.poll_cooperative_workflow_once().await;
8775        }
8776        let poll_request_id = unique_request_id("rust-workflow-poll");
8777        let response = self
8778            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8779            .await;
8780        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8781            return Ok(ManagedPollOutcome::Idle);
8782        };
8783        if response.outcome().should_stop() {
8784            return Ok(ManagedPollOutcome::Stop);
8785        }
8786        let memo_updates_supported =
8787            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8788        let Some(task) = response.task else {
8789            return Ok(ManagedPollOutcome::Idle);
8790        };
8791
8792        let task_id = task.task_id.clone();
8793        let attempt = task.workflow_task_attempt;
8794        let run_id = task.run_id.clone();
8795        let lease_owner = task
8796            .lease_owner
8797            .clone()
8798            .unwrap_or_else(|| self.worker_id.clone());
8799
8800        let decision = match self.execute_workflow_with_local_activities(task).await {
8801            Ok(Some(decision)) => Ok(decision),
8802            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8803            Err(error) => Err(error),
8804        };
8805        self.settle_workflow_task_decision(
8806            &task_id,
8807            &lease_owner,
8808            attempt,
8809            run_id.as_deref(),
8810            decision,
8811            memo_updates_supported,
8812            snapshot,
8813        )
8814        .await
8815    }
8816
8817    #[allow(clippy::too_many_arguments)]
8818    async fn settle_workflow_task_decision(
8819        &self,
8820        task_id: &str,
8821        lease_owner: &str,
8822        attempt: u64,
8823        run_id: Option<&str>,
8824        decision: Result<WorkflowTaskDecision>,
8825        memo_updates_supported: bool,
8826        snapshot: Option<sticky_worker::StickySnapshot>,
8827    ) -> Result<ManagedPollOutcome> {
8828        match decision {
8829            Ok(decision)
8830                if decision.cancellation_delivery.is_some()
8831                    || decision.cancellation_scope_delivery.is_some()
8832                    || decision.cancellation_scope_opening.is_some() =>
8833            {
8834                return Err(Error::CooperativeCancellationUnavailable(
8835                    "worker cancellation delivery has not been negotiated".into(),
8836                ));
8837            }
8838            Ok(decision)
8839                if commands_use_workflow_memo_updates(&decision.commands)
8840                    && !memo_updates_supported =>
8841            {
8842                self.client
8843                    .fail_workflow_task(
8844                        task_id,
8845                        lease_owner,
8846                        attempt,
8847                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8848                    )
8849                    .await?;
8850            }
8851            Ok(decision) if decision.commands.is_empty() => {
8852                // A replay can consume a recorded pending durable command
8853                // without producing a new command. The standalone protocol
8854                // acknowledges that state through the typed waiting outcome;
8855                // an empty completion is rejected by servers that require at
8856                // least one executable command.
8857                self.client
8858                    .fail_workflow_task_with_type(
8859                        task_id,
8860                        lease_owner,
8861                        attempt,
8862                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8863                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8864                    )
8865                    .await?;
8866            }
8867            Ok(decision) => {
8868                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8869                let completion = self
8870                    .client
8871                    .complete_workflow_task_with_message_streams(
8872                        task_id,
8873                        lease_owner,
8874                        attempt,
8875                        decision.commands,
8876                        decision.message_stream_cursors,
8877                        decision.message_stream_waits,
8878                        sticky_claim,
8879                    )
8880                    .await;
8881                if let Err(error) = completion {
8882                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8883                    if !workflow_task_completion_is_terminal_timeout(
8884                        &error, task_id, attempt, run_id,
8885                    ) {
8886                        return Err(error);
8887                    }
8888                }
8889            }
8890            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8891            Err(error) => {
8892                self.discard_sticky_snapshot(snapshot.as_ref())?;
8893                if matches!(
8894                    error,
8895                    Error::HandlerType {
8896                        handler_kind: HandlerKind::Workflow,
8897                        value_kind: HandlerValueKind::Input,
8898                        ..
8899                    }
8900                ) {
8901                    self.client
8902                        .fail_workflow_task_with_failure(
8903                            task_id,
8904                            lease_owner,
8905                            attempt,
8906                            json!({
8907                                "message": error.to_string(),
8908                                "type": "WorkflowEntryArgumentsMismatch",
8909                                "reason": "workflow_entry_arguments_mismatch",
8910                            }),
8911                        )
8912                        .await?;
8913                } else {
8914                    self.client
8915                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8916                        .await?;
8917                }
8918            }
8919        }
8920
8921        Ok(ManagedPollOutcome::Handled)
8922    }
8923
8924    async fn poll_activity_once_reserved(&self) -> Result<ManagedPollOutcome> {
8925        if self.client.worker_sessions_enabled {
8926            self.require_session_registration()?;
8927        }
8928        let poll_request_id = unique_request_id("rust-activity-poll");
8929        let response = self
8930            .retry_worker_operation(|| {
8931                self.client.poll_activity_task_response_with_request_id(
8932                    &self.worker_id,
8933                    &self.task_queue,
8934                    self.poll_timeout,
8935                    &poll_request_id,
8936                    0,
8937                )
8938            })
8939            .await;
8940        let response = match response {
8941            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8942            response => response,
8943        };
8944        let Some(response) = self.settle_worker_poll_response(response).await? else {
8945            return Ok(ManagedPollOutcome::Idle);
8946        };
8947        if response.outcome().should_stop() {
8948            return Ok(ManagedPollOutcome::Stop);
8949        }
8950        let Some(task) = response.task else {
8951            return Ok(ManagedPollOutcome::Idle);
8952        };
8953
8954        self.settle_polled_activity(task).await
8955    }
8956
8957    async fn settle_polled_activity(
8958        &self,
8959        task: worker_session::SessionActivityTask,
8960    ) -> Result<ManagedPollOutcome> {
8961        let lease = task.activity_lease.clone();
8962        let mut worker = self.clone();
8963        worker.client = self.client.with_activity_lease_authority(
8964            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
8965        );
8966        let operation = worker.execute_polled_activity(task);
8967        let result = match lease.as_ref() {
8968            Some(lease) => lease.authority.protect(operation).await,
8969            None => operation.await,
8970        };
8971        match result {
8972            Err(Error::ActivityExecutionAbandoned(_)) => Ok(ManagedPollOutcome::Handled),
8973            result => result,
8974        }
8975    }
8976
8977    async fn execute_polled_activity(
8978        &self,
8979        task: worker_session::SessionActivityTask,
8980    ) -> Result<ManagedPollOutcome> {
8981        if self.cooperative_cancellation_enabled {
8982            return self.settle_cooperative_activity(task).await;
8983        }
8984        let session = self.track_session_task(task.worker_session.as_ref())?;
8985        let hydration_claim = task.hydration_claim;
8986        let task = task.task;
8987
8988        let task_id = task.task_id.clone();
8989        let attempt_id = task
8990            .activity_attempt_id
8991            .clone()
8992            .or(task.attempt_id.clone())
8993            .unwrap_or_default();
8994        let lease_owner = task
8995            .lease_owner
8996            .clone()
8997            .unwrap_or_else(|| self.worker_id.clone());
8998        let codec = task.payload_codec.clone();
8999        let result = self
9000            .execute_session_activity_task(task, session, hydration_claim.as_ref())
9001            .await;
9002        match result {
9003            Err(Error::ActivityExecutionAbandoned(_)) => {}
9004            Err(error) if activity_hydration::stopped(&error) => {}
9005            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
9006            Ok(value) => {
9007                let completion = self
9008                    .client
9009                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
9010                    .await;
9011                if let Err(error) = completion {
9012                    if !activity_task_rejection_is_final(&error) {
9013                        return Err(error);
9014                    }
9015                }
9016            }
9017            Err(error) => {
9018                let failure = self
9019                    .client
9020                    .fail_activity_task_with_error(
9021                        &task_id,
9022                        &attempt_id,
9023                        &lease_owner,
9024                        &ActivityError::from_error(&error, "RustActivityFailure"),
9025                    )
9026                    .await;
9027                if let Err(error) = failure {
9028                    if !activity_task_rejection_is_final(&error) {
9029                        return Err(error);
9030                    }
9031                }
9032            }
9033        }
9034
9035        Ok(ManagedPollOutcome::Handled)
9036    }
9037
9038    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
9039        let poll_request_id = unique_request_id("rust-query-poll");
9040        let response = self
9041            .retry_worker_operation(|| {
9042                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
9043                    "poll_request_id":poll_request_id,
9044                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
9045                async move {
9046                    self.client
9047                        .poll_request_json_unresolved::<Value, Value>(
9048                            "/worker/query-tasks/poll",
9049                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
9050                            &body,
9051                            self.poll_timeout + Duration::from_secs(5),
9052                            0,
9053                        )
9054                        .await
9055                }
9056            })
9057            .await;
9058        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
9059            return Ok(ManagedPollOutcome::Idle);
9060        };
9061        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
9062            match query_authority::Authority::capture(&wire["task"], self) {
9063                Ok(authority) => authority,
9064                Err(_) => return Ok(ManagedPollOutcome::Handled),
9065            }
9066        } else {
9067            None
9068        };
9069        let loading = self.client.resolve_runtime_payloads(
9070            &mut wire,
9071            "/worker/query-tasks/poll",
9072            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
9073        );
9074        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
9075            Err(_) => return Ok(ManagedPollOutcome::Handled),
9076            Ok(result) => result?,
9077        }
9078        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
9079        if response.outcome().should_stop() {
9080            return Ok(ManagedPollOutcome::Stop);
9081        }
9082        let Some(task) = response.task else {
9083            return Ok(ManagedPollOutcome::Idle);
9084        };
9085
9086        let query_task_id = task.query_task_id.clone();
9087        let attempt = task.query_task_attempt;
9088        let lease_owner = task
9089            .lease_owner
9090            .clone()
9091            .unwrap_or_else(|| self.worker_id.clone());
9092        let codec = task.payload_codec.clone();
9093
9094        let execution = query_authority::Authority::protect(
9095            authority.as_ref(),
9096            self,
9097            self.execute_query_task_with_authority(task, authority.as_ref()),
9098        )
9099        .await;
9100        let execution = match execution {
9101            Err(_) => return Ok(ManagedPollOutcome::Handled),
9102            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
9103                return Ok(ManagedPollOutcome::Handled)
9104            }
9105            Ok(result) => result,
9106        };
9107        match execution {
9108            Ok(value) => {
9109                let result_envelope = match encode_typed_envelope(&value, &codec) {
9110                    Ok(result_envelope) => result_envelope,
9111                    Err(error) => {
9112                        let failure = query_authority::Authority::protect(
9113                            authority.as_ref(),
9114                            self,
9115                            self.client.fail_query_task(
9116                                &query_task_id,
9117                                &lease_owner,
9118                                attempt,
9119                                error.to_string(),
9120                                "query_result_encode_failed",
9121                                "QueryResultEncodeFailed",
9122                            ),
9123                        )
9124                        .await;
9125                        let Ok(failure) = failure else {
9126                            return Ok(ManagedPollOutcome::Handled);
9127                        };
9128                        if let Err(error) = failure {
9129                            if !query_task_rejection_is_final(&error) {
9130                                return Err(error);
9131                            }
9132                        }
9133                        return Ok(ManagedPollOutcome::Handled);
9134                    }
9135                };
9136
9137                let completion = query_authority::Authority::protect(
9138                    authority.as_ref(),
9139                    self,
9140                    self.client.complete_query_task_with_envelope(
9141                        &query_task_id,
9142                        &lease_owner,
9143                        attempt,
9144                        value.clone().into_json()?,
9145                        result_envelope,
9146                    ),
9147                )
9148                .await;
9149                let Ok(completion) = completion else {
9150                    return Ok(ManagedPollOutcome::Handled);
9151                };
9152                if let Err(error) = completion {
9153                    if !query_task_rejection_is_final(&error) {
9154                        return Err(error);
9155                    }
9156                }
9157            }
9158            Err(failure) => {
9159                let result = query_authority::Authority::protect(
9160                    authority.as_ref(),
9161                    self,
9162                    self.client.fail_query_task(
9163                        &query_task_id,
9164                        &lease_owner,
9165                        attempt,
9166                        failure.message,
9167                        failure.reason,
9168                        failure.failure_type,
9169                    ),
9170                )
9171                .await;
9172                let Ok(result) = result else {
9173                    return Ok(ManagedPollOutcome::Handled);
9174                };
9175                if let Err(error) = result {
9176                    if !query_task_rejection_is_final(&error) {
9177                        return Err(error);
9178                    }
9179                }
9180            }
9181        }
9182
9183        Ok(ManagedPollOutcome::Handled)
9184    }
9185
9186    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
9187        while !stop.load(Ordering::SeqCst) {
9188            match self.poll_query_once().await {
9189                Ok(ManagedPollOutcome::Stop) => {
9190                    stop.store(true, Ordering::SeqCst);
9191                    break;
9192                }
9193                Err(error) => {
9194                    stop.store(true, Ordering::SeqCst);
9195                    return Err(error);
9196                }
9197                _ => {}
9198            }
9199        }
9200
9201        Ok(())
9202    }
9203
9204    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
9205    where
9206        F: FnMut() -> Fut,
9207        Fut: Future<Output = Result<T>>,
9208    {
9209        let mut retries = 0;
9210
9211        loop {
9212            if self
9213                .run_stop
9214                .as_ref()
9215                .is_some_and(|stop| stop.load(Ordering::SeqCst))
9216            {
9217                return Ok(None);
9218            }
9219            match operation().await {
9220                Err(error)
9221                    if (workflow_hydration::stopped(&error)
9222                        || activity_hydration::stopped(&error))
9223                        && self
9224                            .run_stop
9225                            .as_ref()
9226                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
9227                {
9228                    return Ok(None);
9229                }
9230                Err(error)
9231                    if worker_operation_is_retryable(&error)
9232                        && (retries < self.retry_policy.max_retries
9233                            || (self.recover_transient_outages
9234                                && self.run_stop.is_some()
9235                                && self.retry_policy.max_retries > 0)) =>
9236                {
9237                    retries = retries.saturating_add(1);
9238                    let delay = worker_retry_delay(self.retry_policy, retries)
9239                        .max(Duration::from_millis(1));
9240                    if let Some(stop) = &self.run_stop {
9241                        tokio::select! {
9242                            _ = tokio::time::sleep(delay) => {}
9243                            _ = wait_for_worker_stop(stop) => return Ok(None),
9244                        }
9245                    } else {
9246                        tokio::time::sleep(delay).await;
9247                    }
9248                }
9249                result => return result.map(Some),
9250            }
9251        }
9252    }
9253
9254    async fn settle_worker_poll_response<T>(
9255        &self,
9256        response: Result<Option<T>>,
9257    ) -> Result<Option<T>> {
9258        match response {
9259            Ok(response) => Ok(response),
9260            Err(error) => {
9261                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
9262                    return Err(error);
9263                };
9264                let minimum_delay = self
9265                    .retry_policy
9266                    .initial_backoff
9267                    .max(Duration::from_millis(1));
9268                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
9269                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
9270                Ok(None)
9271            }
9272        }
9273    }
9274
9275    #[cfg(test)]
9276    async fn execute_query_task(
9277        &self,
9278        task: QueryTask,
9279    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9280        self.execute_query_task_with_authority(task, None).await
9281    }
9282
9283    async fn execute_query_task_with_authority(
9284        &self,
9285        task: QueryTask,
9286        authority: Option<&query_authority::Authority>,
9287    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9288        #[cfg(feature = "telemetry")]
9289        if let Some(telemetry) = &self.telemetry {
9290            return telemetry
9291                .run_observed(
9292                    "durable.query.task",
9293                    self.query_telemetry_fields(&task),
9294                    false,
9295                    authority.and_then(|_| self.query_observations(&task)),
9296                    self.execute_query_task_inner(task, authority),
9297                )
9298                .await;
9299        }
9300        self.execute_query_task_inner(task, authority).await
9301    }
9302
9303    async fn execute_query_task_inner(
9304        &self,
9305        mut task: QueryTask,
9306        authority: Option<&query_authority::Authority>,
9307    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9308        validate_query_task_payloads(&task).map_err(|error| {
9309            QueryTaskExecutionFailure::new(
9310                "query_payload_decode_failed",
9311                error.to_string(),
9312                "QueryPayloadDecodeFailed",
9313            )
9314        })?;
9315
9316        if !self.workflows.contains_key(&task.workflow_type) {
9317            return Err(QueryTaskExecutionFailure::new(
9318                "query_workflow_type_not_registered",
9319                format!("no workflow registered for type {:?}", task.workflow_type),
9320                "WorkflowTypeNotRegistered",
9321            ));
9322        }
9323
9324        let Some(handlers) = self.queries.get(&task.workflow_type) else {
9325            return Err(QueryTaskExecutionFailure::new(
9326                "query_handler_unavailable",
9327                format!(
9328                    "query handlers are unavailable for workflow type {:?}",
9329                    task.workflow_type
9330                ),
9331                "QueryHandlerUnavailable",
9332            ));
9333        };
9334        let Some(query) = handlers.get(&task.query_name) else {
9335            return Err(QueryTaskExecutionFailure::new(
9336                "rejected_unknown_query",
9337                format!("unknown query {:?}", task.query_name),
9338                "QueryFailed",
9339            ));
9340        };
9341
9342        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
9343            .map_err(|error| {
9344            QueryTaskExecutionFailure::new(
9345                "query_payload_decode_failed",
9346                format!("cannot decode query arguments: {error}"),
9347                "QueryPayloadDecodeFailed",
9348            )
9349        })?;
9350        let workflow_input_typed =
9351            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
9352                .map_err(|error| {
9353                    QueryTaskExecutionFailure::new(
9354                        "query_workflow_state_unavailable",
9355                        format!("cannot decode workflow start input: {error}"),
9356                        "QueryWorkflowStateUnavailable",
9357                    )
9358                })?;
9359        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
9360            QueryTaskExecutionFailure::new(
9361                "query_workflow_state_unavailable",
9362                format!("cannot project workflow start input: {error}"),
9363                "QueryWorkflowStateUnavailable",
9364            )
9365        })?;
9366        hydrate_query_history_from_export(&mut task).map_err(|error| {
9367            QueryTaskExecutionFailure::new(
9368                "query_workflow_state_unavailable",
9369                format!("cannot restore query history snapshot: {error}"),
9370                "QueryWorkflowStateUnavailable",
9371            )
9372        })?;
9373        enrich_query_history_from_export(&mut task).map_err(|error| {
9374            QueryTaskExecutionFailure::new(
9375                "query_workflow_state_unavailable",
9376                format!("cannot restore compact query history payloads: {error}"),
9377                "QueryWorkflowStateUnavailable",
9378            )
9379        })?;
9380        let signal_events = query_signal_events(&task).map_err(|error| {
9381            QueryTaskExecutionFailure::new(
9382                "query_workflow_state_unavailable",
9383                format!("cannot decode committed workflow signals: {error}"),
9384                "QueryWorkflowStateUnavailable",
9385            )
9386        })?;
9387        let history_events = Arc::new(std::mem::take(&mut task.history_events));
9388        let context = QueryContext {
9389            workflow_id: task.workflow_id,
9390            run_id: task.run_id,
9391            workflow_type: task.workflow_type.clone(),
9392            run_status: task.run_status,
9393            workflow_input,
9394            workflow_input_avro_value: workflow_input_typed.clone(),
9395            history_events: Arc::clone(&history_events),
9396            signal_events: Arc::new(signal_events),
9397        };
9398
9399        let future = match query {
9400            RegisteredQuery::Snapshot(handler) => {
9401                query_authority::before_handler(authority, &self.client).await?;
9402                handler(context, args)
9403            }
9404            RegisteredQuery::Replayed {
9405                state_type,
9406                handler,
9407            } => {
9408                let workflow = self
9409                    .workflows
9410                    .get(&task.workflow_type)
9411                    .expect("workflow registration was checked above");
9412                if workflow.state_type != Some(*state_type) {
9413                    return Err(QueryTaskExecutionFailure::new(
9414                        "query_workflow_state_unavailable",
9415                        "replayed query state type does not match its workflow registration",
9416                        "QueryWorkflowStateUnavailable",
9417                    ));
9418                }
9419                let replay = workflow.replay.as_ref().ok_or_else(|| {
9420                    QueryTaskExecutionFailure::new(
9421                        "query_workflow_state_unavailable",
9422                        format!(
9423                            "workflow type {:?} is not registered for instance-state replay",
9424                            task.workflow_type
9425                        ),
9426                        "QueryWorkflowStateUnavailable",
9427                    )
9428                })?;
9429                let workflow_state = Arc::new(Mutex::new(
9430                    WorkflowState::new_with_identity(
9431                        history_events.as_ref().clone(),
9432                        context.workflow_id.clone(),
9433                        context.run_id.clone(),
9434                        self.task_queue.clone(),
9435                        task.payload_codec,
9436                        None,
9437                    )
9438                    .map_err(|error| {
9439                        QueryTaskExecutionFailure::new(
9440                            "query_workflow_state_unavailable",
9441                            format!("workflow replay failed before query: {error}"),
9442                            "QueryWorkflowStateUnavailable",
9443                        )
9444                    })?,
9445                ));
9446                let workflow_context = WorkflowContext {
9447                    state: workflow_state,
9448                    cancellation_scope_id: "root".into(),
9449                };
9450                query_authority::before_handler(authority, &self.client).await?;
9451                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone())
9452                    .map_err(|error| {
9453                        QueryTaskExecutionFailure::new(
9454                            "query_workflow_state_unavailable",
9455                            error.to_string(),
9456                            "QueryWorkflowStateUnavailable",
9457                        )
9458                    })?;
9459                let outcome = {
9460                    let mut cx = TaskContext::from_waker(noop_waker_ref());
9461                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
9462                        .map_err(|error| {
9463                            QueryTaskExecutionFailure::new(
9464                                "query_workflow_state_unavailable",
9465                                error.to_string(),
9466                                "QueryWorkflowStateUnavailable",
9467                            )
9468                        })?;
9469                    invocation.future.as_mut().poll(&mut cx)
9470                };
9471                match outcome {
9472                    Poll::Ready(Ok(_)) => {
9473                        workflow_context
9474                            .ensure_history_consumed()
9475                            .map_err(|error| {
9476                                QueryTaskExecutionFailure::new(
9477                                    "query_workflow_state_unavailable",
9478                                    format!("workflow replay failed before query: {error}"),
9479                                    "QueryWorkflowStateUnavailable",
9480                                )
9481                            })?;
9482                    }
9483                    Poll::Ready(Err(error)) => {
9484                        return Err(QueryTaskExecutionFailure::new(
9485                            "query_workflow_state_unavailable",
9486                            format!("workflow replay failed before query: {error}"),
9487                            "QueryWorkflowStateUnavailable",
9488                        ));
9489                    }
9490                    Poll::Pending => {
9491                        let commands = workflow_context.take_commands().map_err(|error| {
9492                            QueryTaskExecutionFailure::new(
9493                                "query_workflow_state_unavailable",
9494                                format!("workflow replay failed before query: {error}"),
9495                                "QueryWorkflowStateUnavailable",
9496                            )
9497                        })?;
9498                        if commands.is_empty()
9499                            && !workflow_context
9500                                .matched_recorded_pending()
9501                                .map_err(|error| {
9502                                    QueryTaskExecutionFailure::new(
9503                                        "query_workflow_state_unavailable",
9504                                        format!("workflow replay failed before query: {error}"),
9505                                        "QueryWorkflowStateUnavailable",
9506                                    )
9507                                })?
9508                        {
9509                            return Err(QueryTaskExecutionFailure::new(
9510                                "query_workflow_state_unavailable",
9511                                "workflow replay yielded without a durable command",
9512                                "QueryWorkflowStateUnavailable",
9513                            ));
9514                        }
9515                    }
9516                }
9517                let state = (invocation.snapshot)().map_err(|error| {
9518                    QueryTaskExecutionFailure::new(
9519                        "query_workflow_state_unavailable",
9520                        format!("cannot snapshot replayed workflow state: {error}"),
9521                        "QueryWorkflowStateUnavailable",
9522                    )
9523                })?;
9524                query_authority::before_handler(authority, &self.client).await?;
9525                handler(context, state, args).map_err(|message| {
9526                    QueryTaskExecutionFailure::new(
9527                        "query_workflow_state_unavailable",
9528                        message,
9529                        "QueryWorkflowStateUnavailable",
9530                    )
9531                })?
9532            }
9533        };
9534
9535        future.await.map_err(|error| {
9536            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
9537        })
9538    }
9539
9540    #[cfg(test)]
9541    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
9542        Ok(self.execute_workflow_task_decision(task)?.commands)
9543    }
9544
9545    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
9546        self.execute_workflow_task_decision_with_cancellation(task, None)
9547    }
9548
9549    fn execute_workflow_task_decision_with_cancellation(
9550        &self,
9551        task: WorkflowTask,
9552        observation: Option<&CancellationRequest>,
9553    ) -> Result<WorkflowTaskDecision> {
9554        #[cfg(feature = "telemetry")]
9555        if let Some(telemetry) = &self.telemetry {
9556            return telemetry.run_sync_observed(
9557                "durable.workflow.task",
9558                self.workflow_telemetry_fields(&task),
9559                self.workflow_observations(&task),
9560                || {
9561                    let mut decision =
9562                        self.execute_workflow_task_decision_inner(task, observation)?;
9563                    self.stamp_observability_commands(&mut decision.commands);
9564                    Ok(decision)
9565                },
9566            );
9567        }
9568        self.execute_workflow_task_decision_inner(task, observation)
9569    }
9570
9571    fn execute_workflow_task_decision_inner(
9572        &self,
9573        task: WorkflowTask,
9574        observation: Option<&CancellationRequest>,
9575    ) -> Result<WorkflowTaskDecision> {
9576        match self.prepare_workflow_task_execution(task, observation)? {
9577            PreparedWorkflowTask::Decision(decision) => Ok(decision),
9578            PreparedWorkflowTask::Execution {
9579                task,
9580                context,
9581                mut future,
9582            } => {
9583                let outcome = Self::poll_workflow_future(&context, &mut future)?;
9584                self.finish_workflow_task_execution(&task, &context, outcome)
9585            }
9586        }
9587    }
9588
9589    fn prepare_workflow_task_execution(
9590        &self,
9591        task: WorkflowTask,
9592        observation: Option<&CancellationRequest>,
9593    ) -> Result<PreparedWorkflowTask> {
9594        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
9595            && !self.cooperative_cancellation_enabled
9596        {
9597            return Err(Error::CancellationScopeExecutionUnavailable);
9598        }
9599        validate_workflow_task_payloads(&task)?;
9600        cooperative_cancellation::assert_cancellation_scope_replay_supported(
9601            &task.history_events,
9602            self.allow_cancellation_scope_authoring,
9603            self.allow_cancellation_scope_delivery,
9604        )?;
9605        let cancellation_history = if let Some(observation) = observation {
9606            observation.validate_observation()?;
9607            cooperative_cancellation::cancellation_claim(&task)?;
9608            let canonical = CancellationHistory::from_events(
9609                &task.history_events,
9610                task.run_id.as_deref().unwrap_or_default(),
9611                Some(observation),
9612            )?;
9613            if canonical.request_index >= task.history_events.len() {
9614                return Err(Error::InvalidCooperativeCancellation(
9615                    "workflow replay requires the observed canonical request".into(),
9616                ));
9617            }
9618            Some(canonical)
9619        } else {
9620            None
9621        };
9622        if let Some(update_id) = task
9623            .workflow_update_id
9624            .as_deref()
9625            .filter(|update_id| !update_id.is_empty())
9626        {
9627            if self.allow_cancellation_scope_delivery {
9628                return Err(Error::CancellationScopeExecutionUnavailable);
9629            }
9630            CancellationHistory::from_events(
9631                &task.history_events,
9632                task.run_id.as_deref().unwrap_or_default(),
9633                None,
9634            )?;
9635            return self
9636                .execute_update_task(&task, update_id)
9637                .map(WorkflowTaskDecision::without_message_streams)
9638                .map(PreparedWorkflowTask::Decision);
9639        }
9640
9641        let workflow = self
9642            .workflows
9643            .get(&task.workflow_type)
9644            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
9645        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9646        let resume_signal = decode_resume_signal(&task)?;
9647        let history_budget = WorkflowHistoryBudget {
9648            event_count: task
9649                .total_history_events
9650                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
9651            size_bytes: task.history_size_bytes,
9652            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
9653            pressure: task.history_budget_pressure.clone(),
9654        };
9655        let workflow_command_identity = task
9656            .workflow_command_id
9657            .clone()
9658            .filter(|identity| !identity.is_empty())
9659            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
9660            .unwrap_or_default();
9661        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
9662            task.history_events.clone(),
9663            task.workflow_id.clone(),
9664            task.run_id.clone(),
9665            self.task_queue.clone(),
9666            task.payload_codec.clone(),
9667            resume_signal,
9668            self.allow_cancellation_scope_authoring,
9669            self.allow_cancellation_scope_delivery,
9670        )?;
9671        workflow_state.history_budget = history_budget;
9672        workflow_state.workflow_command_identity = workflow_command_identity;
9673        if let Some(canonical) = cancellation_history {
9674            workflow_state.cancellation_history = canonical;
9675            workflow_state.cancellation_delivery_enabled = true;
9676        }
9677        if workflow_state.cancellation_history.request.is_none() {
9678            workflow_state.cancel_requested = task.cancel_requested;
9679        }
9680        let state = Arc::new(Mutex::new(workflow_state));
9681        let ctx = WorkflowContext {
9682            state,
9683            cancellation_scope_id: "root".into(),
9684        };
9685        let future = (workflow.execute)(ctx.clone(), input)?;
9686        Ok(PreparedWorkflowTask::Execution {
9687            task,
9688            context: ctx,
9689            future,
9690        })
9691    }
9692
9693    fn poll_workflow_future(
9694        ctx: &WorkflowContext,
9695        future: &mut WorkflowFuture,
9696    ) -> Result<Poll<Result<AvroValue>>> {
9697        let mut cx = TaskContext::from_waker(noop_waker_ref());
9698        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9699        Ok(future.as_mut().poll(&mut cx))
9700    }
9701
9702    fn finish_workflow_task_execution(
9703        &self,
9704        task: &WorkflowTask,
9705        ctx: &WorkflowContext,
9706        outcome: Poll<Result<AvroValue>>,
9707    ) -> Result<WorkflowTaskDecision> {
9708        if !ctx
9709            .state
9710            .lock()
9711            .map_err(|_| Error::WorkflowStatePoisoned)?
9712            .local_activity_requests
9713            .is_empty()
9714        {
9715            return Err(Error::CooperativeCancellationUnavailable(
9716                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9717            ));
9718        }
9719        let awaiting_canonical_boundary = {
9720            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9721            state.cancellation_delivery_intent.is_some()
9722                || state.cancellation_scope_opening.is_some()
9723                || state
9724                    .scope_delivery
9725                    .as_ref()
9726                    .is_some_and(|replay| replay.intent.is_some())
9727        };
9728        if awaiting_canonical_boundary {
9729            // A private delivery intent never becomes an application error.
9730            // Even a custom future which ignores a pending durable call cannot
9731            // publish terminal commands before canonical delivery and replay.
9732            if let Poll::Ready(Err(error)) = outcome {
9733                if workflow_task_integrity_error(&error) {
9734                    return Err(error);
9735                }
9736            }
9737            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9738        }
9739
9740        match outcome {
9741            Poll::Ready(Ok(result)) => {
9742                ctx.ensure_history_consumed()?;
9743                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9744                let mut commands = ctx.take_commands()?;
9745                commands.push(json!({
9746                    "type": "complete_workflow",
9747                    "result": result
9748                }));
9749                self.message_stream_decision(&ctx, commands)
9750            }
9751            Poll::Ready(Err(error)) => {
9752                if let Error::ContinueAsNew(request) = error {
9753                    let mut commands = ctx.take_commands()?;
9754                    if let Some(command) = ctx.continue_as_new_command(request)? {
9755                        commands.push(command);
9756                    }
9757                    ctx.ensure_history_consumed()?;
9758                    return self.message_stream_decision(&ctx, commands);
9759                }
9760                if workflow_task_integrity_error(&error) {
9761                    // Replay and protocol failures describe the workflow-task
9762                    // decision itself. Preserve their specific failure reason
9763                    // instead of replacing it with the derivative fact that
9764                    // recorded commands remain unconsumed.
9765                    return Err(error);
9766                }
9767                // A handler error must not hide a committed durable command that
9768                // upgraded workflow code no longer consumes.
9769                ctx.ensure_history_consumed()?;
9770                let mut commands = ctx.take_commands()?;
9771                commands.push(workflow_failure_command(
9772                    &error,
9773                    recorded_activity_failure_boundary(&ctx, &error),
9774                ));
9775                self.message_stream_decision(&ctx, commands)
9776            }
9777            Poll::Pending => {
9778                let commands = ctx.take_commands()?;
9779                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9780                    Err(Error::WorkflowYieldedWithoutCommand)
9781                } else {
9782                    self.message_stream_decision(&ctx, commands)
9783                }
9784            }
9785        }
9786    }
9787
9788    fn message_stream_decision(
9789        &self,
9790        ctx: &WorkflowContext,
9791        commands: Vec<Value>,
9792    ) -> Result<WorkflowTaskDecision> {
9793        if !self.cooperative_cancellation_enabled
9794            && commands.iter().any(|command| {
9795                command["type"] == "schedule_activity"
9796                    && command.get("cancellation_policy").is_some()
9797            })
9798        {
9799            return Err(Error::CooperativeCancellationUnavailable(format!(
9800                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9801                self.worker_id,
9802            )));
9803        }
9804        if !self.cooperative_cancellation_enabled
9805            && commands.iter().any(|command| {
9806                command["type"] == "start_child_workflow"
9807                    && (command["parent_close_policy"] == "request_cancellation"
9808                        || matches!(
9809                            command["cancellation_policy"].as_str(),
9810                            Some("try_cancel" | "wait_cancellation_completed")
9811                        ))
9812            })
9813        {
9814            return Err(Error::CooperativeCancellationUnavailable(format!(
9815                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9816                self.worker_id,
9817            )));
9818        }
9819        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9820        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9821        let scope_delivery = state
9822            .scope_delivery
9823            .as_ref()
9824            .and_then(|replay| replay.intent.clone());
9825        if scope_delivery
9826            .as_ref()
9827            .is_some_and(|intent| commands.len() != intent.command_count)
9828        {
9829            return Err(invalid_recorded_history(
9830                "cancellation_scope_pending_call_escaped",
9831                scope_delivery.as_ref().unwrap().boundary.sequence,
9832                "commands preceding the pending scoped call",
9833                "commands after suspension",
9834                "workflow cannot publish beyond an uncommitted scope delivery",
9835            ));
9836        }
9837        if let Some(opening) = &state.cancellation_scope_opening {
9838            if commands.len() != opening.command_count {
9839                return Err(invalid_recorded_history(
9840                    "cancellation_scope_pending_call_escaped",
9841                    opening.sequence,
9842                    "commands before original scope opening",
9843                    "commands after suspended opening",
9844                    "workflow cannot publish beyond an uncommitted scope opening",
9845                ));
9846            }
9847        }
9848        if state.cancellation_delivery_intent.is_some()
9849            && commands.len() != state.cancellation_delivery_command_count
9850        {
9851            return Err(invalid_recorded_history(
9852                "cooperative_cancellation_pending_call_escaped",
9853                state
9854                    .cancellation_delivery_intent
9855                    .as_ref()
9856                    .expect("pending delivery")
9857                    .sequence,
9858                "only commands preceding the pending cancellation call",
9859                "commands authored after a suspended call",
9860                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9861            ));
9862        }
9863        Ok(WorkflowTaskDecision {
9864            commands,
9865            message_stream_cursors,
9866            message_stream_waits,
9867            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9868            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9869            cancellation_scope_delivery: scope_delivery,
9870        })
9871    }
9872
9873    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9874        if !self.workflows.contains_key(&task.workflow_type) {
9875            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9876        }
9877
9878        let accepted = task.history_events.iter().rev().find_map(|event| {
9879            (event.event_type == "UpdateAccepted"
9880                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9881            .then_some(&event.payload)
9882        });
9883        let update_name = accepted
9884            .and_then(|payload| payload.get("update_name"))
9885            .and_then(Value::as_str)
9886            .or(task.update_name.as_deref())
9887            .unwrap_or_default();
9888        let Some(handler) = self
9889            .updates
9890            .get(&task.workflow_type)
9891            .and_then(|handlers| handlers.get(update_name))
9892        else {
9893            return Ok(vec![json!({
9894                "type": "fail_update",
9895                "update_id": update_id,
9896                "message": format!(
9897                    "no update handler is registered for {}.{update_name}",
9898                    task.workflow_type
9899                ),
9900                "exception_type": "UnknownUpdate",
9901                "non_retryable": true,
9902            })]);
9903        };
9904        let arguments = accepted
9905            .and_then(|payload| payload.get("arguments"))
9906            .or(task.arguments.as_ref());
9907        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9908        let workflow_input_avro_value =
9909            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9910        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9911        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9912        let context = QueryContext {
9913            workflow_id: task.workflow_id.clone(),
9914            run_id: task.run_id.clone(),
9915            workflow_type: task.workflow_type.clone(),
9916            run_status: Some("running".to_string()),
9917            workflow_input,
9918            workflow_input_avro_value,
9919            history_events: Arc::new(task.history_events.clone()),
9920            signal_events: Arc::new(signal_events),
9921        };
9922        let mut future = handler(context, arguments);
9923        let mut cx = TaskContext::from_waker(noop_waker_ref());
9924
9925        match future.as_mut().poll(&mut cx) {
9926            Poll::Ready(Ok(result)) => Ok(vec![json!({
9927                "type": "complete_update",
9928                "update_id": update_id,
9929                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9930            })]),
9931            Poll::Ready(Err(error)) => Ok(vec![json!({
9932                "type": "fail_update",
9933                "update_id": update_id,
9934                "message": error.to_string(),
9935                "exception_type": "UpdateFailed",
9936                "non_retryable": true,
9937            })]),
9938            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9939        }
9940    }
9941
9942    #[cfg(test)]
9943    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9944        self.execute_session_activity_task(task, None, None).await
9945    }
9946
9947    async fn execute_session_activity_task(
9948        &self,
9949        task: ActivityTask,
9950        worker_session: Option<WorkerSession>,
9951        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9952    ) -> Result<AvroValue> {
9953        #[cfg(feature = "telemetry")]
9954        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
9955            !self
9956                .client
9957                .observability_context_supported
9958                .load(Ordering::SeqCst)
9959        }) {
9960            return telemetry
9961                .run(
9962                    "durable.activity.task",
9963                    self.activity_telemetry_fields(&task),
9964                    false,
9965                    self.execute_session_activity_task_inner(task, worker_session, hydration_claim),
9966                )
9967                .await;
9968        }
9969        self.execute_session_activity_task_inner(task, worker_session, hydration_claim)
9970            .await
9971    }
9972
9973    async fn execute_session_activity_task_inner(
9974        &self,
9975        task: ActivityTask,
9976        worker_session: Option<WorkerSession>,
9977        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9978    ) -> Result<AvroValue> {
9979        validate_activity_task_payloads(&task)?;
9980        if worker_session.is_some() {
9981            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9982                || task
9983                    .activity_attempt_id
9984                    .as_deref()
9985                    .or(task.attempt_id.as_deref())
9986                    .is_none_or(str::is_empty)
9987                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9988            {
9989                return Err(Error::ActivityExecutionAbandoned(
9990                    "session activity requires this worker's exact immutable claim".into(),
9991                ));
9992            }
9993        }
9994
9995        let handler = self
9996            .activities
9997            .get(&task.activity_type)
9998            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9999        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10000        let attempt_id = task
10001            .activity_attempt_id
10002            .clone()
10003            .or(task.attempt_id.clone())
10004            .unwrap_or_default();
10005        let lease_owner = task
10006            .lease_owner
10007            .clone()
10008            .unwrap_or_else(|| self.worker_id.clone());
10009        let session = worker_session.clone();
10010        if let Some(claim) = hydration_claim {
10011            claim.confirm(&self.client).await?;
10012        }
10013        #[cfg(feature = "telemetry")]
10014        let observations = self.activity_observations(&task);
10015        #[cfg(feature = "telemetry")]
10016        let fields = self.activity_telemetry_fields(&task);
10017        let ctx = ActivityContext {
10018            client: self.client.clone(),
10019            task_id: task.task_id,
10020            activity_attempt_id: attempt_id,
10021            lease_owner,
10022            activity_type: task.activity_type,
10023            attempt_number: task.attempt_number,
10024            task_queue: self.task_queue.clone(),
10025            worker_id: self.worker_id.clone(),
10026            claim_guard: None,
10027            local_heartbeats: None,
10028            worker_session,
10029        };
10030
10031        let operation = async {
10032            let callback = self.activity_callback(handler, ctx, args, false);
10033            if let Some(session) = session {
10034                tokio::select! {
10035                    biased;
10036                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10037                    result = callback => if session.active() { result } else {
10038                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10039                    },
10040                }
10041            } else {
10042                callback.await
10043            }
10044        };
10045        #[cfg(feature = "telemetry")]
10046        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10047            self.client
10048                .observability_context_supported
10049                .load(Ordering::SeqCst)
10050        }) {
10051            return telemetry
10052                .run_observed(
10053                    "durable.activity.task",
10054                    fields,
10055                    false,
10056                    observations,
10057                    operation,
10058                )
10059                .await;
10060        }
10061        operation.await
10062    }
10063
10064    fn activity_callback(
10065        &self,
10066        handler: &ActivityHandler,
10067        context: ActivityContext,
10068        args: AvroValue,
10069        local: bool,
10070    ) -> ActivityFuture {
10071        #[cfg(feature = "telemetry")]
10072        if let Some(telemetry) = &self.telemetry {
10073            let telemetry = telemetry.clone();
10074            let fields = self.callback_telemetry_fields(&context, local);
10075            let handler = handler.clone();
10076            let name = if local {
10077                "durable.local_activity.attempt"
10078            } else {
10079                "durable.activity.attempt"
10080            };
10081            return Box::pin(async move {
10082                telemetry
10083                    .run(
10084                        name,
10085                        fields,
10086                        true,
10087                        async move { handler(context, args).await },
10088                    )
10089                    .await
10090            });
10091        }
10092        #[cfg(not(feature = "telemetry"))]
10093        let _ = local;
10094        handler(context, args)
10095    }
10096}
10097
10098fn poller_result(
10099    kind: &str,
10100    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10101) -> Result<()> {
10102    match result {
10103        Ok(result) => result,
10104        Err(error) => Err(Error::WorkerLoop(format!(
10105            "{kind} poller join error: {error}"
10106        ))),
10107    }
10108}
10109
10110fn optional_poller_result(
10111    kind: &str,
10112    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10113) -> Result<()> {
10114    match result {
10115        Some(result) => poller_result(kind, result),
10116        None => Ok(()),
10117    }
10118}
10119
10120async fn join_pollers(
10121    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10122    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10123    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10124) -> Result<()> {
10125    let mut first_error = None;
10126
10127    if let Some(handle) = workflow_poller {
10128        if let Err(error) = poller_result("workflow", handle.await) {
10129            first_error.get_or_insert(error);
10130        }
10131    }
10132
10133    if let Some(handle) = activity_poller {
10134        if let Err(error) = poller_result("activity", handle.await) {
10135            first_error.get_or_insert(error);
10136        }
10137    }
10138
10139    if let Some(handle) = query_poller {
10140        if let Err(error) = poller_result("query", handle.await) {
10141            first_error.get_or_insert(error);
10142        }
10143    }
10144
10145    if let Some(error) = first_error {
10146        Err(error)
10147    } else {
10148        Ok(())
10149    }
10150}
10151
10152fn default_worker_id() -> String {
10153    let millis = SystemTime::now()
10154        .duration_since(UNIX_EPOCH)
10155        .unwrap_or_default()
10156        .as_millis();
10157    format!("rust-worker-{}-{millis}", std::process::id())
10158}
10159
10160fn percent_encode_path_segment(segment: &str) -> String {
10161    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10162    let mut encoded = String::with_capacity(segment.len());
10163
10164    for byte in segment.bytes() {
10165        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10166            encoded.push(char::from(byte));
10167        } else {
10168            encoded.push('%');
10169            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10170            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10171        }
10172    }
10173
10174    encoded
10175}
10176
10177fn unique_request_id(prefix: &str) -> String {
10178    let nanos = SystemTime::now()
10179        .duration_since(UNIX_EPOCH)
10180        .unwrap_or_default()
10181        .as_nanos();
10182    format!("{prefix}-{}-{nanos}", std::process::id())
10183}
10184
10185#[derive(Debug)]
10186struct QueryTaskExecutionFailure {
10187    reason: String,
10188    message: String,
10189    failure_type: String,
10190}
10191
10192impl QueryTaskExecutionFailure {
10193    fn new(
10194        reason: impl Into<String>,
10195        message: impl Into<String>,
10196        failure_type: impl Into<String>,
10197    ) -> Self {
10198        Self {
10199            reason: reason.into(),
10200            message: message.into(),
10201            failure_type: failure_type.into(),
10202        }
10203    }
10204}
10205
10206/// Typed local state owned by one deterministic workflow invocation.
10207///
10208/// Use [`WorkflowInstance::update`] for the same state transitions during
10209/// ordinary execution and replay. A replayed query receives a detached
10210/// immutable `Arc<S>` rather than this mutation-capable handle.
10211#[derive(Clone, Debug)]
10212pub struct WorkflowInstance<S> {
10213    state: Arc<Mutex<S>>,
10214}
10215
10216impl<S> WorkflowInstance<S> {
10217    fn new(state: S) -> Self {
10218        Self {
10219            state: Arc::new(Mutex::new(state)),
10220        }
10221    }
10222
10223    /// Read the current workflow-instance state without changing it.
10224    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10225        let state = self
10226            .state
10227            .lock()
10228            .map_err(|_| Error::WorkflowStatePoisoned)?;
10229        Ok(reader(&state))
10230    }
10231
10232    /// Apply one deterministic workflow-instance state transition.
10233    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10234        let mut state = self
10235            .state
10236            .lock()
10237            .map_err(|_| Error::WorkflowStatePoisoned)?;
10238        Ok(transition(&mut state))
10239    }
10240}
10241
10242impl<S: Clone> WorkflowInstance<S> {
10243    fn snapshot(&self) -> Result<S> {
10244        self.read(Clone::clone)
10245    }
10246}
10247
10248#[derive(Clone, Debug, PartialEq)]
10249pub struct MessageStreamMessage {
10250    pub stream_name: String,
10251    pub message_id: String,
10252    pub position: u64,
10253    pub arguments: Vec<AvroValue>,
10254}
10255
10256#[derive(Clone, Debug)]
10257pub struct MessageStream {
10258    ctx: WorkflowContext,
10259    name: String,
10260}
10261
10262impl MessageStream {
10263    /// Wait for one message, then return a bounded currently-available batch.
10264    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10265        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10266            return Err(Error::Codec(format!(
10267                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10268            )));
10269        }
10270        loop {
10271            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10272                return Ok(batch);
10273            }
10274
10275            self.ctx.record_message_stream_wait(&self.name)?;
10276            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10277            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10278            self.ctx.buffer_message_stream_delivery(arguments)?;
10279            if let Some(sequence) = replay_wait_sequence {
10280                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10281            }
10282        }
10283    }
10284
10285    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10286        self.receive(1)
10287            .await?
10288            .into_iter()
10289            .next()
10290            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10291    }
10292}
10293
10294#[derive(Clone, Debug)]
10295pub struct WorkflowContext {
10296    state: Arc<Mutex<WorkflowState>>,
10297    cancellation_scope_id: String,
10298}
10299
10300fn valid_memo_key(key: &str) -> bool {
10301    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10302
10303    !key.is_empty()
10304        && key.len() <= 64
10305        && (numeric_candidate.is_empty()
10306            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10307        && key
10308            .bytes()
10309            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10310}
10311
10312fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10313    BASE64
10314        .decode(encode_avro_value(value)?.blob)
10315        .map(|bytes| bytes.len())
10316        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10317}
10318
10319fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10320    let AvroValue::Map(entries) = value else {
10321        return Err(Error::InvalidMemoUpdate(
10322            "entries must serialize to an Avro string-keyed map".to_string(),
10323        ));
10324    };
10325    if require_entries && entries.is_empty() {
10326        return Err(Error::InvalidMemoUpdate(
10327            "at least one entry is required".to_string(),
10328        ));
10329    }
10330    if entries.len() > MAX_MEMO_ENTRIES {
10331        return Err(Error::InvalidMemoUpdate(format!(
10332            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10333        )));
10334    }
10335
10336    for (key, value) in &entries {
10337        if !valid_memo_key(&key) {
10338            return Err(Error::InvalidMemoUpdate(
10339                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10340            ));
10341        }
10342        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10343            return Err(Error::InvalidMemoUpdate(format!(
10344                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10345            )));
10346        }
10347    }
10348
10349    let value = AvroValue::Map(entries);
10350    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10351        return Err(Error::InvalidMemoUpdate(format!(
10352            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10353        )));
10354    }
10355    Ok(value)
10356}
10357
10358fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10359    let object = envelope.as_object().ok_or_else(|| {
10360        Error::InvalidMemoUpdate(
10361            "history field must use the public {codec, blob} payload envelope".to_string(),
10362        )
10363    })?;
10364    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10365        return Err(Error::InvalidMemoUpdate(
10366            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10367        ));
10368    }
10369
10370    canonical_memo_entries(
10371        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10372        require_entries,
10373    )
10374}
10375
10376impl WorkflowContext {
10377    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10378        let name = name.into();
10379        if name.is_empty()
10380            || name.len() > 128
10381            || !name.bytes().all(|byte| {
10382                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10383            })
10384        {
10385            return Err(Error::Codec(
10386                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10387                    .to_string(),
10388            ));
10389        }
10390        Ok(MessageStream {
10391            ctx: self.clone(),
10392            name,
10393        })
10394    }
10395
10396    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10397        let mut state = self
10398            .state
10399            .lock()
10400            .map_err(|_| Error::WorkflowStatePoisoned)?;
10401        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10402        state
10403            .message_stream_waits
10404            .insert(name.to_string(), position);
10405        Ok(())
10406    }
10407
10408    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
10409        let mut state = self
10410            .state
10411            .lock()
10412            .map_err(|_| Error::WorkflowStatePoisoned)?;
10413        let cursor = state
10414            .message_stream_cursors
10415            .get(&message.stream_name)
10416            .copied()
10417            .unwrap_or(0);
10418        if message.position <= cursor {
10419            return Ok(());
10420        }
10421        let pending = state
10422            .message_stream_messages
10423            .entry(message.stream_name.clone())
10424            .or_default();
10425        if pending.iter().any(|candidate| {
10426            candidate.position == message.position || candidate.message_id == message.message_id
10427        }) {
10428            return Ok(());
10429        }
10430        pending.push(message);
10431        pending.sort_by_key(|candidate| candidate.position);
10432        Ok(())
10433    }
10434
10435    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
10436        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
10437            match delivery {
10438                MessageStreamDelivery::Message(message) => {
10439                    let stream_name = message.stream_name.clone();
10440                    self.buffer_message_stream(message)?;
10441                    return Ok(Some(stream_name));
10442                }
10443                MessageStreamDelivery::Cursor {
10444                    stream_name,
10445                    through_position,
10446                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
10447            }
10448        }
10449        Ok(None)
10450    }
10451
10452    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
10453        let state = self
10454            .state
10455            .lock()
10456            .map_err(|_| Error::WorkflowStatePoisoned)?;
10457        Ok(match state.recorded_commands.get(state.command_cursor) {
10458            Some(RecordedCommand::SignalWait {
10459                sequence,
10460                signal_name,
10461                ..
10462            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
10463            _ => None,
10464        })
10465    }
10466
10467    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
10468        let (history, payload_codec) = {
10469            let state = self
10470                .state
10471                .lock()
10472                .map_err(|_| Error::WorkflowStatePoisoned)?;
10473            (
10474                Arc::clone(&state.history_events),
10475                state.payload_codec.clone(),
10476            )
10477        };
10478
10479        let Some(opened_index) = history.iter().position(|event| {
10480            event.event_type == "SignalWaitOpened"
10481                && durable_event_sequence(event) == Some(wait_sequence)
10482                && event.payload.get("signal_name").and_then(Value::as_str)
10483                    == Some(MESSAGE_STREAM_SIGNAL)
10484        }) else {
10485            return Ok(());
10486        };
10487        let boundary_index = history
10488            .iter()
10489            .enumerate()
10490            .skip(opened_index + 1)
10491            .find_map(|(index, event)| {
10492                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
10493                    && is_authored_command_open_event(event))
10494                .then_some(index)
10495            })
10496            .unwrap_or(history.len());
10497
10498        for event in history[opened_index + 1..boundary_index]
10499            .iter()
10500            .filter(|event| {
10501                event.event_type == "SignalReceived"
10502                    && event.payload.get("signal_name").and_then(Value::as_str)
10503                        == Some(MESSAGE_STREAM_SIGNAL)
10504            })
10505        {
10506            let arguments = decode_signal_event_arguments(event, &payload_codec)?
10507                .into_iter()
10508                .map(AvroValue::into_json)
10509                .collect::<Result<Vec<_>>>()?;
10510            self.buffer_message_stream_delivery(arguments)?;
10511        }
10512        Ok(())
10513    }
10514
10515    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
10516        let mut state = self
10517            .state
10518            .lock()
10519            .map_err(|_| Error::WorkflowStatePoisoned)?;
10520        let cursor = state
10521            .message_stream_cursors
10522            .entry(name.to_string())
10523            .or_default();
10524        *cursor = (*cursor).max(through_position);
10525        if let Some(pending) = state.message_stream_messages.get_mut(name) {
10526            pending.retain(|message| message.position > through_position);
10527        }
10528        Ok(())
10529    }
10530
10531    fn take_message_stream_batch(
10532        &self,
10533        name: &str,
10534        max_items: usize,
10535    ) -> Result<Option<Vec<MessageStreamMessage>>> {
10536        let mut state = self
10537            .state
10538            .lock()
10539            .map_err(|_| Error::WorkflowStatePoisoned)?;
10540        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10541        let pending = state
10542            .message_stream_messages
10543            .entry(name.to_string())
10544            .or_default();
10545        let count = contiguous_message_stream_count(pending, cursor, max_items);
10546        if count == 0 {
10547            return Ok(None);
10548        }
10549        let batch = pending.drain(..count).collect::<Vec<_>>();
10550        let position = batch.last().map(|message| message.position).unwrap_or(0);
10551        state
10552            .message_stream_cursors
10553            .insert(name.to_string(), position);
10554        state.message_stream_waits.remove(name);
10555        Ok(Some(batch))
10556    }
10557
10558    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
10559        let state = self
10560            .state
10561            .lock()
10562            .map_err(|_| Error::WorkflowStatePoisoned)?;
10563        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
10564        cursors.sort_by_key(|(name, _)| *name);
10565        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
10566        waits.sort_by_key(|(name, _)| *name);
10567        Ok((
10568            cursors
10569                .into_iter()
10570                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
10571                .collect(),
10572            waits
10573                .into_iter()
10574                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
10575                .collect(),
10576        ))
10577    }
10578    /// Identity of the parent workflow currently being replayed.
10579    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
10580        let state = self
10581            .state
10582            .lock()
10583            .map_err(|_| Error::WorkflowStatePoisoned)?;
10584        Ok(WorkflowIdentity {
10585            workflow_id: state.workflow_id.clone(),
10586            run_id: state.run_id.clone(),
10587        })
10588    }
10589
10590    /// Return the server-published history budget for this workflow task.
10591    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
10592        let state = self
10593            .state
10594            .lock()
10595            .map_err(|_| Error::WorkflowStatePoisoned)?;
10596        Ok(state.history_budget.clone())
10597    }
10598
10599    /// Continue this workflow instance as a fresh run with replacement arguments.
10600    ///
10601    /// Return this value directly from the workflow handler. The worker converts
10602    /// it to the terminal protocol command only after replay has consumed every
10603    /// recorded durable command.
10604    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
10605        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
10606    }
10607
10608    /// Continue as new with optional workflow-type and task-queue overrides.
10609    pub fn continue_as_new_with_options<T: Serialize>(
10610        &self,
10611        options: ContinueAsNewOptions,
10612        args: T,
10613    ) -> Result<Value> {
10614        options.validate()?;
10615        Err(Error::ContinueAsNew(ContinueAsNewRequest {
10616            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
10617            options,
10618        }))
10619    }
10620
10621    pub fn activity<T: Serialize>(
10622        &self,
10623        activity_type: impl Into<String>,
10624        args: T,
10625    ) -> ActivityCall {
10626        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10627    }
10628
10629    pub fn activity_on_queue<T, Q>(
10630        &self,
10631        activity_type: impl Into<String>,
10632        task_queue: Option<Q>,
10633        args: T,
10634    ) -> ActivityCall
10635    where
10636        T: Serialize,
10637        Q: Into<String>,
10638    {
10639        let mut options = ActivityOptions::new();
10640        options.task_queue = task_queue.map(Into::into);
10641        self.activity_with_options(activity_type, options, args)
10642    }
10643
10644    /// Schedule one durable activity with retry, routing, and timeout options.
10645    ///
10646    /// Options are validated before the command is emitted. Once the command is
10647    /// recorded, replay consumes the same activity lifecycle at this command
10648    /// position and never emits a duplicate schedule.
10649    ///
10650    /// ```no_run
10651    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10652    /// # use std::time::Duration;
10653    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10654    /// let result = ctx
10655    ///     .activity_with_options(
10656    ///         "charge-card",
10657    ///         ActivityOptions::new()
10658    ///             .task_queue("payments")
10659    ///             .retry_policy(
10660    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10661    ///                     Duration::from_secs(1),
10662    ///                     2,
10663    ///                     Some(Duration::from_secs(30)),
10664    ///                 ),
10665    ///             )
10666    ///             .start_to_close_timeout(Duration::from_secs(60))
10667    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10668    ///             .heartbeat_timeout(Duration::from_secs(15)),
10669    ///         json!([{"order_id": "order-42"}]),
10670    ///     )
10671    ///     .await;
10672    /// match result {
10673    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10674    ///         "reason": failure.reason,
10675    ///         "timeout_kind": failure.timeout_kind,
10676    ///     })),
10677    ///     other => other,
10678    /// }
10679    /// # }
10680    /// ```
10681    pub fn activity_with_options<T: Serialize>(
10682        &self,
10683        activity_type: impl Into<String>,
10684        options: ActivityOptions,
10685        args: T,
10686    ) -> ActivityCall {
10687        ActivityCall {
10688            ctx: self.clone(),
10689            activity_type: activity_type.into(),
10690            options,
10691            worker_session: None,
10692            args: Some(AvroValue::from_serialize(&args)),
10693            scheduled: false,
10694            local: false,
10695            local_result: None,
10696            parallel_group_path: Vec::new(),
10697        }
10698    }
10699
10700    pub async fn activity_avro_value<T: Serialize>(
10701        &self,
10702        activity_type: impl Into<String>,
10703        args: T,
10704    ) -> Result<AvroValue> {
10705        let mut call = self.activity(activity_type, args);
10706        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10707    }
10708
10709    pub async fn activity_avro_value_with_options<T: Serialize>(
10710        &self,
10711        activity_type: impl Into<String>,
10712        options: ActivityOptions,
10713        args: T,
10714    ) -> Result<AvroValue> {
10715        let mut call = self.activity_with_options(activity_type, options, args);
10716        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10717    }
10718
10719    /// Schedule an activity with a Serde request and decode its Serde result.
10720    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10721    where
10722        I: Serialize,
10723        O: DeserializeOwned,
10724    {
10725        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10726            .await
10727    }
10728
10729    /// Schedule an activity with options and decode its result into `O`.
10730    ///
10731    /// Both directions use the fixed Avro Value codec. In particular, this
10732    /// method does not deserialize the JSON-safe inspection projection returned
10733    /// by the dynamic [`ActivityCall`] future.
10734    pub async fn activity_typed_with_options<I, O>(
10735        &self,
10736        activity_type: impl Into<String>,
10737        options: ActivityOptions,
10738        args: I,
10739    ) -> Result<O>
10740    where
10741        I: Serialize,
10742        O: DeserializeOwned,
10743    {
10744        let activity_type = activity_type.into();
10745        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10746            handler_type_error::<I>(
10747                HandlerKind::Activity,
10748                &activity_type,
10749                HandlerValueKind::Input,
10750                error.to_string(),
10751            )
10752        });
10753        let mut call = ActivityCall {
10754            ctx: self.clone(),
10755            activity_type: activity_type.clone(),
10756            options,
10757            worker_session: None,
10758            args: Some(encoded),
10759            scheduled: false,
10760            local: false,
10761            local_result: None,
10762            parallel_group_path: Vec::new(),
10763        };
10764        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10765        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10766    }
10767
10768    /// Schedule and join a deterministic activity/child/timer group.
10769    ///
10770    /// Nested groups retain their input shape. Every durable leaf is scheduled
10771    /// before this future yields, results are assembled by declaration order,
10772    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10773    /// declaration path, stable group metadata, and completed siblings.
10774    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10775        ParallelCall::new(self.clone(), operations)
10776    }
10777
10778    /// Alias for [`WorkflowContext::parallel`].
10779    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10780        self.parallel(operations)
10781    }
10782
10783    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10784    pub async fn parallel_avro_value(
10785        &self,
10786        operations: Vec<ParallelOperation>,
10787    ) -> Result<Vec<ParallelAvroResult>> {
10788        let mut call = self.parallel(operations);
10789        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10790    }
10791
10792    /// Start every durable operation and resume from the one winner persisted
10793    /// by Server. Non-winning operations continue and remain addressable.
10794    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10795        let operations = operations
10796            .into_iter()
10797            .enumerate()
10798            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10799            .collect();
10800        SelectCall::new(self.clone(), operations)
10801    }
10802
10803    /// Named-key variant of [`WorkflowContext::select`].
10804    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10805    where
10806        K: Into<SelectionKey>,
10807    {
10808        SelectCall::new(
10809            self.clone(),
10810            operations
10811                .into_iter()
10812                .map(|(key, operation)| (key.into(), operation))
10813                .collect(),
10814        )
10815    }
10816
10817    /// Create a workflow-local deterministic compensation registry.
10818    pub fn saga(&self) -> Saga {
10819        Saga::new(self.clone())
10820    }
10821
10822    /// Whether cancellation has reached this replay's authored boundary.
10823    ///
10824    /// Server's current `/cancel` route is terminal and does not set this flag.
10825    /// A canonical service request remains pending until its committed delivery
10826    /// is consumed. Request observation alone does not authorize an exception.
10827    pub fn is_cancellation_requested(&self) -> Result<bool> {
10828        let state = self
10829            .state
10830            .lock()
10831            .map_err(|_| Error::WorkflowStatePoisoned)?;
10832        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10833            return Ok(state
10834                .scope_delivery
10835                .as_ref()
10836                .unwrap()
10837                .contexts
10838                .contains_key(&self.cancellation_scope_id));
10839        }
10840        Ok(state.cancel_requested
10841            || state
10842                .scope_delivery
10843                .as_ref()
10844                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10845    }
10846
10847    /// Raise a typed cooperative cancellation at an author-controlled point.
10848    ///
10849    /// Passing this result to [`Saga::finish`] compensates already registered
10850    /// forward steps before the cancellation remains the initiating outcome.
10851    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10852        let mut state = self
10853            .state
10854            .lock()
10855            .map_err(|_| Error::WorkflowStatePoisoned)?;
10856        if state.cancellation_shield_depth == 0 {
10857            if let Some(replay) = &state.scope_delivery {
10858                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10859                    let delivered = replay
10860                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10861                        .ok_or_else(|| {
10862                            Error::InvalidCooperativeCancellation(
10863                                "scoped request lacks its consumed original delivery".into(),
10864                            )
10865                        })?;
10866                    return Err(Error::CancellationScopeRequested(
10867                        CancellationScopeRequested {
10868                            context: context
10869                                .clone()
10870                                .with_replay(Some(Arc::downgrade(&self.state))),
10871                            delivery: delivered.boundary.clone(),
10872                        },
10873                    ));
10874                }
10875            }
10876        }
10877        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10878            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10879                return Ok(());
10880            }
10881            return Err(state.cancellation_error());
10882        }
10883        Ok(())
10884    }
10885
10886    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10887        SignalCall {
10888            ctx: self.clone(),
10889            signal_name: signal_name.into(),
10890            runtime_reserved_allowed: false,
10891            opened_wait: false,
10892            matched_pending: false,
10893            parallel_group_path: Vec::new(),
10894        }
10895    }
10896
10897    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10898        SignalCall {
10899            ctx: self.clone(),
10900            signal_name: signal_name.into(),
10901            runtime_reserved_allowed: true,
10902            opened_wait: false,
10903            matched_pending: false,
10904            parallel_group_path: Vec::new(),
10905        }
10906    }
10907
10908    pub async fn wait_signal_avro_value(
10909        &self,
10910        signal_name: impl Into<String>,
10911    ) -> Result<Vec<AvroValue>> {
10912        let mut call = self.wait_signal(signal_name);
10913        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10914    }
10915
10916    /// Return every committed signal argument list with the given name.
10917    ///
10918    /// This history-backed view is deterministic and is intended for
10919    /// condition predicates that must be re-evaluated after a signal while the
10920    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10921    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10922        self.signals_avro_value(signal_name)?
10923            .into_iter()
10924            .map(|arguments| {
10925                arguments
10926                    .into_iter()
10927                    .map(AvroValue::into_json)
10928                    .collect::<Result<Vec<_>>>()
10929            })
10930            .collect()
10931    }
10932
10933    /// Lossless fixed Avro Value view of committed signals with the given name.
10934    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10935        let state = self
10936            .state
10937            .lock()
10938            .map_err(|_| Error::WorkflowStatePoisoned)?;
10939        state
10940            .history_events
10941            .iter()
10942            .filter(|event| {
10943                event.event_type == "SignalReceived"
10944                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10945            })
10946            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10947            .collect()
10948    }
10949
10950    /// Return every committed update argument list with the given name.
10951    ///
10952    /// Accepted and applied records for the same update ID are de-duplicated.
10953    /// A Server task created after an update therefore replays the workflow and
10954    /// re-evaluates an open condition without application polling.
10955    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10956        self.updates_avro_value(update_name)?
10957            .into_iter()
10958            .map(|arguments| {
10959                arguments
10960                    .into_iter()
10961                    .map(AvroValue::into_json)
10962                    .collect::<Result<Vec<_>>>()
10963            })
10964            .collect()
10965    }
10966
10967    /// Lossless fixed Avro Value view of committed updates with the given name.
10968    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10969        let state = self
10970            .state
10971            .lock()
10972            .map_err(|_| Error::WorkflowStatePoisoned)?;
10973        let mut seen = Vec::new();
10974        let mut updates = Vec::new();
10975        for event in state.history_events.iter() {
10976            if !matches!(
10977                event.event_type.as_str(),
10978                "UpdateAccepted" | "UpdateApplied"
10979            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10980                || event.payload.get("arguments").is_none()
10981            {
10982                continue;
10983            }
10984            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10985                if seen.iter().any(|recorded| recorded == update_id) {
10986                    continue;
10987                }
10988                seen.push(update_id.to_string());
10989            }
10990            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10991        }
10992        Ok(updates)
10993    }
10994
10995    /// Wait for a deterministic predicate to become true or for its durable
10996    /// timeout to elapse.
10997    ///
10998    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10999    /// predicate tokens automatically change the recorded definition
11000    /// fingerprint. Direct callers must provide an equally stable identity in
11001    /// [`ConditionWaitOptions`].
11002    pub fn wait_condition<F>(
11003        &self,
11004        options: ConditionWaitOptions,
11005        predicate: F,
11006    ) -> ConditionWaitCall
11007    where
11008        F: Fn() -> Result<bool> + Send + 'static,
11009    {
11010        ConditionWaitCall {
11011            ctx: self.clone(),
11012            options,
11013            predicate: Box::new(predicate),
11014            occurrence_id: None,
11015            opened_wait: false,
11016            parallel_group_path: Vec::new(),
11017        }
11018    }
11019
11020    /// Wait for server-backed durable time without blocking the worker executor.
11021    ///
11022    /// Polling this future emits one `start_timer` command and yields. The
11023    /// server records the deadline, so neither worker nor server restarts reset
11024    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11025    /// `TimerFired` pair at the same position in the shared durable-command
11026    /// stream, with matching sequence, timer identity, and delay. Sub-second
11027    /// durations round up because protocol deadlines use whole seconds.
11028    ///
11029    /// ```no_run
11030    /// # use durable_workflow::{json, Client, Worker};
11031    /// # use std::time::Duration;
11032    /// # fn configure(client: Client) {
11033    /// let mut worker = Worker::new(client, "rust-workers");
11034    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11035    ///     ctx.sleep(Duration::from_secs(5)).await?;
11036    ///     Ok(json!({"status": "timer fired"}))
11037    /// });
11038    /// # }
11039    /// ```
11040    pub fn sleep(&self, duration: Duration) -> TimerCall {
11041        let delay_seconds = duration
11042            .as_secs()
11043            .checked_add(u64::from(duration.subsec_nanos() > 0));
11044        TimerCall {
11045            ctx: self.clone(),
11046            delay_seconds,
11047            scheduled: false,
11048            matched_pending: false,
11049            parallel_group_path: Vec::new(),
11050        }
11051    }
11052
11053    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11054    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11055        self.sleep(duration)
11056    }
11057
11058    /// Evaluate a non-deterministic callback once and durably record its typed value.
11059    ///
11060    /// On replay the callback is not invoked: the value is decoded from the
11061    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11062    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11063    /// small values that must remain fixed for the lifetime of a workflow run.
11064    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11065    where
11066        T: Serialize + DeserializeOwned,
11067        F: FnOnce() -> T,
11068    {
11069        {
11070            let mut state = self
11071                .state
11072                .lock()
11073                .map_err(|_| Error::WorkflowStatePoisoned)?;
11074            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11075                return match recorded {
11076                    RecordedCommand::SideEffect { sequence, value } => {
11077                        state.command_cursor += 1;
11078                        value.deserialize().map_err(|error| {
11079                            Error::NonDeterministicReplay(ReplayFailure::new(
11080                                "side_effect_type_mismatch",
11081                                Some(sequence),
11082                                Some(std::any::type_name::<T>().to_string()),
11083                                Some(error.to_string()),
11084                                "recorded side-effect value is incompatible with the requested Rust type",
11085                            ))
11086                        })
11087                    }
11088                    other => Err(command_mismatch(&other, "side effect")),
11089                };
11090            }
11091        }
11092
11093        let value = callback();
11094        let avro_value = AvroValue::from_serialize(&value)?;
11095        let mut state = self
11096            .state
11097            .lock()
11098            .map_err(|_| Error::WorkflowStatePoisoned)?;
11099        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11100        state.commands.push(json!({
11101            "type": "record_side_effect",
11102            "result": result,
11103        }));
11104        Ok(value)
11105    }
11106
11107    /// Record or replay a lossless fixed Avro Value side effect.
11108    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11109    where
11110        F: FnOnce() -> AvroValue,
11111    {
11112        {
11113            let mut state = self
11114                .state
11115                .lock()
11116                .map_err(|_| Error::WorkflowStatePoisoned)?;
11117            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11118                return match recorded {
11119                    RecordedCommand::SideEffect { value, .. } => {
11120                        state.command_cursor += 1;
11121                        Ok(value)
11122                    }
11123                    other => Err(command_mismatch(&other, "side effect")),
11124                };
11125            }
11126        }
11127
11128        let value = callback();
11129        let mut state = self
11130            .state
11131            .lock()
11132            .map_err(|_| Error::WorkflowStatePoisoned)?;
11133        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11134        state.commands.push(json!({
11135            "type": "record_side_effect",
11136            "result": result,
11137        }));
11138        Ok(value)
11139    }
11140
11141    /// Append output items at a deterministic workflow command boundary.
11142    ///
11143    /// Stable idempotency keys are derived from the server-provided durable
11144    /// workflow command identity, command ordinal, and item index. Replay
11145    /// consumes the recorded side effect and never emits another append.
11146    pub fn append_workflow_stream(
11147        &self,
11148        stream_name: impl Into<String>,
11149        items: &[WorkflowStreamAppendItem],
11150        max_pending_items: Option<u64>,
11151    ) -> Result<()> {
11152        if items.is_empty() {
11153            return Err(Error::Codec(
11154                "workflow_stream_items_empty: append requires at least one item".to_string(),
11155            ));
11156        }
11157        if max_pending_items == Some(0) {
11158            return Err(Error::Codec(
11159                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11160                    .to_string(),
11161            ));
11162        }
11163        let stream_name = stream_name.into();
11164        if stream_name.is_empty() {
11165            return Err(Error::Codec(
11166                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11167            ));
11168        }
11169
11170        let mut state = self
11171            .state
11172            .lock()
11173            .map_err(|_| Error::WorkflowStatePoisoned)?;
11174        let command_ordinal = state.workflow_stream_command_counter;
11175        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11176            state.workflow_stream_command_counter += 1;
11177            return match recorded {
11178                RecordedCommand::SideEffect { .. } => {
11179                    state.command_cursor += 1;
11180                    Ok(())
11181                }
11182                other => Err(command_mismatch(&other, "workflow stream append")),
11183            };
11184        }
11185
11186        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11187        state.workflow_stream_command_counter += 1;
11188        let wire_items = items
11189            .iter()
11190            .enumerate()
11191            .map(|(item_index, item)| {
11192                item.wire_value(Some(format!(
11193                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11194                )))
11195            })
11196            .collect::<Vec<_>>();
11197        let mut directive = json!({
11198            "operation": "append",
11199            "stream_name": stream_name,
11200            "command_identity": identity,
11201            "command_ordinal": command_ordinal,
11202            "items": wire_items,
11203        });
11204        if let Some(max_pending_items) = max_pending_items {
11205            directive["max_pending_items"] = json!(max_pending_items);
11206        }
11207        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11208        state.commands.push(json!({
11209            "type": "record_side_effect",
11210            "result": result,
11211            "workflow_stream": directive,
11212        }));
11213        Ok(())
11214    }
11215
11216    /// Close a run-scoped output stream at a deterministic command boundary.
11217    pub fn close_workflow_stream(
11218        &self,
11219        stream_name: impl Into<String>,
11220        retention_seconds: Option<u64>,
11221    ) -> Result<()> {
11222        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11223    }
11224
11225    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11226    pub fn error_workflow_stream(
11227        &self,
11228        stream_name: impl Into<String>,
11229        error_reason: impl Into<String>,
11230        retention_seconds: Option<u64>,
11231    ) -> Result<()> {
11232        let error_reason = error_reason.into();
11233        if error_reason.is_empty() {
11234            return Err(Error::Codec(
11235                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11236            ));
11237        }
11238        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11239    }
11240
11241    fn finish_workflow_stream(
11242        &self,
11243        stream_name: String,
11244        error_reason: Option<String>,
11245        retention_seconds: Option<u64>,
11246    ) -> Result<()> {
11247        if stream_name.is_empty() {
11248            return Err(Error::Codec(
11249                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11250            ));
11251        }
11252        if retention_seconds == Some(0) {
11253            return Err(Error::Codec(
11254                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11255            ));
11256        }
11257        let mut state = self
11258            .state
11259            .lock()
11260            .map_err(|_| Error::WorkflowStatePoisoned)?;
11261        let command_ordinal = state.workflow_stream_command_counter;
11262        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11263            state.workflow_stream_command_counter += 1;
11264            return match recorded {
11265                RecordedCommand::SideEffect { .. } => {
11266                    state.command_cursor += 1;
11267                    Ok(())
11268                }
11269                other => Err(command_mismatch(&other, "workflow stream close")),
11270            };
11271        }
11272        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11273        state.workflow_stream_command_counter += 1;
11274        let mut directive = json!({
11275            "operation": if error_reason.is_some() { "error" } else { "close" },
11276            "stream_name": stream_name,
11277            "command_identity": identity,
11278            "command_ordinal": command_ordinal,
11279        });
11280        if let Some(error_reason) = error_reason {
11281            directive["error_reason"] = json!(error_reason);
11282        }
11283        if let Some(retention_seconds) = retention_seconds {
11284            directive["retention_seconds"] = json!(retention_seconds);
11285        }
11286        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11287        state.commands.push(json!({
11288            "type": "record_side_effect",
11289            "result": result,
11290            "workflow_stream": directive,
11291        }));
11292        Ok(())
11293    }
11294
11295    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11296        let identity = state.workflow_command_identity.as_str();
11297        if identity.is_empty() {
11298            return Err(Error::MissingWorkflowCommandIdentity);
11299        }
11300        Ok(identity)
11301    }
11302
11303    /// Validate, emit, or replay a typed workflow search-attribute update.
11304    ///
11305    /// The command is non-blocking within a workflow decision, but its
11306    /// `SearchAttributesUpserted` event occupies the same deterministic command
11307    /// stream as activities, timers, conditions, and other durable operations.
11308    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11309        update.validate()?;
11310        let (attributes, attribute_types) = update.into_wire_parts();
11311        let mut state = self
11312            .state
11313            .lock()
11314            .map_err(|_| Error::WorkflowStatePoisoned)?;
11315
11316        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11317            return match recorded {
11318                RecordedCommand::SearchAttributes {
11319                    sequence,
11320                    attributes: recorded_attributes,
11321                    attribute_types: recorded_attribute_types,
11322                } => {
11323                    if recorded_attributes != attributes {
11324                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11325                            "search_attribute_value_mismatch",
11326                            Some(sequence),
11327                            Some(recorded_attributes.to_string()),
11328                            Some(attributes.to_string()),
11329                            "search-attribute values differ from the recorded durable command",
11330                        )));
11331                    }
11332                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11333                        if recorded_types != attribute_types {
11334                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11335                                "search_attribute_type_mismatch",
11336                                Some(sequence),
11337                                Some(json!(recorded_types).to_string()),
11338                                Some(json!(attribute_types).to_string()),
11339                                "search-attribute declared types differ from the recorded durable command",
11340                            )));
11341                        }
11342                    }
11343                    state.command_cursor += 1;
11344                    Ok(())
11345                }
11346                other => Err(command_mismatch(&other, "search-attribute update")),
11347            };
11348        }
11349
11350        let mut command = serde_json::Map::from_iter([
11351            ("type".to_string(), json!("upsert_search_attributes")),
11352            ("attributes".to_string(), attributes),
11353        ]);
11354        if !attribute_types.is_empty() {
11355            command.insert("attribute_types".to_string(), json!(attribute_types));
11356        }
11357        state.commands.push(Value::Object(command));
11358        Ok(())
11359    }
11360
11361    /// Record a UUIDv4 once and return the same UUID on every replay.
11362    pub fn uuid_v4(&self) -> Result<Uuid> {
11363        self.side_effect(Uuid::new_v4)
11364    }
11365
11366    /// Select the newest supported version for a change, or replay the version
11367    /// already committed for that stable change ID.
11368    ///
11369    /// An unmarked old history that reached its next durable operation, or
11370    /// already completed, selects `-1` when that version is supported. This
11371    /// leaves the original operation available and writes no additional marker.
11372    /// Consistent markers written by older workers retain their original ordered
11373    /// positions. Repeated calls consume a matching marker at the current cursor.
11374    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11375    pub fn get_version(
11376        &self,
11377        change_id: impl Into<String>,
11378        min_supported: i32,
11379        max_supported: i32,
11380    ) -> Result<i32> {
11381        let change_id = change_id.into();
11382        if change_id.trim().is_empty() {
11383            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11384                "version_change_id_invalid",
11385                None,
11386                Some("non-empty change ID".to_string()),
11387                Some(change_id),
11388                "version markers require a stable non-empty change ID",
11389            )));
11390        }
11391        if min_supported > max_supported {
11392            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11393                "version_range_invalid",
11394                None,
11395                Some("min_supported <= max_supported".to_string()),
11396                Some(format!("{min_supported}..={max_supported}")),
11397                "version marker supported range is invalid",
11398            )));
11399        }
11400
11401        let mut state = self
11402            .state
11403            .lock()
11404            .map_err(|_| Error::WorkflowStatePoisoned)?;
11405        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
11406            if let Some(RecordedCommand::VersionMarker {
11407                sequence: alias_sequence,
11408                change_id: alias_change_id,
11409                version: alias_version,
11410            }) = state.recorded_commands.get(state.command_cursor)
11411            {
11412                if alias_change_id == &change_id {
11413                    if *alias_version != version {
11414                        return Err(invalid_recorded_history(
11415                            "version_marker_conflict",
11416                            *alias_sequence,
11417                            &format!("selected version {version} for change ID {change_id:?}"),
11418                            &format!("recorded version {alias_version}"),
11419                            "recorded marker conflicts with the decision already selected during replay",
11420                        ));
11421                    }
11422                    ensure_version_supported(
11423                        &change_id,
11424                        version,
11425                        min_supported,
11426                        max_supported,
11427                        *alias_sequence,
11428                    )?;
11429                    // Older workers could record the same decision again. Keep
11430                    // each physical boundary without skipping intervening work.
11431                    state.command_cursor += 1;
11432                    return Ok(version);
11433                }
11434            }
11435            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
11436            return Ok(version);
11437        }
11438
11439        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11440            return match recorded {
11441                RecordedCommand::VersionMarker {
11442                    sequence,
11443                    change_id: recorded_change_id,
11444                    version,
11445                    ..
11446                } => {
11447                    if recorded_change_id != change_id {
11448                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11449                            "version_change_id_mismatch",
11450                            Some(sequence),
11451                            Some(recorded_change_id),
11452                            Some(change_id),
11453                            "recorded version marker change ID differs from current workflow code",
11454                        )));
11455                    }
11456                    ensure_version_supported(
11457                        &change_id,
11458                        version,
11459                        min_supported,
11460                        max_supported,
11461                        sequence,
11462                    )?;
11463                    state.command_cursor += 1;
11464                    state.version_markers.insert(change_id, (version, sequence));
11465                    Ok(version)
11466                }
11467                other => {
11468                    let version = -1;
11469                    let sequence = other.sequence();
11470                    ensure_version_supported(
11471                        &change_id,
11472                        version,
11473                        min_supported,
11474                        max_supported,
11475                        sequence,
11476                    )?;
11477                    // The existing operation proves this patch site was reached
11478                    // before its marker existed. Keep its original cursor.
11479                    state.version_markers.insert(change_id, (version, sequence));
11480                    Ok(version)
11481                }
11482            };
11483        }
11484
11485        if state
11486            .history_events
11487            .iter()
11488            .any(|event| event.event_type == "WorkflowCompleted")
11489        {
11490            let version = -1;
11491            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
11492            state.version_markers.insert(change_id, (version, 0));
11493            return Ok(version);
11494        }
11495
11496        let version = max_supported;
11497        state.commands.push(json!({
11498            "type": "record_version_marker",
11499            "change_id": change_id,
11500            "version": version,
11501            "min_supported": min_supported,
11502            "max_supported": max_supported,
11503        }));
11504        // Sequence numbers are assigned by the server. Zero identifies a marker
11505        // selected in this uncommitted decision batch for duplicate-call checks.
11506        state.version_markers.insert(change_id, (version, 0));
11507        Ok(version)
11508    }
11509
11510    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
11511    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
11512        Ok(self.get_version(change_id, -1, 1)? == 1)
11513    }
11514
11515    /// Keep a patch marker in history after the legacy branch has been removed.
11516    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
11517        self.get_version(change_id, -1, 1).map(|_| ())
11518    }
11519
11520    /// Merge non-indexed workflow memo metadata through durable history.
11521    ///
11522    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
11523    /// public Avro payload envelope consumed by Server and Cloud runtimes.
11524    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
11525        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
11526        let mut state = self
11527            .state
11528            .lock()
11529            .map_err(|_| Error::WorkflowStatePoisoned)?;
11530
11531        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11532            return match recorded {
11533                RecordedCommand::Memo {
11534                    sequence,
11535                    entries: recorded_entries,
11536                } => {
11537                    if recorded_entries != entries {
11538                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11539                            "memo_update_mismatch",
11540                            Some(sequence),
11541                            Some(format!("{recorded_entries:?}")),
11542                            Some(format!("{entries:?}")),
11543                            "recorded memo entries differ from the current workflow update",
11544                        )));
11545                    }
11546                    state.command_cursor += 1;
11547                    Ok(())
11548                }
11549                other => Err(command_mismatch(&other, "memo upsert")),
11550            };
11551        }
11552
11553        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
11554        state.commands.push(json!({
11555            "type": "upsert_memo",
11556            "entries": entries_envelope,
11557        }));
11558        Ok(())
11559    }
11560
11561    /// Start a named durable child on an explicit queue and await its result.
11562    ///
11563    /// The command is recorded in the parent's sequence-ordered durable command
11564    /// stream. Replay keeps a scheduled child pending without emitting another
11565    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
11566    /// values preserve the history payload codec and include both sides of the
11567    /// durable relationship; failures are returned as
11568    /// [`Error::ChildWorkflowFailed`].
11569    ///
11570    /// ```no_run
11571    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
11572    /// # fn configure(client: Client) {
11573    /// let mut worker = Worker::new(client, "parent-workers");
11574    /// worker.register_workflow("order-parent", |ctx, _input| async move {
11575    ///     let child = ctx
11576    ///         .start_child_workflow(
11577    ///             "fulfil-order",
11578    ///             ChildWorkflowOptions::new("fulfilment-workers")
11579    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
11580    ///             json!([{"order_id": "order-42"}]),
11581    ///         )
11582    ///         .await?;
11583    ///     Ok(child.result)
11584    /// });
11585    /// # }
11586    /// ```
11587    pub fn start_child_workflow<T: Serialize>(
11588        &self,
11589        workflow_type: impl Into<String>,
11590        options: ChildWorkflowOptions,
11591        args: T,
11592    ) -> ChildWorkflowCall {
11593        ChildWorkflowCall {
11594            ctx: self.clone(),
11595            workflow_type: workflow_type.into(),
11596            options,
11597            args: Some(AvroValue::from_serialize(&args)),
11598            scheduled: false,
11599            matched_pending: false,
11600            parallel_group_path: Vec::new(),
11601        }
11602    }
11603
11604    pub async fn start_child_workflow_avro_value<T: Serialize>(
11605        &self,
11606        workflow_type: impl Into<String>,
11607        options: ChildWorkflowOptions,
11608        args: T,
11609    ) -> Result<ChildWorkflowAvroResult> {
11610        let mut call = self.start_child_workflow(workflow_type, options, args);
11611        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11612    }
11613
11614    fn take_commands(&self) -> Result<Vec<Value>> {
11615        let mut state = self
11616            .state
11617            .lock()
11618            .map_err(|_| Error::WorkflowStatePoisoned)?;
11619        Ok(std::mem::take(&mut state.commands))
11620    }
11621
11622    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11623        let mut state = self
11624            .state
11625            .lock()
11626            .map_err(|_| Error::WorkflowStatePoisoned)?;
11627
11628        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11629            return Err(command_mismatch(&recorded, "continue as new"));
11630        }
11631        if state.recorded_continue_as_new_sequence.is_some() {
11632            state.continue_as_new_consumed = true;
11633            return Ok(None);
11634        }
11635
11636        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11637        let mut command = serde_json::Map::from_iter([
11638            ("type".to_string(), json!("continue_as_new")),
11639            ("arguments".to_string(), arguments),
11640            ("queue".to_string(), json!(state.task_queue.clone())),
11641        ]);
11642        if let Some(workflow_type) = request.options.workflow_type {
11643            command.insert("workflow_type".to_string(), json!(workflow_type));
11644        }
11645        if let Some(task_queue) = request.options.task_queue {
11646            command.insert("queue".to_string(), json!(task_queue));
11647        }
11648        Ok(Some(Value::Object(command)))
11649    }
11650
11651    fn matched_recorded_pending(&self) -> Result<bool> {
11652        let state = self
11653            .state
11654            .lock()
11655            .map_err(|_| Error::WorkflowStatePoisoned)?;
11656        Ok(state.matched_recorded_pending)
11657    }
11658
11659    fn ensure_history_consumed(&self) -> Result<()> {
11660        let state = self
11661            .state
11662            .lock()
11663            .map_err(|_| Error::WorkflowStatePoisoned)?;
11664        if let Some(replay) = &state.scope_delivery {
11665            if let Some((&sequence, _)) = replay
11666                .canonical
11667                .deliveries
11668                .iter()
11669                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11670            {
11671                return Err(invalid_recorded_history(
11672                    "cancellation_scope_delivery_unconsumed",
11673                    sequence,
11674                    "original scoped delivery",
11675                    "workflow completion",
11676                    "workflow completed without consuming its committed scope delivery",
11677                ));
11678            }
11679        }
11680        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11681            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11682                "recorded_commands_unconsumed",
11683                Some(command.sequence()),
11684                Some(command.shape().to_string()),
11685                Some("workflow completion".to_string()),
11686                "workflow completed before consuming all recorded durable commands",
11687            )));
11688        }
11689        if let Some(delivery) = state
11690            .cancellation_history
11691            .delivery
11692            .as_ref()
11693            .filter(|_| !state.cancellation_consumed)
11694        {
11695            return Err(invalid_recorded_history(
11696                "cooperative_cancellation_unconsumed",
11697                delivery.sequence,
11698                "committed cancellation call",
11699                "workflow completion",
11700                "workflow completed without reaching its committed cancellation boundary",
11701            ));
11702        }
11703        if let Some(sequence) = state
11704            .recorded_continue_as_new_sequence
11705            .filter(|_| !state.continue_as_new_consumed)
11706        {
11707            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11708                "recorded_continue_as_new_unconsumed",
11709                Some(sequence),
11710                Some("continue as new".to_string()),
11711                Some("workflow completion".to_string()),
11712                "workflow completed without consuming its recorded continue-as-new transition",
11713            )));
11714        }
11715        Ok(())
11716    }
11717}
11718
11719fn contiguous_message_stream_count(
11720    pending: &[MessageStreamMessage],
11721    cursor: u64,
11722    max_items: usize,
11723) -> usize {
11724    pending
11725        .iter()
11726        .take(max_items)
11727        .enumerate()
11728        .take_while(|(offset, message)| {
11729            u64::try_from(*offset)
11730                .ok()
11731                .and_then(|offset| cursor.checked_add(offset + 1))
11732                == Some(message.position)
11733        })
11734        .count()
11735}
11736
11737fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11738    matches!(
11739        event.event_type.as_str(),
11740        "ActivityScheduled"
11741            | "TimerScheduled"
11742            | "ChildWorkflowScheduled"
11743            | "SignalWaitOpened"
11744            | "ConditionWaitOpened"
11745            | "SearchAttributesUpserted"
11746            | "SideEffectRecorded"
11747            | "VersionMarkerRecorded"
11748            | "MemoUpserted"
11749            | "WorkflowContinuedAsNew"
11750    )
11751}
11752
11753#[derive(Debug)]
11754struct WorkflowState {
11755    workflow_id: Option<String>,
11756    run_id: Option<String>,
11757    task_queue: String,
11758    payload_codec: String,
11759    history_events: Arc<Vec<HistoryEvent>>,
11760    history_budget: WorkflowHistoryBudget,
11761    cancel_requested: bool,
11762    cancellation_history: CancellationHistory,
11763    cancellation_consumed: bool,
11764    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11765    cancellation_shield_depth: u64,
11766    cancellation_delivery_enabled: bool,
11767    cancellation_delivery_intent: Option<CancellationDelivery>,
11768    cancellation_delivery_command_count: usize,
11769    allow_cancellation_scope_authoring: bool,
11770    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11771    cancellation_scope_memberships: BTreeMap<u64, String>,
11772    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11773    resume_signal: Option<ResumeSignal>,
11774    recorded_commands: Vec<RecordedCommand>,
11775    selection_markers: Vec<SelectionMarker>,
11776    selection_marker_cursor: usize,
11777    cancelled_selection_members: Vec<SelectionCancellation>,
11778    recorded_continue_as_new_sequence: Option<u64>,
11779    continue_as_new_consumed: bool,
11780    command_cursor: usize,
11781    condition_wait_occurrence_counter: u64,
11782    matched_recorded_pending: bool,
11783    version_markers: HashMap<String, (i32, u64)>,
11784    workflow_command_identity: String,
11785    workflow_stream_command_counter: u64,
11786    commands: Vec<Value>,
11787    local_activity_requests: Vec<local_activity::Request>,
11788    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11789    message_stream_cursors: HashMap<String, u64>,
11790    message_stream_waits: HashMap<String, u64>,
11791}
11792
11793impl WorkflowState {
11794    #[cfg(test)]
11795    fn new(
11796        history: Vec<HistoryEvent>,
11797        task_queue: String,
11798        payload_codec: String,
11799        resume_signal: Option<ResumeSignal>,
11800    ) -> Result<Self> {
11801        Self::new_with_identity(
11802            history,
11803            None,
11804            None,
11805            task_queue,
11806            payload_codec,
11807            resume_signal,
11808        )
11809    }
11810
11811    fn new_with_identity(
11812        history: Vec<HistoryEvent>,
11813        workflow_id: Option<String>,
11814        run_id: Option<String>,
11815        task_queue: String,
11816        payload_codec: String,
11817        resume_signal: Option<ResumeSignal>,
11818    ) -> Result<Self> {
11819        Self::new_with_identity_and_scopes(
11820            history,
11821            workflow_id,
11822            run_id,
11823            task_queue,
11824            payload_codec,
11825            resume_signal,
11826            false,
11827        )
11828    }
11829
11830    fn new_with_identity_and_scopes(
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        allow_cancellation_scope_authoring: bool,
11838    ) -> Result<Self> {
11839        Self::new_with_identity_and_scope_delivery(
11840            history,
11841            workflow_id,
11842            run_id,
11843            task_queue,
11844            payload_codec,
11845            resume_signal,
11846            allow_cancellation_scope_authoring,
11847            false,
11848        )
11849    }
11850
11851    fn new_with_identity_and_scope_delivery(
11852        history: Vec<HistoryEvent>,
11853        workflow_id: Option<String>,
11854        run_id: Option<String>,
11855        task_queue: String,
11856        payload_codec: String,
11857        resume_signal: Option<ResumeSignal>,
11858        allow_cancellation_scope_authoring: bool,
11859        allow_cancellation_scope_delivery: bool,
11860    ) -> Result<Self> {
11861        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11862            &history,
11863            allow_cancellation_scope_authoring,
11864            allow_cancellation_scope_delivery,
11865        )?;
11866        let scopes = if allow_cancellation_scope_authoring {
11867            cancellation_scope::CancellationScopeHistory::read(
11868                &history,
11869                run_id.as_deref().unwrap_or_default(),
11870            )?
11871        } else {
11872            cancellation_scope::CancellationScopeHistory::default()
11873        };
11874        let cancellation_history = CancellationHistory::from_events(
11875            &history,
11876            run_id.as_deref().unwrap_or_default(),
11877            None,
11878        )?;
11879        if allow_cancellation_scope_authoring
11880            && cancellation_history.request.is_some()
11881            && !allow_cancellation_scope_delivery
11882        {
11883            return Err(Error::CancellationScopeExecutionUnavailable);
11884        }
11885        let scope_delivery = if allow_cancellation_scope_delivery {
11886            Some(cancellation_scope_replay::ScopeReplay::read(
11887                &history,
11888                &scopes,
11889                run_id.as_deref().unwrap_or_default(),
11890                workflow_id.as_deref().unwrap_or_default(),
11891            )?)
11892        } else {
11893            None
11894        };
11895        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11896            &history,
11897            &payload_codec,
11898            WorkflowIdentity {
11899                workflow_id: workflow_id.clone(),
11900                run_id: run_id.clone(),
11901            },
11902        )?)?;
11903        for (sequence, opening) in &scopes.openings {
11904            if recorded_commands
11905                .iter()
11906                .any(|command| command.sequence() == *sequence)
11907            {
11908                return Err(invalid_recorded_history(
11909                    "invalid_cancellation_scope_history",
11910                    *sequence,
11911                    "distinct authored scope opening",
11912                    "operation collision",
11913                    "scope opening collides with a command",
11914                ));
11915            }
11916            recorded_commands.push(RecordedCommand::CancellationScope {
11917                sequence: *sequence,
11918                scope_id: opening.scope_id.clone(),
11919                parent_scope_id: opening.parent_scope_id.clone(),
11920                shield_parent: opening.shield_parent,
11921            });
11922        }
11923        recorded_commands.sort_by_key(RecordedCommand::sequence);
11924        if let Some(replay) = &scope_delivery {
11925            replay.bind_commands(&mut recorded_commands)?;
11926        }
11927        let selection_markers = recorded_selection_markers(&history)?;
11928        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11929        let recorded_continue_as_new = history
11930            .iter()
11931            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11932            .collect::<Vec<_>>();
11933        if recorded_continue_as_new.len() > 1 {
11934            return Err(invalid_recorded_history(
11935                "duplicate_continue_as_new_transition",
11936                recorded_continue_as_new
11937                    .last()
11938                    .and_then(|event| durable_event_sequence(event))
11939                    .unwrap_or(0),
11940                "one WorkflowContinuedAsNew event",
11941                &format!(
11942                    "{} WorkflowContinuedAsNew events",
11943                    recorded_continue_as_new.len()
11944                ),
11945                "workflow history records one continue-as-new transition more than once",
11946            ));
11947        }
11948        let recorded_continue_as_new_sequence = recorded_continue_as_new
11949            .first()
11950            .map(|event| {
11951                durable_event_sequence(event).ok_or_else(|| {
11952                    Error::NonDeterministicReplay(ReplayFailure::new(
11953                        "continue_as_new_sequence_missing",
11954                        None,
11955                        Some("recorded transition sequence".to_string()),
11956                        Some("missing sequence".to_string()),
11957                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11958                    ))
11959                })
11960            })
11961            .transpose()?;
11962        let mut message_stream_cursors = HashMap::new();
11963        for event in &history {
11964            if !matches!(
11965                event.event_type.as_str(),
11966                "SignalReceived" | "SignalApplied"
11967            ) || event.payload.get("signal_name").and_then(Value::as_str)
11968                != Some(MESSAGE_STREAM_SIGNAL)
11969            {
11970                continue;
11971            }
11972            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11973            if arguments.len() != 1 {
11974                continue;
11975            }
11976            let envelope = arguments[0].clone().into_json()?;
11977            let Some(envelope) = envelope.as_object() else {
11978                continue;
11979            };
11980            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11981            {
11982                continue;
11983            }
11984            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11985                continue;
11986            };
11987            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11988            else {
11989                continue;
11990            };
11991            let cursor = message_stream_cursors
11992                .entry(stream_name.to_string())
11993                .or_insert(0);
11994            *cursor = (*cursor).max(through_position);
11995        }
11996        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11997        let cancel_requested = history.iter().any(|event| {
11998            matches!(
11999                event.event_type.as_str(),
12000                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
12001            )
12002        });
12003        let cancellation_clock = cancellation_history
12004            .request
12005            .as_ref()
12006            .and_then(|request| request.context.as_ref())
12007            .map(|_| {
12008                cancellation_replay_clock::ReplayClock::new(
12009                    &history,
12010                    &recorded_commands,
12011                    cancellation_history.delivery_index,
12012                )
12013            })
12014            .or_else(|| {
12015                scope_delivery.as_ref().map(|_| {
12016                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12017                })
12018            });
12019        Ok(Self {
12020            workflow_command_identity: String::new(),
12021            workflow_stream_command_counter: 0,
12022            workflow_id,
12023            run_id,
12024            task_queue,
12025            payload_codec,
12026            history_events: Arc::new(history),
12027            history_budget: WorkflowHistoryBudget {
12028                event_count,
12029                ..WorkflowHistoryBudget::default()
12030            },
12031            cancel_requested,
12032            cancellation_history,
12033            cancellation_consumed: false,
12034            cancellation_clock,
12035            cancellation_shield_depth: 0,
12036            cancellation_delivery_enabled: false,
12037            cancellation_delivery_intent: None,
12038            cancellation_delivery_command_count: 0,
12039            allow_cancellation_scope_authoring,
12040            cancellation_scope_opening: None,
12041            cancellation_scope_memberships: scopes.memberships,
12042            scope_delivery,
12043            resume_signal,
12044            recorded_commands,
12045            selection_markers,
12046            selection_marker_cursor: 0,
12047            cancelled_selection_members,
12048            recorded_continue_as_new_sequence,
12049            continue_as_new_consumed: false,
12050            command_cursor: 0,
12051            condition_wait_occurrence_counter: 0,
12052            matched_recorded_pending: false,
12053            version_markers: HashMap::new(),
12054            commands: Vec::new(),
12055            local_activity_requests: Vec::new(),
12056            message_stream_messages: HashMap::new(),
12057            message_stream_cursors,
12058            message_stream_waits: HashMap::new(),
12059        })
12060    }
12061}
12062
12063enum MessageStreamDelivery {
12064    Message(MessageStreamMessage),
12065    Cursor {
12066        stream_name: String,
12067        through_position: u64,
12068    },
12069}
12070
12071fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12072    if arguments.len() != 1 {
12073        return Ok(None);
12074    }
12075    let envelope = arguments
12076        .into_iter()
12077        .next()
12078        .expect("one argument was checked");
12079    let Some(envelope) = envelope.as_object() else {
12080        return Ok(None);
12081    };
12082    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12083        return Ok(None);
12084    };
12085    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12086        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12087        else {
12088            return Ok(None);
12089        };
12090        return Ok(Some(MessageStreamDelivery::Cursor {
12091            stream_name: stream_name.to_string(),
12092            through_position,
12093        }));
12094    }
12095    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12096        return Ok(None);
12097    }
12098    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12099        return Ok(None);
12100    };
12101    let Some(position) = envelope
12102        .get("position")
12103        .and_then(Value::as_u64)
12104        .filter(|value| *value > 0)
12105    else {
12106        return Ok(None);
12107    };
12108    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12109        return Ok(None);
12110    };
12111    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12112    else {
12113        return Ok(None);
12114    };
12115    let decoded = decode_avro_value(&payload_envelope)?;
12116    let AvroValue::Array(values) = decoded else {
12117        return Ok(None);
12118    };
12119    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12120        stream_name: stream_name.to_string(),
12121        message_id: message_id.to_string(),
12122        position,
12123        arguments: values,
12124    })))
12125}
12126
12127#[derive(Clone, Debug)]
12128enum RecordedCommand {
12129    ServiceOperation {
12130        sequence: u64,
12131        call: nexus::RecordedServiceCall,
12132    },
12133    CancellationScope {
12134        sequence: u64,
12135        scope_id: String,
12136        parent_scope_id: String,
12137        shield_parent: bool,
12138    },
12139    CancellationGroup {
12140        sequence: u64,
12141        span: u64,
12142        original: Vec<RecordedCommand>,
12143    },
12144    CancellationBoundary {
12145        sequence: u64,
12146        call_kind: CancellationCallKind,
12147        original: Option<Box<RecordedCommand>>,
12148    },
12149    Activity {
12150        sequence: u64,
12151        activity_type: Option<String>,
12152        cancellation_policy: String,
12153        options: Option<RecordedActivityOptions>,
12154        outcome: Option<ActivityOutcome>,
12155        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12156    },
12157    Timer {
12158        sequence: u64,
12159        delay_seconds: u64,
12160        fired: bool,
12161        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12162    },
12163    ChildWorkflow {
12164        sequence: u64,
12165        workflow_type: Option<String>,
12166        policies: RecordedChildPolicies,
12167        outcome: Option<ChildWorkflowOutcome>,
12168        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12169    },
12170    SignalWait {
12171        sequence: u64,
12172        signal_name: String,
12173        value: Option<Vec<AvroValue>>,
12174        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12175    },
12176    ConditionWait {
12177        sequence: u64,
12178        occurrence_id: String,
12179        condition_key: Option<String>,
12180        predicate_identity: String,
12181        timeout_seconds: Option<u64>,
12182        result: Option<ConditionWaitResult>,
12183        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12184    },
12185    SearchAttributes {
12186        sequence: u64,
12187        attributes: Value,
12188        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12189    },
12190    SideEffect {
12191        sequence: u64,
12192        value: AvroValue,
12193    },
12194    VersionMarker {
12195        sequence: u64,
12196        change_id: String,
12197        version: i32,
12198    },
12199    Memo {
12200        sequence: u64,
12201        entries: AvroValue,
12202    },
12203}
12204
12205#[derive(Clone, Debug, PartialEq, Eq)]
12206struct SelectionMarker {
12207    selection_group_id: String,
12208    selection_group_base_sequence: u64,
12209    selection_group_size: usize,
12210    member_key: SelectionKey,
12211    member_index: usize,
12212    member_base_sequence: u64,
12213    member_size: usize,
12214    operation_kind: String,
12215    operation_identity: String,
12216    outcome: String,
12217    resolution_event_id: String,
12218    resolution_event_type: String,
12219}
12220
12221#[derive(Clone, Debug, PartialEq, Eq)]
12222struct SelectionCancellation {
12223    selection_group_id: String,
12224    member_key: SelectionKey,
12225    member_index: usize,
12226    member_base_sequence: u64,
12227    member_size: usize,
12228    operation_kind: String,
12229    operation_identity: String,
12230}
12231
12232fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12233    let mut markers: Vec<SelectionMarker> = Vec::new();
12234    for event in events
12235        .iter()
12236        .filter(|event| event.event_type == "SelectionResolved")
12237    {
12238        let payload = &event.payload;
12239        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12240        let group_size = required_selection_usize(payload, "selection_group_size")?;
12241        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12242        let member_size = required_selection_usize(payload, "member_size")?;
12243        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12244        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12245            invalid_recorded_history(
12246                "selection_marker_invalid",
12247                base_sequence,
12248                "non-empty selection_group_id",
12249                &payload.to_string(),
12250                "selection winner history is missing its durable group identity",
12251            )
12252        })?;
12253        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12254        if group_id != expected_group_id {
12255            return Err(invalid_recorded_history(
12256                "selection_marker_invalid",
12257                base_sequence,
12258                &expected_group_id,
12259                &group_id,
12260                "selection winner history contains an incompatible group identity",
12261            ));
12262        }
12263        let group_end = base_sequence
12264            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12265            .unwrap_or(u64::MAX);
12266        let member_end = member_base_sequence
12267            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12268            .unwrap_or(u64::MAX);
12269        if member_index >= group_size
12270            || member_base_sequence < base_sequence
12271            || member_end > group_end
12272        {
12273            return Err(invalid_recorded_history(
12274                "selection_marker_invalid",
12275                base_sequence,
12276                "winner member within selection group bounds",
12277                &payload.to_string(),
12278                "selection winner history contains an invalid member range",
12279            ));
12280        }
12281        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12282            invalid_recorded_history(
12283                "selection_marker_invalid",
12284                base_sequence,
12285                "selection operation kind",
12286                &payload.to_string(),
12287                "selection winner history is missing its operation kind",
12288            )
12289        })?;
12290        if !matches!(
12291            operation_kind.as_str(),
12292            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12293        ) {
12294            return Err(invalid_recorded_history(
12295                "selection_marker_invalid",
12296                base_sequence,
12297                "activity, child, timer, signal, condition, or group",
12298                &operation_kind,
12299                "selection winner history contains an unsupported operation kind",
12300            ));
12301        }
12302        let operation_identity =
12303            payload_string(payload, "operation_identity").ok_or_else(|| {
12304                invalid_recorded_history(
12305                    "selection_marker_invalid",
12306                    base_sequence,
12307                    "non-empty operation identity",
12308                    &payload.to_string(),
12309                    "selection winner history is missing its durable operation identity",
12310                )
12311            })?;
12312        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12313            invalid_recorded_history(
12314                "selection_marker_invalid",
12315                base_sequence,
12316                "completed or failed selection outcome",
12317                &payload.to_string(),
12318                "selection winner history is missing its outcome",
12319            )
12320        })?;
12321        if !matches!(outcome.as_str(), "completed" | "failed") {
12322            return Err(invalid_recorded_history(
12323                "selection_marker_invalid",
12324                base_sequence,
12325                "completed or failed selection outcome",
12326                &outcome,
12327                "selection winner history contains an unsupported outcome",
12328            ));
12329        }
12330        let marker = SelectionMarker {
12331            selection_group_id: group_id,
12332            selection_group_base_sequence: base_sequence,
12333            selection_group_size: group_size,
12334            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
12335            member_index,
12336            member_base_sequence,
12337            member_size,
12338            operation_kind,
12339            operation_identity,
12340            outcome,
12341            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
12342                || {
12343                    invalid_recorded_history(
12344                        "selection_marker_invalid",
12345                        base_sequence,
12346                        "durable resolution_event_id",
12347                        &payload.to_string(),
12348                        "selection winner history is missing its terminal event identity",
12349                    )
12350                },
12351            )?,
12352            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
12353                || {
12354                    invalid_recorded_history(
12355                        "selection_marker_invalid",
12356                        base_sequence,
12357                        "durable resolution_event_type",
12358                        &payload.to_string(),
12359                        "selection winner history is missing its terminal event type",
12360                    )
12361                },
12362            )?,
12363        };
12364        if let Some(existing) = markers
12365            .iter()
12366            .find(|existing| existing.selection_group_id == marker.selection_group_id)
12367        {
12368            if existing != &marker {
12369                return Err(invalid_recorded_history(
12370                    "selection_marker_conflict",
12371                    base_sequence,
12372                    &format!("one winner for {}", marker.selection_group_id),
12373                    &payload.to_string(),
12374                    "selection history records conflicting winners for one durable group",
12375                ));
12376            }
12377            continue;
12378        }
12379        markers.push(marker);
12380    }
12381    Ok(markers)
12382}
12383
12384fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
12385    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
12386    for event in events
12387        .iter()
12388        .filter(|event| event.event_type == "SelectionOperationCancelled")
12389    {
12390        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
12391            invalid_recorded_history(
12392                "selection_cancellation_invalid",
12393                0,
12394                "non-empty selection_group_id",
12395                &event.payload.to_string(),
12396                "selection cancellation history is missing its group identity",
12397            )
12398        })?;
12399        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
12400        let marker = SelectionCancellation {
12401            selection_group_id: group_id,
12402            member_key: selection_key_from_value(
12403                event.payload.get("member_key"),
12404                member_base_sequence,
12405            )?,
12406            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
12407            member_base_sequence,
12408            member_size: required_selection_usize(&event.payload, "member_size")?,
12409            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
12410                invalid_recorded_history(
12411                    "selection_cancellation_invalid",
12412                    member_base_sequence,
12413                    "selection operation kind",
12414                    &event.payload.to_string(),
12415                    "selection cancellation is missing its operation kind",
12416                )
12417            })?,
12418            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
12419                || {
12420                    invalid_recorded_history(
12421                        "selection_cancellation_invalid",
12422                        member_base_sequence,
12423                        "selection operation identity",
12424                        &event.payload.to_string(),
12425                        "selection cancellation is missing its operation identity",
12426                    )
12427                },
12428            )?,
12429        };
12430        if let Some(existing) = cancelled.iter().find(|recorded| {
12431            recorded.selection_group_id == marker.selection_group_id
12432                && recorded.member_base_sequence == marker.member_base_sequence
12433        }) {
12434            if existing != &marker {
12435                return Err(invalid_recorded_history(
12436                    "selection_cancellation_conflict",
12437                    member_base_sequence,
12438                    "one stable SelectionOperationCancelled marker",
12439                    &event.payload.to_string(),
12440                    "selection cancellation history contains conflicting member metadata",
12441                ));
12442            }
12443        } else {
12444            cancelled.push(marker);
12445        }
12446    }
12447    Ok(cancelled)
12448}
12449
12450fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
12451    payload
12452        .get(field)
12453        .and_then(value_as_u64)
12454        .filter(|value| *value > 0)
12455        .ok_or_else(|| {
12456            invalid_recorded_history(
12457                "selection_marker_invalid",
12458                0,
12459                &format!("positive integer {field}"),
12460                &payload.to_string(),
12461                "selection history contains invalid durable identity metadata",
12462            )
12463        })
12464}
12465
12466fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
12467    required_selection_usize_allow_zero(payload, field).and_then(|value| {
12468        if value > 0 {
12469            Ok(value)
12470        } else {
12471            Err(invalid_recorded_history(
12472                "selection_marker_invalid",
12473                0,
12474                &format!("positive integer {field}"),
12475                &payload.to_string(),
12476                "selection history contains invalid durable identity metadata",
12477            ))
12478        }
12479    })
12480}
12481
12482fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
12483    payload
12484        .get(field)
12485        .and_then(value_as_u64)
12486        .and_then(|value| usize::try_from(value).ok())
12487        .ok_or_else(|| {
12488            invalid_recorded_history(
12489                "selection_marker_invalid",
12490                0,
12491                &format!("non-negative integer {field}"),
12492                &payload.to_string(),
12493                "selection history contains invalid durable identity metadata",
12494            )
12495        })
12496}
12497
12498#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12499struct RecordedActivityOptions {
12500    task_queue: RecordedSnapshotValue<Option<String>>,
12501    execution_mode: RecordedSnapshotValue<Option<String>>,
12502    retry_policy: ActivityRetrySnapshot,
12503    worker_session: Option<Value>,
12504}
12505
12506#[derive(Clone, Debug)]
12507struct RecordedChildPolicies {
12508    parent_close_policy: String,
12509    cancellation_policy: String,
12510}
12511
12512fn recorded_activity_cancellation_policy(
12513    events: &[&HistoryEvent],
12514    sequence: u64,
12515) -> Result<String> {
12516    let mut policy: Option<String> = None;
12517    for event in events.iter().filter(|event| {
12518        matches!(
12519            event.event_type.as_str(),
12520            "ActivityScheduled"
12521                | "ActivityStarted"
12522                | "ActivityCompleted"
12523                | "ActivityFailed"
12524                | "ActivityTimedOut"
12525                | "ActivityCancelled"
12526        )
12527    }) {
12528        for source in [Some(&event.payload), event.payload.get("activity")]
12529            .into_iter()
12530            .flatten()
12531        {
12532            let Some(value) = source.get("cancellation_policy") else {
12533                continue;
12534            };
12535            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
12536                value.as_str()
12537            else {
12538                return Err(invalid_recorded_history(
12539                    "invalid_activity_cancellation_policy_history",
12540                    sequence,
12541                    "supported Activity cancellation policy",
12542                    &value.to_string(),
12543                    "Activity history contains an invalid cancellation policy",
12544                ));
12545            };
12546            if let Some(previous) = policy.as_deref() {
12547                if previous != incoming {
12548                    return Err(invalid_recorded_history(
12549                        "activity_cancellation_policy_history_conflict",
12550                        sequence,
12551                        previous,
12552                        incoming,
12553                        "Activity cancellation policy changed between history events",
12554                    ));
12555                }
12556            }
12557            policy = Some(incoming.to_string());
12558        }
12559        policy.get_or_insert_with(|| "try_cancel".to_string());
12560    }
12561    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
12562}
12563
12564fn recorded_child_policy_value<'a>(
12565    payload: &'a Value,
12566    field: &str,
12567    sequence: u64,
12568) -> Result<Option<&'a str>> {
12569    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
12570        return Ok(None);
12571    };
12572    let valid = match (field, value.as_str()) {
12573        (
12574            "parent_close_policy",
12575            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
12576        ) => true,
12577        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
12578            true
12579        }
12580        _ => false,
12581    };
12582    if !valid {
12583        return Err(invalid_recorded_history(
12584            "invalid_child_workflow_policy_history",
12585            sequence,
12586            "supported child workflow policy",
12587            &value.to_string(),
12588            "child workflow history contains an invalid policy",
12589        ));
12590    }
12591    Ok(value.as_str())
12592}
12593
12594fn recorded_child_policies(
12595    events: &[&HistoryEvent],
12596    scheduled: &HistoryEvent,
12597    sequence: u64,
12598) -> Result<RecordedChildPolicies> {
12599    let parent_close_policy =
12600        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
12601            .unwrap_or("abandon")
12602            .to_string();
12603    let cancellation_policy =
12604        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
12605            .unwrap_or("abandon")
12606            .to_string();
12607    for event in events {
12608        for (field, expected) in [
12609            ("parent_close_policy", parent_close_policy.as_str()),
12610            ("cancellation_policy", cancellation_policy.as_str()),
12611        ] {
12612            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
12613                if actual != expected {
12614                    return Err(invalid_recorded_history(
12615                        "child_workflow_policy_history_conflict",
12616                        sequence,
12617                        expected,
12618                        actual,
12619                        "child workflow policy changed between history events",
12620                    ));
12621                }
12622            }
12623        }
12624    }
12625    Ok(RecordedChildPolicies {
12626        parent_close_policy,
12627        cancellation_policy,
12628    })
12629}
12630
12631fn ensure_child_policies_match(
12632    sequence: u64,
12633    recorded: &RecordedChildPolicies,
12634    current: &ChildWorkflowOptions,
12635) -> Result<()> {
12636    for (field, expected, actual) in [
12637        (
12638            "parent_close_policy",
12639            recorded.parent_close_policy.as_str(),
12640            current.parent_close_policy.as_str(),
12641        ),
12642        (
12643            "cancellation_policy",
12644            recorded.cancellation_policy.as_str(),
12645            current.cancellation_policy.as_str(),
12646        ),
12647    ] {
12648        if expected != actual {
12649            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12650                "child_workflow_policy_changed",
12651                Some(sequence),
12652                Some(expected.to_string()),
12653                Some(actual.to_string()),
12654                format!("child workflow {field} changed during replay"),
12655            )));
12656        }
12657    }
12658    Ok(())
12659}
12660
12661#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12662enum RecordedSnapshotValue<T> {
12663    /// Older history did not persist this field, so it cannot constrain replay.
12664    Unknown,
12665    Known(T),
12666}
12667
12668impl<T: PartialEq> RecordedSnapshotValue<T> {
12669    fn matches_current(&self, current: &Self) -> bool {
12670        match self {
12671            Self::Unknown => true,
12672            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12673        }
12674    }
12675}
12676
12677#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12678struct ActivityRetrySnapshot {
12679    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12680    max_attempts: RecordedSnapshotValue<Option<u64>>,
12681    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12682    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12683    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12684    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12685    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12686    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12687}
12688
12689impl ActivityRetrySnapshot {
12690    fn matches_current(&self, current: &Self) -> bool {
12691        self.snapshot_version
12692            .matches_current(&current.snapshot_version)
12693            && self.max_attempts.matches_current(&current.max_attempts)
12694            && self
12695                .backoff_seconds
12696                .matches_current(&current.backoff_seconds)
12697            && self
12698                .start_to_close_timeout
12699                .matches_current(&current.start_to_close_timeout)
12700            && self
12701                .schedule_to_start_timeout
12702                .matches_current(&current.schedule_to_start_timeout)
12703            && self
12704                .schedule_to_close_timeout
12705                .matches_current(&current.schedule_to_close_timeout)
12706            && self
12707                .heartbeat_timeout
12708                .matches_current(&current.heartbeat_timeout)
12709            && self
12710                .non_retryable_error_types
12711                .matches_current(&current.non_retryable_error_types)
12712    }
12713}
12714
12715fn recorded_optional_u64(
12716    object: Option<&serde_json::Map<String, Value>>,
12717    field: &str,
12718) -> RecordedSnapshotValue<Option<u64>> {
12719    match object.and_then(|object| object.get(field)) {
12720        None => RecordedSnapshotValue::Unknown,
12721        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12722        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12723    }
12724}
12725
12726fn recorded_optional_string(
12727    object: &serde_json::Map<String, Value>,
12728    field: &str,
12729) -> RecordedSnapshotValue<Option<String>> {
12730    match object.get(field) {
12731        None => RecordedSnapshotValue::Unknown,
12732        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12733        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12734    }
12735}
12736
12737fn recorded_activity_execution_mode(
12738    events: &[&HistoryEvent],
12739    sequence: u64,
12740) -> Result<RecordedSnapshotValue<Option<String>>> {
12741    let mut recorded = RecordedSnapshotValue::Unknown;
12742    for event in events {
12743        for object in [
12744            event.payload.as_object(),
12745            event.payload.get("activity").and_then(Value::as_object),
12746        ]
12747        .into_iter()
12748        .flatten()
12749        {
12750            let mode = match object.get("execution_mode") {
12751                None => None,
12752                Some(Value::Null) => Some(None),
12753                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12754                Some(_) => {
12755                    return Err(invalid_recorded_history(
12756                        "activity_execution_mode_invalid",
12757                        sequence,
12758                        "null or a non-empty execution mode",
12759                        "invalid execution_mode",
12760                        "activity history contains an invalid execution mode",
12761                    ))
12762                }
12763            };
12764            let legacy_mode = match object.get("local_activity") {
12765                None => None,
12766                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12767                Some(_) => {
12768                    return Err(invalid_recorded_history(
12769                        "activity_execution_mode_invalid",
12770                        sequence,
12771                        "boolean local_activity",
12772                        "invalid local_activity",
12773                        "activity history contains an invalid local-activity marker",
12774                    ))
12775                }
12776            };
12777            for mode in [mode, legacy_mode].into_iter().flatten() {
12778                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12779                {
12780                    return Err(invalid_recorded_history(
12781                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12782                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12783                    ));
12784                }
12785                recorded = RecordedSnapshotValue::Known(mode);
12786            }
12787        }
12788    }
12789    Ok(recorded)
12790}
12791
12792fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12793    let policy = policy.and_then(Value::as_object);
12794    let backoff_seconds = policy
12795        .and_then(|policy| policy.get("backoff_seconds"))
12796        .and_then(Value::as_array)
12797        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12798        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12799    let mut non_retryable_error_types = Vec::new();
12800    for error_type in policy
12801        .and_then(|policy| policy.get("non_retryable_error_types"))
12802        .and_then(Value::as_array)
12803        .into_iter()
12804        .flatten()
12805        .filter_map(Value::as_str)
12806        .map(str::trim)
12807        .filter(|error_type| !error_type.is_empty())
12808    {
12809        if !non_retryable_error_types
12810            .iter()
12811            .any(|recorded| recorded == error_type)
12812        {
12813            non_retryable_error_types.push(error_type.to_string());
12814        }
12815    }
12816
12817    ActivityRetrySnapshot {
12818        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12819        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12820        backoff_seconds,
12821        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12822        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12823        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12824        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12825        non_retryable_error_types: if policy
12826            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12827        {
12828            RecordedSnapshotValue::Known(non_retryable_error_types)
12829        } else {
12830            RecordedSnapshotValue::Unknown
12831        },
12832    }
12833}
12834
12835fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12836    let policy = options.retry_policy.as_ref();
12837    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12838        Some(Value::Null) => None,
12839        Some(value) => value_as_u64(value),
12840        None => Some(1),
12841    };
12842    let backoff_seconds = policy
12843        .and_then(|policy| policy.get("backoff_seconds"))
12844        .and_then(Value::as_array)
12845        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12846        .unwrap_or_default();
12847    let non_retryable_error_types = policy
12848        .and_then(|policy| policy.get("non_retryable_error_types"))
12849        .and_then(Value::as_array)
12850        .into_iter()
12851        .flatten()
12852        .filter_map(Value::as_str)
12853        .map(str::to_string)
12854        .collect();
12855
12856    ActivityRetrySnapshot {
12857        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12858        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12859        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12860        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12861        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12862        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12863        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12864        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12865    }
12866}
12867
12868fn activity_options_description(options: &RecordedActivityOptions) -> String {
12869    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12870}
12871
12872impl RecordedCommand {
12873    fn sequence(&self) -> u64 {
12874        match self {
12875            Self::CancellationGroup { sequence, .. }
12876            | Self::CancellationScope { sequence, .. }
12877            | Self::CancellationBoundary { sequence, .. }
12878            | Self::Activity { sequence, .. }
12879            | Self::Timer { sequence, .. }
12880            | Self::ChildWorkflow { sequence, .. }
12881            | Self::SignalWait { sequence, .. }
12882            | Self::ConditionWait { sequence, .. }
12883            | Self::SearchAttributes { sequence, .. }
12884            | Self::SideEffect { sequence, .. }
12885            | Self::VersionMarker { sequence, .. }
12886            | Self::Memo { sequence, .. } => *sequence,
12887            Self::ServiceOperation { sequence, .. } => *sequence,
12888        }
12889    }
12890
12891    fn shape(&self) -> &'static str {
12892        match self {
12893            Self::CancellationScope { .. } => "cancellation scope",
12894            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12895                "cooperative cancellation"
12896            }
12897            Self::Activity { .. } => "activity",
12898            Self::Timer { .. } => "timer",
12899            Self::ChildWorkflow { .. } => "child workflow",
12900            Self::SignalWait { .. } => "signal wait",
12901            Self::ConditionWait { .. } => "condition wait",
12902            Self::SearchAttributes { .. } => "search-attribute update",
12903            Self::SideEffect { .. } => "side effect",
12904            Self::VersionMarker { .. } => "version marker",
12905            Self::Memo { .. } => "memo upsert",
12906            Self::ServiceOperation { .. } => "service operation",
12907        }
12908    }
12909}
12910
12911fn ensure_version_supported(
12912    change_id: &str,
12913    version: i32,
12914    min_supported: i32,
12915    max_supported: i32,
12916    sequence: u64,
12917) -> Result<()> {
12918    if (min_supported..=max_supported).contains(&version) {
12919        return Ok(());
12920    }
12921    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12922        "version_marker_incompatible_range",
12923        (sequence != 0).then_some(sequence),
12924        Some(format!("{min_supported}..={max_supported}")),
12925        Some(format!("{change_id}:{version}")),
12926        "recorded workflow version is outside the range supported by current code",
12927    )))
12928}
12929
12930#[derive(Clone, Debug)]
12931struct ResumeSignal {
12932    signal_name: String,
12933    arguments: Vec<AvroValue>,
12934}
12935
12936const MAX_PARALLEL_OPERATIONS: usize = 1000;
12937
12938fn parallel_group_prefix(kind: &str) -> &'static str {
12939    match kind {
12940        "activity" => "parallel-activities",
12941        "child" => "parallel-children",
12942        "timer" => "parallel-timers",
12943        _ => "parallel-calls",
12944    }
12945}
12946
12947fn parallel_group_entry(
12948    base_sequence: u64,
12949    size: usize,
12950    index: usize,
12951    kind: &str,
12952) -> ParallelGroupMetadata {
12953    ParallelGroupMetadata {
12954        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12955        parallel_group_kind: kind.to_string(),
12956        parallel_group_base_sequence: base_sequence,
12957        parallel_group_size: size,
12958        parallel_group_index: index,
12959        parallel_group_mode: None,
12960        selection_member_key: None,
12961        selection_member_index: None,
12962        selection_member_base_sequence: None,
12963        selection_member_size: None,
12964        selection_member_kind: None,
12965    }
12966}
12967
12968struct SelectionMemberMetadata {
12969    key: SelectionKey,
12970    index: usize,
12971    base_sequence: u64,
12972    size: usize,
12973    kind: String,
12974}
12975
12976fn selection_group_entry(
12977    base_sequence: u64,
12978    size: usize,
12979    index: usize,
12980    kind: &str,
12981    member: &SelectionMemberMetadata,
12982) -> ParallelGroupMetadata {
12983    ParallelGroupMetadata {
12984        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
12985        parallel_group_kind: kind.to_string(),
12986        parallel_group_base_sequence: base_sequence,
12987        parallel_group_size: size,
12988        parallel_group_index: index,
12989        parallel_group_mode: Some("select".to_string()),
12990        selection_member_key: Some(member.key.clone()),
12991        selection_member_index: Some(member.index),
12992        selection_member_base_sequence: Some(member.base_sequence),
12993        selection_member_size: Some(member.size),
12994        selection_member_kind: Some(member.kind.clone()),
12995    }
12996}
12997
12998fn apply_parallel_group_path(
12999    command: &mut serde_json::Map<String, Value>,
13000    path: &[ParallelGroupMetadata],
13001) {
13002    let Some(inner) = path.last() else {
13003        return;
13004    };
13005    command.insert(
13006        "parallel_group_id".to_string(),
13007        json!(inner.parallel_group_id),
13008    );
13009    command.insert(
13010        "parallel_group_kind".to_string(),
13011        json!(inner.parallel_group_kind),
13012    );
13013    command.insert(
13014        "parallel_group_base_sequence".to_string(),
13015        json!(inner.parallel_group_base_sequence),
13016    );
13017    command.insert(
13018        "parallel_group_size".to_string(),
13019        json!(inner.parallel_group_size),
13020    );
13021    command.insert(
13022        "parallel_group_index".to_string(),
13023        json!(inner.parallel_group_index),
13024    );
13025    if let Some(mode) = &inner.parallel_group_mode {
13026        command.insert("parallel_group_mode".to_string(), json!(mode));
13027    }
13028    if let Some(key) = &inner.selection_member_key {
13029        command.insert("selection_member_key".to_string(), json!(key));
13030    }
13031    if let Some(index) = inner.selection_member_index {
13032        command.insert("selection_member_index".to_string(), json!(index));
13033    }
13034    if let Some(base_sequence) = inner.selection_member_base_sequence {
13035        command.insert(
13036            "selection_member_base_sequence".to_string(),
13037            json!(base_sequence),
13038        );
13039    }
13040    if let Some(size) = inner.selection_member_size {
13041        command.insert("selection_member_size".to_string(), json!(size));
13042    }
13043    if let Some(kind) = &inner.selection_member_kind {
13044        command.insert("selection_member_kind".to_string(), json!(kind));
13045    }
13046    command.insert("parallel_group_path".to_string(), json!(path));
13047}
13048
13049fn ensure_parallel_path_matches(
13050    sequence: u64,
13051    recorded: Option<&[ParallelGroupMetadata]>,
13052    expected: &[ParallelGroupMetadata],
13053) -> Result<()> {
13054    match (recorded, expected.is_empty()) {
13055        (None, true) => Ok(()),
13056        (Some(recorded), false) if recorded == expected => Ok(()),
13057        (None, false) => Err(invalid_recorded_history(
13058            "parallel_group_metadata_missing",
13059            sequence,
13060            &serde_json::to_string(expected).unwrap_or_default(),
13061            "<missing>",
13062            "recorded parallel member is missing its durable group path",
13063        )),
13064        (Some(recorded), true) => Err(invalid_recorded_history(
13065            "parallel_group_shape_mismatch",
13066            sequence,
13067            "sequential command",
13068            &serde_json::to_string(recorded).unwrap_or_default(),
13069            "recorded command belonged to a parallel group but current code schedules it sequentially",
13070        )),
13071        (Some(recorded), false) => Err(invalid_recorded_history(
13072            "parallel_group_shape_mismatch",
13073            sequence,
13074            &serde_json::to_string(recorded).unwrap_or_default(),
13075            &serde_json::to_string(expected).unwrap_or_default(),
13076            "recorded parallel-group identity or path changed during replay",
13077        )),
13078    }
13079}
13080
13081#[derive(Clone, Debug)]
13082enum ParallelShape {
13083    Leaf,
13084    Group(Vec<ParallelShape>),
13085}
13086
13087struct ParallelDescriptor {
13088    operation: ParallelOperation,
13089    offset: usize,
13090    member_path: Vec<usize>,
13091    group_path: Vec<ParallelGroupMetadata>,
13092}
13093
13094fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13095    operations
13096        .iter()
13097        .map(|operation| match operation {
13098            ParallelOperation::Group(children) => parallel_leaf_count(children),
13099            _ => 1,
13100        })
13101        .sum()
13102}
13103
13104fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13105    match operation {
13106        ParallelOperation::Activity { .. } => Some("activity"),
13107        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13108        ParallelOperation::Timer(_) => Some("timer"),
13109        ParallelOperation::Signal(_) => Some("signal"),
13110        ParallelOperation::Condition { .. } => Some("condition"),
13111        ParallelOperation::Group(children) => parallel_group_kind(children),
13112    }
13113}
13114
13115fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13116    let mut kind = None;
13117    for operation in operations {
13118        let Some(operation_kind) = parallel_operation_kind(operation) else {
13119            continue;
13120        };
13121        match kind {
13122            None => kind = Some(operation_kind),
13123            Some(current) if current == operation_kind => {}
13124            Some(_) => return Some("mixed"),
13125        }
13126    }
13127    kind
13128}
13129
13130fn validate_parallel_operations(
13131    operations: &[ParallelOperation],
13132    member_path: &mut Vec<usize>,
13133    root: bool,
13134) -> Result<()> {
13135    let leaves = parallel_leaf_count(operations);
13136    if leaves > MAX_PARALLEL_OPERATIONS {
13137        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13138            reason: "fan_out_limit_exceeded",
13139            member_path: member_path.clone(),
13140            message: format!(
13141                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13142            ),
13143        }));
13144    }
13145    if !root && operations.is_empty() {
13146        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13147            reason: "nested_group_empty",
13148            member_path: member_path.clone(),
13149            message: "a nested group must contain at least one durable leaf".to_string(),
13150        }));
13151    }
13152
13153    for (index, operation) in operations.iter().enumerate() {
13154        member_path.push(index);
13155        match operation {
13156            ParallelOperation::Activity {
13157                options, arguments, ..
13158            } => {
13159                options
13160                    .validate()
13161                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13162                if let Err(error) = arguments {
13163                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13164                        reason: "arguments_invalid",
13165                        member_path: member_path.clone(),
13166                        message: error.to_string(),
13167                    }));
13168                }
13169            }
13170            ParallelOperation::ChildWorkflow {
13171                options, arguments, ..
13172            } => {
13173                validate_parallel_child_options(options)?;
13174                if let Err(error) = arguments {
13175                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13176                        reason: "arguments_invalid",
13177                        member_path: member_path.clone(),
13178                        message: error.to_string(),
13179                    }));
13180                }
13181            }
13182            ParallelOperation::Timer(duration)
13183                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13184            {
13185                return Err(Error::TimerDurationOverflow);
13186            }
13187            ParallelOperation::Timer(_) => {}
13188            ParallelOperation::Signal(signal_name) => {
13189                validate_user_signal_name(signal_name)?;
13190                if signal_name.trim().is_empty() {
13191                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13192                        reason: "signal_name_empty",
13193                        member_path: member_path.clone(),
13194                        message: "signal wait name must not be empty".to_string(),
13195                    }));
13196                }
13197            }
13198            ParallelOperation::Condition { options, .. } => {
13199                options.validate()?;
13200            }
13201            ParallelOperation::Group(children) => {
13202                validate_parallel_operations(children, member_path, false)?;
13203            }
13204        }
13205        member_path.pop();
13206    }
13207    Ok(())
13208}
13209
13210fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13211    if options.task_queue.trim().is_empty() {
13212        return Err(Error::InvalidChildWorkflowOptions(
13213            "task_queue must not be empty".to_string(),
13214        ));
13215    }
13216    for (name, value) in [
13217        (
13218            "execution_timeout_seconds",
13219            options.execution_timeout_seconds,
13220        ),
13221        ("run_timeout_seconds", options.run_timeout_seconds),
13222    ] {
13223        if value == Some(0) {
13224            return Err(Error::InvalidChildWorkflowOptions(format!(
13225                "{name} must be at least 1"
13226            )));
13227        }
13228    }
13229    if options
13230        .retry_policy
13231        .as_ref()
13232        .is_some_and(|policy| policy.max_attempts == Some(0))
13233    {
13234        return Err(Error::InvalidChildWorkflowOptions(
13235            "retry_policy.max_attempts must be at least 1".to_string(),
13236        ));
13237    }
13238    Ok(())
13239}
13240
13241fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13242    ParallelShape::Group(
13243        operations
13244            .iter()
13245            .map(|operation| match operation {
13246                ParallelOperation::Group(children) => parallel_shape(children),
13247                _ => ParallelShape::Leaf,
13248            })
13249            .collect(),
13250    )
13251}
13252
13253fn parallel_descriptors(
13254    operations: Vec<ParallelOperation>,
13255    base_sequence: u64,
13256) -> Result<Vec<ParallelDescriptor>> {
13257    let size = parallel_leaf_count(&operations);
13258    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13259    let mut descriptors = Vec::with_capacity(size);
13260    let mut cursor = 0;
13261
13262    for (index, operation) in operations.into_iter().enumerate() {
13263        match operation {
13264            ParallelOperation::Group(children) => {
13265                let child_base = base_sequence
13266                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13267                    .ok_or(Error::TimerDurationOverflow)?;
13268                for mut descriptor in parallel_descriptors(children, child_base)? {
13269                    let outer_index = cursor + descriptor.offset;
13270                    descriptor.group_path.insert(
13271                        0,
13272                        parallel_group_entry(base_sequence, size, outer_index, kind),
13273                    );
13274                    descriptor.member_path.insert(0, index);
13275                    descriptor.offset = outer_index;
13276                    descriptors.push(descriptor);
13277                }
13278                cursor = descriptors.len();
13279            }
13280            operation => {
13281                descriptors.push(ParallelDescriptor {
13282                    operation,
13283                    offset: cursor,
13284                    member_path: vec![index],
13285                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13286                });
13287                cursor += 1;
13288            }
13289        }
13290    }
13291    Ok(descriptors)
13292}
13293
13294enum ParallelLeafCall {
13295    Activity(ActivityCall),
13296    ChildWorkflow(ChildWorkflowCall),
13297    Timer(TimerCall),
13298    Signal(SignalCall),
13299    Condition(ConditionWaitCall),
13300}
13301
13302fn parallel_leaf_call(
13303    ctx: &WorkflowContext,
13304    operation: ParallelOperation,
13305    parallel_group_path: Vec<ParallelGroupMetadata>,
13306) -> ParallelLeafCall {
13307    match operation {
13308        ParallelOperation::Activity {
13309            activity_type,
13310            options,
13311            arguments,
13312        } => ParallelLeafCall::Activity(ActivityCall {
13313            ctx: ctx.clone(),
13314            activity_type,
13315            options,
13316            worker_session: None,
13317            args: Some(arguments),
13318            scheduled: false,
13319            local: false,
13320            local_result: None,
13321            parallel_group_path,
13322        }),
13323        ParallelOperation::ChildWorkflow {
13324            workflow_type,
13325            options,
13326            arguments,
13327        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13328            ctx: ctx.clone(),
13329            workflow_type,
13330            options,
13331            args: Some(arguments),
13332            scheduled: false,
13333            matched_pending: false,
13334            parallel_group_path,
13335        }),
13336        ParallelOperation::Timer(duration) => {
13337            let delay_seconds = duration
13338                .as_secs()
13339                .checked_add(u64::from(duration.subsec_nanos() > 0));
13340            ParallelLeafCall::Timer(TimerCall {
13341                ctx: ctx.clone(),
13342                delay_seconds,
13343                scheduled: false,
13344                matched_pending: false,
13345                parallel_group_path,
13346            })
13347        }
13348        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
13349            ctx: ctx.clone(),
13350            signal_name,
13351            runtime_reserved_allowed: false,
13352            opened_wait: false,
13353            matched_pending: false,
13354            parallel_group_path,
13355        }),
13356        ParallelOperation::Condition { options, predicate } => {
13357            ParallelLeafCall::Condition(ConditionWaitCall {
13358                ctx: ctx.clone(),
13359                options,
13360                predicate,
13361                occurrence_id: None,
13362                opened_wait: false,
13363                parallel_group_path,
13364            })
13365        }
13366        ParallelOperation::Group(_) => {
13367            unreachable!("parallel descriptors contain only durable leaves")
13368        }
13369    }
13370}
13371
13372impl ParallelLeafCall {
13373    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
13374        match self {
13375            Self::Activity(call) => Pin::new(call)
13376                .poll_avro_value(cx)
13377                .map_ok(ParallelAvroResult::Activity),
13378            Self::ChildWorkflow(call) => Pin::new(call)
13379                .poll_avro_value(cx)
13380                .map_ok(ParallelAvroResult::ChildWorkflow),
13381            Self::Timer(call) => Pin::new(call)
13382                .poll(cx)
13383                .map_ok(|()| ParallelAvroResult::Timer),
13384            Self::Signal(call) => Pin::new(call)
13385                .poll_avro_value(cx)
13386                .map_ok(ParallelAvroResult::Signal),
13387            Self::Condition(call) => Pin::new(call)
13388                .poll(cx)
13389                .map_ok(ParallelAvroResult::Condition),
13390        }
13391    }
13392}
13393
13394struct ParallelLeaf {
13395    call: ParallelLeafCall,
13396    sequence: u64,
13397    member_path: Vec<usize>,
13398    group_path: Vec<ParallelGroupMetadata>,
13399    result: Option<ParallelAvroResult>,
13400}
13401
13402/// Future returned by [`WorkflowContext::parallel`].
13403pub struct ParallelCall {
13404    ctx: WorkflowContext,
13405    operations: Option<Vec<ParallelOperation>>,
13406    shape: Option<ParallelShape>,
13407    leaves: Vec<ParallelLeaf>,
13408    pending_scope_delivery: bool,
13409    worker_session: Option<WorkerSessionOptions>,
13410}
13411
13412impl ParallelCall {
13413    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
13414        Self {
13415            ctx,
13416            operations: Some(operations),
13417            shape: None,
13418            leaves: Vec::new(),
13419            pending_scope_delivery: false,
13420            worker_session: None,
13421        }
13422    }
13423
13424    fn initialize(&mut self) -> Result<()> {
13425        if let Some(session) = &self.worker_session {
13426            session.to_wire()?;
13427        }
13428        let operations = self.operations.take().unwrap_or_default();
13429        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
13430        self.shape = Some(parallel_shape(&operations));
13431        if operations.is_empty() {
13432            return Ok(());
13433        }
13434
13435        let base_sequence = {
13436            let state = self
13437                .ctx
13438                .state
13439                .lock()
13440                .map_err(|_| Error::WorkflowStatePoisoned)?;
13441            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13442                recorded.sequence()
13443            } else {
13444                let last = state
13445                    .recorded_commands
13446                    .last()
13447                    .map(RecordedCommand::sequence)
13448                    .unwrap_or(0);
13449                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13450                    .and_then(|sequence| sequence.checked_add(1))
13451                    .ok_or_else(|| {
13452                        Error::InvalidParallelGroup(ParallelGroupError {
13453                            reason: "sequence_overflow",
13454                            member_path: Vec::new(),
13455                            message: "parallel group sequence identity overflowed u64".to_string(),
13456                        })
13457                    })?
13458            }
13459        };
13460
13461        let descriptors = parallel_descriptors(operations, base_sequence)?;
13462        {
13463            let mut state = self
13464                .ctx
13465                .state
13466                .lock()
13467                .map_err(|_| Error::WorkflowStatePoisoned)?;
13468            let cursor = state.command_cursor;
13469            self.ctx.validate_scope_membership(&mut state, cursor)?;
13470            if state.prepare_parallel_scope_cancellation(&descriptors)? {
13471                self.pending_scope_delivery = true;
13472                return Ok(());
13473            }
13474            state.expand_cancellation_group(&descriptors)?;
13475            state.prepare_group_cancellation(&descriptors)?;
13476        }
13477        self.leaves = descriptors
13478            .into_iter()
13479            .map(|descriptor| {
13480                let mut call = parallel_leaf_call(
13481                    &self.ctx,
13482                    descriptor.operation,
13483                    descriptor.group_path.clone(),
13484                );
13485                if let (Some(session), ParallelLeafCall::Activity(activity)) =
13486                    (&self.worker_session, &mut call)
13487                {
13488                    activity.worker_session = Some(session.clone());
13489                }
13490                ParallelLeaf {
13491                    call,
13492                    sequence: base_sequence + descriptor.offset as u64,
13493                    member_path: descriptor.member_path,
13494                    group_path: descriptor.group_path,
13495                    result: None,
13496                }
13497            })
13498            .collect();
13499        Ok(())
13500    }
13501
13502    fn poll_avro_value(
13503        mut self: Pin<&mut Self>,
13504        cx: &mut TaskContext<'_>,
13505    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
13506        if self.operations.is_some() {
13507            if let Err(error) = self.initialize() {
13508                return Poll::Ready(Err(error));
13509            }
13510        }
13511        if self.pending_scope_delivery {
13512            return Poll::Pending;
13513        }
13514        if self.leaves.is_empty() {
13515            return Poll::Ready(Ok(Vec::new()));
13516        }
13517
13518        let mut failures = Vec::new();
13519        let mut pending = false;
13520        for (index, leaf) in self.leaves.iter_mut().enumerate() {
13521            if leaf.result.is_some() {
13522                continue;
13523            }
13524            match leaf.call.poll_avro_value(cx) {
13525                Poll::Ready(Ok(result)) => leaf.result = Some(result),
13526                Poll::Ready(Err(error)) => failures.push((index, error)),
13527                Poll::Pending => pending = true,
13528            }
13529        }
13530
13531        if !failures.is_empty() {
13532            if let Some(position) = failures
13533                .iter()
13534                .position(|(_, error)| workflow_task_integrity_error(error))
13535            {
13536                return Poll::Ready(Err(failures.remove(position).1));
13537            }
13538            if self
13539                .ctx
13540                .state
13541                .lock()
13542                .map_err(|_| Error::WorkflowStatePoisoned)?
13543                .cancellation_delivery_intent
13544                .is_some()
13545            {
13546                return Poll::Pending;
13547            }
13548            if let Some(position) = failures
13549                .iter()
13550                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
13551            {
13552                return Poll::Ready(Err(failures.remove(position).1));
13553            }
13554            failures.sort_by_key(|(index, _)| *index);
13555            let (failed_index, cause) = failures.remove(0);
13556            let failed = &self.leaves[failed_index];
13557            let completed = self
13558                .leaves
13559                .iter()
13560                .filter_map(|leaf| {
13561                    leaf.result
13562                        .clone()
13563                        .and_then(|result| result.into_json_result().ok())
13564                        .map(|result| ParallelCompletion {
13565                            member_path: leaf.member_path.clone(),
13566                            result,
13567                        })
13568                })
13569                .collect();
13570            let group_id = failed
13571                .group_path
13572                .first()
13573                .map(|entry| entry.parallel_group_id.clone())
13574                .unwrap_or_default();
13575            let sequences = self
13576                .leaves
13577                .iter()
13578                .map(|leaf| leaf.sequence)
13579                .collect::<Vec<_>>();
13580            self.ctx
13581                .state
13582                .lock()
13583                .map_err(|_| Error::WorkflowStatePoisoned)?
13584                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
13585            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
13586                group_id,
13587                member_path: failed.member_path.clone(),
13588                group_path: failed.group_path.clone(),
13589                completed,
13590                cause: Box::new(cause),
13591            })));
13592        }
13593        if pending
13594            || self
13595                .ctx
13596                .state
13597                .lock()
13598                .map_err(|_| Error::WorkflowStatePoisoned)?
13599                .cancellation_delivery_intent
13600                .is_some()
13601        {
13602            return Poll::Pending;
13603        }
13604
13605        let mut flat_results = self
13606            .leaves
13607            .iter_mut()
13608            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
13609            .collect::<Vec<_>>()
13610            .into_iter();
13611        let results = parallel_results_for_shape(
13612            self.shape.as_ref().expect("initialized parallel shape"),
13613            &mut flat_results,
13614        );
13615        let sequences = self
13616            .leaves
13617            .iter()
13618            .map(|leaf| leaf.sequence)
13619            .collect::<Vec<_>>();
13620        self.ctx
13621            .state
13622            .lock()
13623            .map_err(|_| Error::WorkflowStatePoisoned)?
13624            .advance_cancellation_sequences(&sequences, None);
13625        Poll::Ready(Ok(match results {
13626            ParallelAvroResult::Group(results) => results,
13627            ParallelAvroResult::Activity(_)
13628            | ParallelAvroResult::ChildWorkflow(_)
13629            | ParallelAvroResult::Timer
13630            | ParallelAvroResult::Signal(_)
13631            | ParallelAvroResult::Condition(_) => {
13632                unreachable!("root parallel shape is a group")
13633            }
13634        }))
13635    }
13636}
13637
13638fn parallel_results_for_shape(
13639    shape: &ParallelShape,
13640    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13641) -> ParallelAvroResult {
13642    match shape {
13643        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13644        ParallelShape::Group(children) => ParallelAvroResult::Group(
13645            children
13646                .iter()
13647                .map(|child| parallel_results_for_shape(child, flat_results))
13648                .collect(),
13649        ),
13650    }
13651}
13652
13653impl Future for ParallelCall {
13654    type Output = Result<Vec<ParallelResult>>;
13655
13656    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13657        self.poll_avro_value(cx)
13658            .map_ok(|results| {
13659                results
13660                    .into_iter()
13661                    .map(ParallelAvroResult::into_json_result)
13662                    .collect::<Result<Vec<_>>>()
13663            })
13664            .map_ok(|result| result)
13665            .flatten_result()
13666    }
13667}
13668
13669#[derive(Clone, Debug)]
13670struct SelectionMemberPlan {
13671    key: SelectionKey,
13672    index: usize,
13673    base_sequence: u64,
13674    size: usize,
13675    kind: String,
13676    shape: ParallelShape,
13677    leaf_start: usize,
13678}
13679
13680fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13681    match operation {
13682        ParallelOperation::Activity { .. } => "activity",
13683        ParallelOperation::ChildWorkflow { .. } => "child",
13684        ParallelOperation::Timer(_) => "timer",
13685        ParallelOperation::Signal(_) => "signal",
13686        ParallelOperation::Condition { .. } => "condition",
13687        ParallelOperation::Group(_) => "group",
13688    }
13689}
13690
13691fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13692    match operation {
13693        ParallelOperation::Group(children) => parallel_shape(children),
13694        _ => ParallelShape::Leaf,
13695    }
13696}
13697
13698fn selection_descriptors(
13699    operations: Vec<(SelectionKey, ParallelOperation)>,
13700    base_sequence: u64,
13701) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13702    if operations.is_empty() {
13703        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13704            reason: "selection_empty",
13705            member_path: Vec::new(),
13706            message: "durable selection requires at least one operation".to_string(),
13707        }));
13708    }
13709    let operation_refs = operations
13710        .iter()
13711        .map(|(_, operation)| operation)
13712        .collect::<Vec<_>>();
13713    let total_size = operation_refs
13714        .iter()
13715        .map(|operation| match operation {
13716            ParallelOperation::Group(children) => parallel_leaf_count(children),
13717            _ => 1,
13718        })
13719        .sum::<usize>();
13720    if total_size > MAX_PARALLEL_OPERATIONS {
13721        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13722            reason: "fan_out_limit_exceeded",
13723            member_path: Vec::new(),
13724            message: format!(
13725                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13726            ),
13727        }));
13728    }
13729    let group_kind = {
13730        let mut kind = None;
13731        for operation in &operation_refs {
13732            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13733            match kind {
13734                None => kind = Some(operation_kind),
13735                Some(current) if current == operation_kind => {}
13736                Some(_) => {
13737                    kind = Some("mixed");
13738                    break;
13739                }
13740            }
13741        }
13742        kind.unwrap_or("mixed")
13743    };
13744
13745    let mut descriptors = Vec::with_capacity(total_size);
13746    let mut members = Vec::with_capacity(operations.len());
13747    let mut cursor = 0usize;
13748    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13749    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13750        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13751            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13752                reason: "selection_key_invalid",
13753                member_path: vec![member_index],
13754                message: "selection member keys must be non-empty strings or non-negative integers"
13755                    .to_string(),
13756            }));
13757        }
13758        if seen_keys.contains(&key) {
13759            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13760                reason: "selection_key_duplicate",
13761                member_path: vec![member_index],
13762                message: format!("selection member key {key:?} is duplicated"),
13763            }));
13764        }
13765        seen_keys.push(key.clone());
13766        let member_size = match &operation {
13767            ParallelOperation::Group(children) => parallel_leaf_count(children),
13768            _ => 1,
13769        };
13770        if member_size == 0 {
13771            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13772                reason: "selection_member_empty",
13773                member_path: vec![member_index],
13774                message: "a selection member must contain at least one durable leaf".to_string(),
13775            }));
13776        }
13777        let member_base = base_sequence
13778            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13779            .ok_or(Error::TimerDurationOverflow)?;
13780        let member_kind = selection_operation_kind(&operation).to_string();
13781        let member_shape = selection_operation_shape(&operation);
13782        let leaf_start = descriptors.len();
13783        match operation {
13784            ParallelOperation::Group(children) => {
13785                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13786                for mut descriptor in parallel_descriptors(children, member_base)? {
13787                    let flat_index = cursor + descriptor.offset;
13788                    descriptor.group_path.insert(
13789                        0,
13790                        selection_group_entry(
13791                            base_sequence,
13792                            total_size,
13793                            flat_index,
13794                            group_kind,
13795                            &SelectionMemberMetadata {
13796                                key: key.clone(),
13797                                index: member_index,
13798                                base_sequence: member_base,
13799                                size: member_size,
13800                                kind: member_kind.clone(),
13801                            },
13802                        ),
13803                    );
13804                    descriptor.member_path.insert(0, member_index);
13805                    descriptor.offset = flat_index;
13806                    descriptors.push(descriptor);
13807                }
13808            }
13809            operation => {
13810                validate_parallel_operations(
13811                    std::slice::from_ref(&operation),
13812                    &mut Vec::new(),
13813                    true,
13814                )?;
13815                descriptors.push(ParallelDescriptor {
13816                    operation,
13817                    offset: cursor,
13818                    member_path: vec![member_index],
13819                    group_path: vec![selection_group_entry(
13820                        base_sequence,
13821                        total_size,
13822                        cursor,
13823                        group_kind,
13824                        &SelectionMemberMetadata {
13825                            key: key.clone(),
13826                            index: member_index,
13827                            base_sequence: member_base,
13828                            size: member_size,
13829                            kind: member_kind.clone(),
13830                        },
13831                    )],
13832                });
13833            }
13834        }
13835        members.push(SelectionMemberPlan {
13836            key,
13837            index: member_index,
13838            base_sequence: member_base,
13839            size: member_size,
13840            kind: member_kind,
13841            shape: member_shape,
13842            leaf_start,
13843        });
13844        cursor += member_size;
13845    }
13846    Ok((descriptors, members))
13847}
13848
13849struct SelectionLeaf {
13850    call: ParallelLeafCall,
13851    outcome: Option<Result<ParallelAvroResult>>,
13852}
13853
13854/// Stable reference to one member of a durable selection group.
13855#[derive(Clone)]
13856pub struct DurableOperationHandle {
13857    ctx: WorkflowContext,
13858    pub key: SelectionKey,
13859    pub index: usize,
13860    pub kind: String,
13861    pub identity: String,
13862    pub base_sequence: u64,
13863    pub size: usize,
13864    pub selection_group_id: String,
13865    shape: ParallelShape,
13866}
13867
13868impl std::fmt::Debug for DurableOperationHandle {
13869    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13870        formatter
13871            .debug_struct("DurableOperationHandle")
13872            .field("key", &self.key)
13873            .field("index", &self.index)
13874            .field("kind", &self.kind)
13875            .field("identity", &self.identity)
13876            .field("base_sequence", &self.base_sequence)
13877            .field("size", &self.size)
13878            .field("selection_group_id", &self.selection_group_id)
13879            .finish()
13880    }
13881}
13882
13883impl DurableOperationHandle {
13884    /// Await this member after another member has already won the selection.
13885    pub fn await_result(&self) -> DurableOperationAwaitCall {
13886        DurableOperationAwaitCall {
13887            handle: self.clone(),
13888        }
13889    }
13890
13891    /// Request cancellation without affecting siblings. The future resolves
13892    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13893    /// beat a concurrently committed terminal result.
13894    pub fn cancel(&self) -> CancelDurableOperationCall {
13895        CancelDurableOperationCall {
13896            handle: self.clone(),
13897            emitted: false,
13898        }
13899    }
13900}
13901
13902/// The one winner committed for a durable selection group.
13903#[derive(Debug)]
13904pub struct SelectionResult {
13905    pub key: SelectionKey,
13906    pub index: usize,
13907    pub kind: String,
13908    pub identity: String,
13909    pub value: Option<ParallelResult>,
13910    pub failure: Option<Error>,
13911    pub winner: DurableOperationHandle,
13912    pub handles: Vec<DurableOperationHandle>,
13913}
13914
13915impl SelectionResult {
13916    pub fn succeeded(&self) -> bool {
13917        self.failure.is_none()
13918    }
13919
13920    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13921        self.handles.iter().find(|handle| &handle.key == key)
13922    }
13923
13924    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13925        self.handles
13926            .iter()
13927            .filter(|handle| handle.index != self.index)
13928            .collect()
13929    }
13930
13931    pub fn into_result(self) -> Result<ParallelResult> {
13932        match (self.value, self.failure) {
13933            (Some(value), None) => Ok(value),
13934            (_, Some(error)) => Err(error),
13935            _ => Err(Error::WorkerLoop(
13936                "selection result contained neither a value nor a failure".to_string(),
13937            )),
13938        }
13939    }
13940}
13941
13942/// Future returned by [`WorkflowContext::select`].
13943pub struct SelectCall {
13944    ctx: WorkflowContext,
13945    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13946    members: Vec<SelectionMemberPlan>,
13947    leaves: Vec<SelectionLeaf>,
13948    group_id: Option<String>,
13949}
13950
13951impl SelectCall {
13952    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13953        Self {
13954            ctx,
13955            operations: Some(operations),
13956            members: Vec::new(),
13957            leaves: Vec::new(),
13958            group_id: None,
13959        }
13960    }
13961
13962    fn initialize(&mut self) -> Result<()> {
13963        let operations = self.operations.take().unwrap_or_default();
13964        let base_sequence = {
13965            let state = self
13966                .ctx
13967                .state
13968                .lock()
13969                .map_err(|_| Error::WorkflowStatePoisoned)?;
13970            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13971                state.recorded_commands.get(state.command_cursor)
13972            {
13973                *sequence
13974            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13975            {
13976                marker.selection_group_base_sequence
13977            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13978                recorded.sequence()
13979            } else {
13980                let last = state
13981                    .recorded_commands
13982                    .last()
13983                    .map(RecordedCommand::sequence)
13984                    .unwrap_or(0);
13985                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13986                    .and_then(|sequence| sequence.checked_add(1))
13987                    .ok_or(Error::TimerDurationOverflow)?
13988            }
13989        };
13990        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13991        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13992        {
13993            let mut state = self
13994                .ctx
13995                .state
13996                .lock()
13997                .map_err(|_| Error::WorkflowStatePoisoned)?;
13998            state.expand_cancellation_group(&descriptors)?;
13999            state.prepare_group_cancellation(&descriptors)?;
14000        }
14001        self.leaves = descriptors
14002            .into_iter()
14003            .map(|descriptor| SelectionLeaf {
14004                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
14005                outcome: None,
14006            })
14007            .collect();
14008        self.members = members;
14009        self.group_id = Some(group_id);
14010        Ok(())
14011    }
14012}
14013
14014impl Future for SelectCall {
14015    type Output = Result<SelectionResult>;
14016
14017    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14018        if self.operations.is_some() {
14019            if let Err(error) = self.initialize() {
14020                return Poll::Ready(Err(error));
14021            }
14022        }
14023
14024        for leaf in &mut self.leaves {
14025            if leaf.outcome.is_some() {
14026                continue;
14027            }
14028            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14029                if outcome
14030                    .as_ref()
14031                    .err()
14032                    .is_some_and(workflow_task_integrity_error)
14033                {
14034                    return Poll::Ready(outcome.map(|_| unreachable!()));
14035                }
14036                leaf.outcome = Some(outcome);
14037            }
14038        }
14039
14040        if self
14041            .ctx
14042            .state
14043            .lock()
14044            .map_err(|_| Error::WorkflowStatePoisoned)?
14045            .cancellation_delivery_intent
14046            .is_some()
14047        {
14048            return Poll::Pending;
14049        }
14050
14051        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14052            matches!(
14053                leaf.outcome,
14054                Some(Err(Error::CooperativeCancellationRequested(_)))
14055            )
14056        }) {
14057            return Poll::Ready(
14058                leaf.outcome
14059                    .take()
14060                    .expect("matched cancellation")
14061                    .map(|_| unreachable!()),
14062            );
14063        }
14064
14065        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14066        let selection_member_range = self
14067            .members
14068            .first()
14069            .map(|member| member.base_sequence)
14070            .zip(self.leaves.len().try_into().ok())
14071            .map(|(base_sequence, size): (u64, u64)| {
14072                base_sequence..base_sequence.saturating_add(size)
14073            });
14074        let marker = {
14075            let mut state = match self.ctx.state.lock() {
14076                Ok(state) => state,
14077                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14078            };
14079            let marker = state
14080                .selection_markers
14081                .get(state.selection_marker_cursor)
14082                .cloned();
14083            if marker.is_none()
14084                && all_members_terminal
14085                && selection_member_range.as_ref().is_some_and(|member_range| {
14086                    state
14087                        .recorded_commands
14088                        .iter()
14089                        .any(|command| member_range.contains(&command.sequence()))
14090                })
14091            {
14092                // Terminal member history can be committed before the server's
14093                // SelectionResolved marker becomes visible to this task. That
14094                // marker is the durable barrier the selection is still waiting
14095                // on, so an otherwise commandless replay remains legitimately
14096                // pending instead of failing as an untracked yield.
14097                state.matched_recorded_pending = true;
14098            }
14099            marker
14100        };
14101        let Some(marker) = marker else {
14102            return Poll::Pending;
14103        };
14104        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14105            || marker.selection_group_size != self.leaves.len()
14106            || self.members.first().map(|member| member.base_sequence)
14107                != Some(marker.selection_group_base_sequence)
14108        {
14109            return Poll::Ready(Err(invalid_recorded_history(
14110                "selection_group_shape_mismatch",
14111                marker.selection_group_base_sequence,
14112                self.group_id
14113                    .as_deref()
14114                    .unwrap_or("initialized selection group"),
14115                &marker.selection_group_id,
14116                "recorded selection group differs from current workflow code",
14117            )));
14118        }
14119        let Some(member_position) = self.members.iter().position(|member| {
14120            member.key == marker.member_key
14121                && member.index == marker.member_index
14122                && member.base_sequence == marker.member_base_sequence
14123                && member.size == marker.member_size
14124                && member.kind == marker.operation_kind
14125        }) else {
14126            return Poll::Ready(Err(invalid_recorded_history(
14127                "selection_member_shape_mismatch",
14128                marker.member_base_sequence,
14129                "winner member matching current workflow code",
14130                &format!("{:?}", marker.member_key),
14131                "recorded selection winner differs from the authored member identity",
14132            )));
14133        };
14134        let member = self.members[member_position].clone();
14135        let (handles, resolution_sequence) = {
14136            let mut state = match self.ctx.state.lock() {
14137                Ok(state) => state,
14138                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14139            };
14140            let identities = self
14141                .members
14142                .iter()
14143                .map(|candidate| {
14144                    selection_operation_identity(
14145                        &state,
14146                        &candidate.kind,
14147                        candidate.base_sequence,
14148                        candidate.size,
14149                    )
14150                })
14151                .collect::<Vec<_>>();
14152            if let Some((position, missing)) = identities
14153                .iter()
14154                .enumerate()
14155                .find(|(_, identity)| identity.is_empty())
14156                .map(|(position, identity)| (position, identity.clone()))
14157            {
14158                let candidate = &self.members[position];
14159                return Poll::Ready(Err(invalid_recorded_history(
14160                    "selection_operation_identity_missing",
14161                    candidate.base_sequence,
14162                    &format!(
14163                        "durable {} resource identity from scheduled/open history",
14164                        candidate.kind
14165                    ),
14166                    &missing,
14167                    "selection member history is missing its canonical durable identity",
14168                )));
14169            }
14170            let expected_winner_identity = &identities[member_position];
14171            let resolution_sequence = match validated_selection_resolution_sequence(
14172                &state,
14173                &marker,
14174                &member,
14175                expected_winner_identity,
14176            ) {
14177                Ok(sequence) => sequence,
14178                Err(error) => return Poll::Ready(Err(error)),
14179            };
14180            let handles = self
14181                .members
14182                .iter()
14183                .zip(identities)
14184                .map(|(member, identity)| DurableOperationHandle {
14185                    ctx: self.ctx.clone(),
14186                    key: member.key.clone(),
14187                    index: member.index,
14188                    kind: member.kind.clone(),
14189                    identity,
14190                    base_sequence: member.base_sequence,
14191                    size: member.size,
14192                    selection_group_id: marker.selection_group_id.clone(),
14193                    shape: member.shape.clone(),
14194                })
14195                .collect::<Vec<_>>();
14196            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14197                return Poll::Ready(Err(error));
14198            }
14199            state.selection_marker_cursor += 1;
14200            (handles, resolution_sequence)
14201        };
14202
14203        let mut winner_failure = None;
14204        let mut flat_results = Vec::with_capacity(member.size);
14205        if marker.outcome == "failed" {
14206            let resolution_offset = match resolution_sequence
14207                .checked_sub(member.base_sequence)
14208                .and_then(|offset| usize::try_from(offset).ok())
14209            {
14210                Some(offset) if offset < member.size => offset,
14211                _ => {
14212                    return Poll::Ready(Err(invalid_recorded_history(
14213                        "selection_resolution_event_mismatch",
14214                        member.base_sequence,
14215                        "failure event within selected member bounds",
14216                        &resolution_sequence.to_string(),
14217                        "selection failure event is outside the authored member",
14218                    )))
14219                }
14220            };
14221            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14222            match leaf.outcome.take() {
14223                Some(Err(error)) => winner_failure = Some(error),
14224                _ => {
14225                    return Poll::Ready(Err(invalid_recorded_history(
14226                        "selection_winner_outcome_mismatch",
14227                        member.base_sequence,
14228                        "exact failed terminal history referenced by SelectionResolved",
14229                        "missing or successful resolution event",
14230                        "selection winner marker disagrees with terminal operation history",
14231                    )))
14232                }
14233            }
14234        } else {
14235            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14236                match leaf.outcome.take() {
14237                    Some(Ok(result)) => flat_results.push(result),
14238                    Some(Err(_)) => {
14239                        return Poll::Ready(Err(invalid_recorded_history(
14240                            "selection_winner_outcome_mismatch",
14241                            member.base_sequence,
14242                            "fully completed nested selection member",
14243                            "failed durable leaf",
14244                            "completed selection winner contains a failed leaf",
14245                        )))
14246                    }
14247                    None => {
14248                        return Poll::Ready(Err(invalid_recorded_history(
14249                            "selection_winner_unresolved",
14250                            member.base_sequence,
14251                            "terminal history for every completed winner leaf",
14252                            "pending member history",
14253                            "completed SelectionResolved member has an unfinished durable barrier",
14254                        )))
14255                    }
14256                }
14257            }
14258        }
14259        let value = if winner_failure.is_none() {
14260            let mut flat_results = flat_results.into_iter();
14261            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14262            match value.into_json_result() {
14263                Ok(value) => Some(value),
14264                Err(error) => return Poll::Ready(Err(error)),
14265            }
14266        } else {
14267            None
14268        };
14269        let winner = handles[member_position].clone();
14270        self.ctx
14271            .state
14272            .lock()
14273            .map_err(|_| Error::WorkflowStatePoisoned)?
14274            .advance_cancellation_selection(&marker.selection_group_id);
14275        Poll::Ready(Ok(SelectionResult {
14276            key: winner.key.clone(),
14277            index: winner.index,
14278            kind: winner.kind.clone(),
14279            identity: winner.identity.clone(),
14280            value,
14281            failure: winner_failure,
14282            winner,
14283            handles,
14284        }))
14285    }
14286}
14287
14288fn selection_operation_identity(
14289    state: &WorkflowState,
14290    kind: &str,
14291    base_sequence: u64,
14292    size: usize,
14293) -> String {
14294    if kind == "group" {
14295        return format!("group:{base_sequence}:{size}");
14296    }
14297    let fields: &[&str] = match kind {
14298        "activity" => &["activity_execution_id"],
14299        "child" => &["child_workflow_run_id"],
14300        "timer" => &["timer_id"],
14301        "signal" => &["signal_wait_id"],
14302        "condition" => &["condition_wait_id"],
14303        _ => &[],
14304    };
14305    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14306        for event in state
14307            .history_events
14308            .iter()
14309            .filter(|event| durable_event_sequence(event) == Some(sequence))
14310        {
14311            for field in fields {
14312                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14313                    if !identity.is_empty() {
14314                        return identity.to_string();
14315                    }
14316                }
14317            }
14318        }
14319    }
14320    String::new()
14321}
14322
14323fn validated_selection_resolution_sequence(
14324    state: &WorkflowState,
14325    marker: &SelectionMarker,
14326    member: &SelectionMemberPlan,
14327    expected_identity: &str,
14328) -> Result<u64> {
14329    if expected_identity.is_empty() {
14330        return Err(invalid_recorded_history(
14331            "selection_operation_identity_missing",
14332            member.base_sequence,
14333            &format!(
14334                "durable {} resource identity from scheduled/open history",
14335                member.kind
14336            ),
14337            "missing operation identity",
14338            "selection member history is missing its canonical durable identity",
14339        ));
14340    }
14341    if marker.operation_identity != expected_identity {
14342        return Err(invalid_recorded_history(
14343            "selection_operation_identity_mismatch",
14344            member.base_sequence,
14345            expected_identity,
14346            &marker.operation_identity,
14347            "selection winner identity does not match durable scheduled/open history",
14348        ));
14349    }
14350
14351    let failure_types = [
14352        "ActivityFailed",
14353        "ActivityCancelled",
14354        "ActivityTimedOut",
14355        "ChildRunFailed",
14356        "ChildRunCancelled",
14357        "ChildRunTerminated",
14358    ];
14359    let success_types = [
14360        "ActivityCompleted",
14361        "ChildRunCompleted",
14362        "TimerFired",
14363        "SignalApplied",
14364        "ConditionWaitSatisfied",
14365        "ConditionWaitTimedOut",
14366    ];
14367    let terminal_types: &[&str] = if marker.outcome == "failed" {
14368        &failure_types
14369    } else {
14370        &success_types
14371    };
14372    let mut candidates = Vec::new();
14373    let member_commands = (member.base_sequence
14374        ..member.base_sequence.saturating_add(member.size as u64))
14375        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
14376        .map(|command| (command.sequence(), command))
14377        .collect::<BTreeMap<_, _>>();
14378    let mut resolved_conditions = BTreeSet::new();
14379    for event in state.history_events.iter() {
14380        let Some(sequence) = durable_event_sequence(event) else {
14381            continue;
14382        };
14383        let Some(command) = member_commands.get(&sequence) else {
14384            continue;
14385        };
14386        if !terminal_types.contains(&event.event_type.as_str()) {
14387            continue;
14388        }
14389        if matches!(command, RecordedCommand::ConditionWait { .. }) {
14390            if !matches!(
14391                event.event_type.as_str(),
14392                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
14393            ) && !(event.event_type == "TimerFired"
14394                && event.payload.get("timer_kind").and_then(Value::as_str)
14395                    == Some("condition_timeout"))
14396            {
14397                continue;
14398            }
14399            if !resolved_conditions.insert(sequence) {
14400                continue;
14401            }
14402        }
14403        let event_id = event
14404            .raw
14405            .get("id")
14406            .or_else(|| event.raw.get("event_id"))
14407            .and_then(Value::as_str)
14408            .filter(|value| !value.is_empty())
14409            .ok_or_else(|| {
14410                invalid_recorded_history(
14411                    "selection_resolution_event_id_missing",
14412                    member.base_sequence,
14413                    "terminal selection history with a durable event id",
14414                    &event.payload.to_string(),
14415                    "selection terminal history cannot be bound to its winner marker",
14416                )
14417            })?;
14418        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
14419    }
14420    let resolution = if marker.outcome == "failed" {
14421        candidates.first()
14422    } else {
14423        candidates.last()
14424    };
14425    let Some((event_id, event_type, sequence)) = resolution else {
14426        return Err(invalid_recorded_history(
14427            "selection_resolution_event_missing",
14428            member.base_sequence,
14429            "terminal history for the selected member",
14430            &format!("{:?}", marker.member_key),
14431            "selection winner marker has no matching durable terminal event",
14432        ));
14433    };
14434    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
14435        return Err(invalid_recorded_history(
14436            "selection_resolution_event_mismatch",
14437            member.base_sequence,
14438            &format!("{event_type}:{event_id}"),
14439            &format!(
14440                "{}:{}",
14441                marker.resolution_event_type, marker.resolution_event_id
14442            ),
14443            "selection winner marker does not reference the event that made its member terminal",
14444        ));
14445    }
14446    Ok(*sequence)
14447}
14448
14449fn selection_member_recorded_command(
14450    state: &WorkflowState,
14451    authored_sequence: u64,
14452) -> Option<&RecordedCommand> {
14453    let original = state
14454        .recorded_commands
14455        .iter()
14456        .find(|command| command.sequence() == authored_sequence)?;
14457    let RecordedCommand::ConditionWait {
14458        occurrence_id,
14459        parallel_group_path: Some(_),
14460        ..
14461    } = original
14462    else {
14463        return Some(original);
14464    };
14465    // Decoding proves each physical reopen has the same authored identity and
14466    // group path after a satisfied predecessor. Only its latest wait can make
14467    // this logical member terminal.
14468    state
14469        .recorded_commands
14470        .iter()
14471        .filter(|command| {
14472            matches!(command, RecordedCommand::ConditionWait {
14473                occurrence_id: candidate, ..
14474            } if candidate == occurrence_id)
14475        })
14476        .max_by_key(|command| command.sequence())
14477}
14478
14479fn recorded_selection_member_outcome(
14480    state: &WorkflowState,
14481    handle: &DurableOperationHandle,
14482) -> Result<Option<ParallelResult>> {
14483    for event in state.history_events.iter() {
14484        let Some(sequence) = durable_event_sequence(event) else {
14485            continue;
14486        };
14487        if sequence < handle.base_sequence
14488            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
14489            || !matches!(
14490                event.event_type.as_str(),
14491                "ActivityFailed"
14492                    | "ActivityCancelled"
14493                    | "ActivityTimedOut"
14494                    | "ChildRunFailed"
14495                    | "ChildRunCancelled"
14496                    | "ChildRunTerminated"
14497            )
14498        {
14499            continue;
14500        }
14501        let Some(command) = state
14502            .recorded_commands
14503            .iter()
14504            .find(|command| command.sequence() == sequence)
14505        else {
14506            continue;
14507        };
14508        match command {
14509            RecordedCommand::Activity {
14510                outcome: Some(Err(failure)),
14511                ..
14512            } => return Err(Error::ActivityFailed(failure.clone())),
14513            RecordedCommand::ChildWorkflow {
14514                outcome: Some(Err(failure)),
14515                ..
14516            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
14517            _ => {}
14518        }
14519    }
14520
14521    let mut results = Vec::with_capacity(handle.size);
14522    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14523        let Some(command) = selection_member_recorded_command(state, sequence) else {
14524            return Ok(None);
14525        };
14526        let result = match command {
14527            RecordedCommand::Activity { outcome, .. } => match outcome {
14528                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
14529                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
14530                None => return Ok(None),
14531            },
14532            RecordedCommand::Timer { fired, .. } => {
14533                if !fired {
14534                    return Ok(None);
14535                }
14536                ParallelAvroResult::Timer
14537            }
14538            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
14539                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
14540                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
14541                None => return Ok(None),
14542            },
14543            RecordedCommand::SignalWait { value, .. } => match value {
14544                Some(value) => ParallelAvroResult::Signal(value.clone()),
14545                None => return Ok(None),
14546            },
14547            RecordedCommand::ConditionWait { result, .. } => match result {
14548                Some(result) => ParallelAvroResult::Condition(*result),
14549                None => return Ok(None),
14550            },
14551            other => {
14552                return Err(command_mismatch(
14553                    other,
14554                    format!("selected {} member", handle.kind),
14555                ))
14556            }
14557        };
14558        results.push(result);
14559    }
14560    let mut results = results.into_iter();
14561    parallel_results_for_shape(&handle.shape, &mut results)
14562        .into_json_result()
14563        .map(Some)
14564}
14565
14566fn recorded_selection_member_is_terminal(
14567    state: &WorkflowState,
14568    handle: &DurableOperationHandle,
14569) -> bool {
14570    let mut completed = 0usize;
14571    let mut all_completed = true;
14572    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14573        let Some(command) = selection_member_recorded_command(state, sequence) else {
14574            all_completed = false;
14575            continue;
14576        };
14577        let terminal = match command {
14578            RecordedCommand::Activity {
14579                outcome: Some(Err(_)),
14580                ..
14581            }
14582            | RecordedCommand::ChildWorkflow {
14583                outcome: Some(Err(_)),
14584                ..
14585            } => return true,
14586            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
14587            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
14588            RecordedCommand::Timer { fired, .. } => *fired,
14589            RecordedCommand::SignalWait { value, .. } => value.is_some(),
14590            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
14591            RecordedCommand::SearchAttributes { .. }
14592            | RecordedCommand::CancellationScope { .. }
14593            | RecordedCommand::SideEffect { .. }
14594            | RecordedCommand::VersionMarker { .. }
14595            | RecordedCommand::Memo { .. }
14596            | RecordedCommand::CancellationBoundary { .. }
14597            | RecordedCommand::CancellationGroup { .. } => false,
14598            RecordedCommand::ServiceOperation { .. } => false,
14599        };
14600        if !terminal {
14601            all_completed = false;
14602            continue;
14603        }
14604        completed += 1;
14605    }
14606    all_completed && completed == handle.size
14607}
14608
14609fn selection_cancellation_for_handle(
14610    state: &WorkflowState,
14611    handle: &DurableOperationHandle,
14612) -> Result<bool> {
14613    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
14614        recorded.selection_group_id == handle.selection_group_id
14615            && recorded.member_base_sequence == handle.base_sequence
14616    }) else {
14617        return Ok(false);
14618    };
14619    validate_selection_cancellation_marker(marker, handle)?;
14620    Ok(true)
14621}
14622
14623fn validate_selection_cancellations_for_handles(
14624    state: &WorkflowState,
14625    handles: &[DurableOperationHandle],
14626) -> Result<()> {
14627    let Some(group_id) = handles
14628        .first()
14629        .map(|handle| handle.selection_group_id.as_str())
14630    else {
14631        return Ok(());
14632    };
14633    for marker in state
14634        .cancelled_selection_members
14635        .iter()
14636        .filter(|marker| marker.selection_group_id == group_id)
14637    {
14638        let Some(handle) = handles
14639            .iter()
14640            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14641        else {
14642            return Err(invalid_recorded_history(
14643                "selection_cancellation_member_mismatch",
14644                marker.member_base_sequence,
14645                "SelectionOperationCancelled matching an authored selection handle",
14646                &format!("{marker:?}"),
14647                "selection cancellation member base does not name an authored member",
14648            ));
14649        };
14650        validate_selection_cancellation_marker(marker, handle)?;
14651    }
14652    Ok(())
14653}
14654
14655fn validate_selection_cancellation_marker(
14656    marker: &SelectionCancellation,
14657    handle: &DurableOperationHandle,
14658) -> Result<()> {
14659    if marker.selection_group_id != handle.selection_group_id
14660        || marker.member_key != handle.key
14661        || marker.member_index != handle.index
14662        || marker.member_base_sequence != handle.base_sequence
14663        || marker.member_size != handle.size
14664        || marker.operation_kind != handle.kind
14665        || marker.operation_identity != handle.identity
14666    {
14667        return Err(invalid_recorded_history(
14668            "selection_cancellation_member_mismatch",
14669            handle.base_sequence,
14670            "SelectionOperationCancelled matching the authored selection handle",
14671            &format!("{marker:?}"),
14672            "selection cancellation history targets different authored member metadata",
14673        ));
14674    }
14675    Ok(())
14676}
14677
14678/// Future returned by [`DurableOperationHandle::await_result`].
14679pub struct DurableOperationAwaitCall {
14680    handle: DurableOperationHandle,
14681}
14682
14683impl Future for DurableOperationAwaitCall {
14684    type Output = Result<ParallelResult>;
14685
14686    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14687        let mut state = match self.handle.ctx.state.lock() {
14688            Ok(state) => state,
14689            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14690        };
14691        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14692            return Poll::Ready(Err(error));
14693        }
14694        match state.prepare_selection_handle_cancellation(&self.handle) {
14695            Ok(true) => return Poll::Pending,
14696            Ok(false) => {}
14697            Err(error) => return Poll::Ready(Err(error)),
14698        }
14699        match selection_cancellation_for_handle(&state, &self.handle) {
14700            Err(error) => return Poll::Ready(Err(error)),
14701            Ok(false) => {}
14702            Ok(true) => {
14703                state.advance_cancellation_receipt(
14704                    &self.handle.selection_group_id,
14705                    self.handle.base_sequence,
14706                );
14707                return Poll::Ready(Err(Error::DurableOperationCancelled(
14708                    DurableOperationCancelled {
14709                        selection_group_id: self.handle.selection_group_id.clone(),
14710                        member_key: self.handle.key.clone(),
14711                        member_index: self.handle.index,
14712                        operation_kind: self.handle.kind.clone(),
14713                        operation_identity: self.handle.identity.clone(),
14714                    },
14715                )));
14716            }
14717        }
14718        match recorded_selection_member_outcome(&state, &self.handle) {
14719            Ok(Some(result)) => {
14720                state.advance_cancellation_handle(&self.handle, false);
14721                Poll::Ready(Ok(result))
14722            }
14723            Ok(None) => Poll::Pending,
14724            Err(error) => {
14725                if !workflow_task_integrity_error(&error) {
14726                    state.advance_cancellation_handle(&self.handle, true);
14727                }
14728                Poll::Ready(Err(error))
14729            }
14730        }
14731    }
14732}
14733
14734fn validate_selection_delivery_handle(
14735    state: &WorkflowState,
14736    handle: &DurableOperationHandle,
14737) -> Result<()> {
14738    let path = state
14739        .recorded_commands
14740        .iter()
14741        .find(|command| command.sequence() == handle.base_sequence)
14742        .and_then(|command| match command {
14743            RecordedCommand::Activity {
14744                parallel_group_path,
14745                ..
14746            }
14747            | RecordedCommand::ChildWorkflow {
14748                parallel_group_path,
14749                ..
14750            }
14751            | RecordedCommand::Timer {
14752                parallel_group_path,
14753                ..
14754            }
14755            | RecordedCommand::SignalWait {
14756                parallel_group_path,
14757                ..
14758            }
14759            | RecordedCommand::ConditionWait {
14760                parallel_group_path,
14761                ..
14762            } => parallel_group_path.as_ref(),
14763            _ => None,
14764        })
14765        .and_then(|path| path.first());
14766    let matches = path.is_some_and(|entry| {
14767        entry.parallel_group_mode.as_deref() == Some("select")
14768            && entry.parallel_group_id == handle.selection_group_id
14769            && entry.selection_member_key.as_ref() == Some(&handle.key)
14770            && entry.selection_member_index == Some(handle.index)
14771            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14772            && entry.selection_member_size == Some(handle.size)
14773            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14774    });
14775    if !matches
14776        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14777            != handle.identity
14778    {
14779        return Err(invalid_recorded_history(
14780            "cooperative_cancellation_call_mismatch",
14781            handle.base_sequence,
14782            "selection handle matching its authored durable identity",
14783            &format!("{handle:?}"),
14784            "selection handle identity or member metadata changed before cancellation replay",
14785        ));
14786    }
14787    Ok(())
14788}
14789
14790/// Future returned by [`DurableOperationHandle::cancel`].
14791pub struct CancelDurableOperationCall {
14792    handle: DurableOperationHandle,
14793    emitted: bool,
14794}
14795
14796impl Future for CancelDurableOperationCall {
14797    type Output = Result<()>;
14798
14799    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14800        let ctx = self.handle.ctx.clone();
14801        let mut state = match ctx.state.lock() {
14802            Ok(state) => state,
14803            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14804        };
14805        match selection_cancellation_for_handle(&state, &self.handle) {
14806            Err(error) => return Poll::Ready(Err(error)),
14807            Ok(true) => {
14808                state.advance_cancellation_receipt(
14809                    &self.handle.selection_group_id,
14810                    self.handle.base_sequence,
14811                );
14812                return Poll::Ready(Ok(()));
14813            }
14814            Ok(false) => {}
14815        }
14816        if recorded_selection_member_is_terminal(&state, &self.handle) {
14817            return Poll::Ready(Ok(()));
14818        }
14819        if !self.emitted {
14820            state.commands.push(json!({
14821                "type": "cancel_selection_operation",
14822                "selection_group_id": self.handle.selection_group_id,
14823                "member_key": self.handle.key,
14824                "member_index": self.handle.index,
14825                "member_base_sequence": self.handle.base_sequence,
14826                "member_size": self.handle.size,
14827                "operation_kind": self.handle.kind,
14828                "operation_identity": self.handle.identity,
14829            }));
14830            self.emitted = true;
14831        }
14832        // Unit completes the request, not the member's outcome. Following
14833        // workflow commands commit atomically with this cancellation request.
14834        // Waiting here would need another workflow task that cancellation
14835        // alone does not create. await_result still requires recorded history.
14836        Poll::Ready(Ok(()))
14837    }
14838}
14839
14840trait PollNestedResultExt<T> {
14841    fn flatten_result(self) -> Poll<Result<T>>;
14842}
14843
14844impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14845    fn flatten_result(self) -> Poll<Result<T>> {
14846        match self {
14847            Poll::Ready(Ok(result)) => Poll::Ready(result),
14848            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14849            Poll::Pending => Poll::Pending,
14850        }
14851    }
14852}
14853
14854struct SagaCompensation {
14855    activity_type: String,
14856    options: ActivityOptions,
14857    arguments: AvroValue,
14858    registration_order: usize,
14859}
14860
14861/// Workflow-local deterministic saga compensation helper.
14862///
14863/// Register each compensation only after its forward step succeeds. Passing
14864/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14865/// reverse registration order after any failure, including cooperative
14866/// cancellation. Each compensation is an ordinary durable activity, so replay,
14867/// duplicate delivery, and worker restart use existing history semantics.
14868pub struct Saga {
14869    ctx: WorkflowContext,
14870    compensations: Vec<SagaCompensation>,
14871}
14872
14873impl Saga {
14874    fn new(ctx: WorkflowContext) -> Self {
14875        Self {
14876            ctx,
14877            compensations: Vec::new(),
14878        }
14879    }
14880
14881    pub fn add_compensation<T: Serialize>(
14882        &mut self,
14883        activity_type: impl Into<String>,
14884        args: T,
14885    ) -> Result<&mut Self> {
14886        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14887    }
14888
14889    pub fn add_compensation_with_options<T: Serialize>(
14890        &mut self,
14891        activity_type: impl Into<String>,
14892        options: ActivityOptions,
14893        args: T,
14894    ) -> Result<&mut Self> {
14895        let activity_type = activity_type.into();
14896        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14897            return Err(Error::Codec(
14898                "saga compensation activity type must be non-empty without surrounding whitespace"
14899                    .to_string(),
14900            ));
14901        }
14902        options.validate().map_err(Error::InvalidActivityOptions)?;
14903        let arguments = AvroValue::from_serialize(&args)?;
14904        let registration_order = self.compensations.len() + 1;
14905        self.compensations.push(SagaCompensation {
14906            activity_type,
14907            options,
14908            arguments,
14909            registration_order,
14910        });
14911        Ok(self)
14912    }
14913
14914    /// Compensate `initiating_failure` and return the failure that must remain.
14915    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14916        let _shield = match self.ctx.cancellation_shield() {
14917            Ok(shield) => shield,
14918            Err(error) => return error,
14919        };
14920        while let Some(compensation) = self.compensations.pop() {
14921            if let Err(compensation_failure) = self
14922                .ctx
14923                .activity_with_options(
14924                    compensation.activity_type.clone(),
14925                    compensation.options,
14926                    compensation.arguments,
14927                )
14928                .await
14929            {
14930                if workflow_task_integrity_error(&compensation_failure) {
14931                    return compensation_failure;
14932                }
14933                return Error::SagaCompensationFailed(SagaCompensationFailure {
14934                    initiating_failure: Box::new(initiating_failure),
14935                    compensation_failure: Box::new(compensation_failure),
14936                    compensation_activity_type: compensation.activity_type,
14937                    compensation_registration_order: compensation.registration_order,
14938                });
14939            }
14940        }
14941        initiating_failure
14942    }
14943
14944    /// Return a successful forward value or compensate and preserve its failure.
14945    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14946        match outcome {
14947            Ok(value) => Ok(value),
14948            Err(error) => Err(self.compensate(error).await),
14949        }
14950    }
14951}
14952
14953pub struct ActivityCall {
14954    ctx: WorkflowContext,
14955    activity_type: String,
14956    options: ActivityOptions,
14957    worker_session: Option<WorkerSessionOptions>,
14958    args: Option<Result<AvroValue>>,
14959    scheduled: bool,
14960    local: bool,
14961    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14962    parallel_group_path: Vec<ParallelGroupMetadata>,
14963}
14964
14965impl ActivityCall {
14966    fn poll_avro_value(
14967        mut self: Pin<&mut Self>,
14968        _cx: &mut TaskContext<'_>,
14969    ) -> Poll<Result<AvroValue>> {
14970        let ctx = self.ctx.clone();
14971        let mut state = match ctx.state.lock() {
14972            Ok(state) => state,
14973            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14974        };
14975
14976        if let Some(result) = &self.local_result {
14977            return match result.lock() {
14978                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14979                    Poll::Ready(result.map_err(Error::ActivityFailed))
14980                }),
14981                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14982            };
14983        }
14984        if self.scheduled {
14985            return Poll::Pending;
14986        }
14987
14988        let options = match self.options.validate() {
14989            Ok(options) => options,
14990            Err(error) => {
14991                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14992            }
14993        };
14994        if self.local {
14995            if self.worker_session.is_some() {
14996                return Poll::Ready(Err(Error::WorkerLoop(
14997                    "local activities cannot use worker-session routing".into(),
14998                )));
14999            }
15000            if let Err(error) = local_activity::validate(&options) {
15001                return Poll::Ready(Err(error));
15002            }
15003        }
15004        let session = match self
15005            .worker_session
15006            .as_ref()
15007            .map(WorkerSessionOptions::to_wire)
15008            .transpose()
15009        {
15010            Ok(value) => value,
15011            Err(error) => return Poll::Ready(Err(error)),
15012        };
15013        let session_queue = session
15014            .as_ref()
15015            .and_then(|session| session["queue"].as_str());
15016        let task_queue = options
15017            .task_queue
15018            .clone()
15019            .or_else(|| session_queue.map(str::to_owned))
15020            .unwrap_or_else(|| state.task_queue.clone());
15021        if session_queue.is_some_and(|queue| queue != task_queue) {
15022            return Poll::Ready(Err(Error::WorkerLoop(
15023                "worker-session queue must match the activity task queue".into(),
15024            )));
15025        }
15026        let current_recorded_options = RecordedActivityOptions {
15027            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15028            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15029            retry_policy: current_activity_retry_snapshot(&options),
15030            worker_session: session,
15031        };
15032
15033        let cursor = state.command_cursor;
15034        let call_kind = if self.local {
15035            CancellationCallKind::LocalActivity
15036        } else {
15037            CancellationCallKind::Activity
15038        };
15039        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15040            return Poll::Ready(Err(error));
15041        }
15042        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15043            Ok(recorded) => recorded,
15044            Err(error) => return Poll::Ready(Err(error)),
15045        };
15046        if let Some(recorded) = recorded {
15047            let sequence = recorded.sequence();
15048            match recorded {
15049                RecordedCommand::Activity {
15050                    activity_type,
15051                    cancellation_policy,
15052                    options: recorded_options,
15053                    outcome,
15054                    parallel_group_path,
15055                    ..
15056                } => {
15057                    let current_policy = options
15058                        .cancellation_policy
15059                        .unwrap_or(CancellationPolicy::TryCancel)
15060                        .as_str();
15061                    if cancellation_policy != current_policy {
15062                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15063                            ReplayFailure::new(
15064                                "activity_cancellation_policy_changed",
15065                                Some(sequence),
15066                                Some(cancellation_policy),
15067                                Some(current_policy.to_string()),
15068                                "Activity cancellation policy changed during replay",
15069                            ),
15070                        )));
15071                    }
15072                    if let Err(error) = ensure_parallel_path_matches(
15073                        sequence,
15074                        parallel_group_path.as_deref(),
15075                        &self.parallel_group_path,
15076                    ) {
15077                        return Poll::Ready(Err(error));
15078                    }
15079                    if let Some(recorded_type) = activity_type {
15080                        if recorded_type != self.activity_type {
15081                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15082                                ReplayFailure::new(
15083                                    "recorded_command_detail_mismatch",
15084                                    Some(sequence),
15085                                    Some(format!("activity:{recorded_type}")),
15086                                    Some(format!("activity:{}", self.activity_type)),
15087                                    "recorded activity type differs from the current workflow command",
15088                                ),
15089                            )));
15090                        }
15091                    }
15092                    if let Some(recorded_options) = recorded_options {
15093                        if recorded_options.worker_session
15094                            != current_recorded_options.worker_session
15095                        {
15096                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15097                                "activity_worker_session_mismatch", Some(sequence),
15098                                Some(activity_options_description(&recorded_options)),
15099                                Some(activity_options_description(&current_recorded_options)),
15100                                "recorded worker-session routing differs from the current activity",
15101                            ))));
15102                        }
15103                        if !recorded_options
15104                            .task_queue
15105                            .matches_current(&current_recorded_options.task_queue)
15106                        {
15107                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15108                                ReplayFailure::new(
15109                                    "activity_task_queue_mismatch",
15110                                    Some(sequence),
15111                                    Some(activity_options_description(&recorded_options)),
15112                                    Some(activity_options_description(&current_recorded_options)),
15113                                    "recorded activity task queue differs from the current workflow command",
15114                                ),
15115                            )));
15116                        }
15117                        if (self.local
15118                            && matches!(
15119                                recorded_options.execution_mode,
15120                                RecordedSnapshotValue::Unknown
15121                            ))
15122                            || !recorded_options
15123                                .execution_mode
15124                                .matches_current(&current_recorded_options.execution_mode)
15125                        {
15126                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15127                                ReplayFailure::new(
15128                                    "activity_execution_mode_mismatch",
15129                                    Some(sequence),
15130                                    Some(activity_options_description(&recorded_options)),
15131                                    Some(activity_options_description(&current_recorded_options)),
15132                                    "recorded activity execution mode differs from the current workflow command",
15133                                ),
15134                            )));
15135                        }
15136                        if !recorded_options
15137                            .retry_policy
15138                            .matches_current(&current_recorded_options.retry_policy)
15139                        {
15140                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15141                                ReplayFailure::new(
15142                                    "activity_retry_policy_mismatch",
15143                                    Some(sequence),
15144                                    Some(activity_options_description(&recorded_options)),
15145                                    Some(activity_options_description(&current_recorded_options)),
15146                                    "recorded activity retry policy differs from the current workflow command",
15147                                ),
15148                            )));
15149                        }
15150                    }
15151                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15152                        return Poll::Ready(Err(error));
15153                    }
15154                    match state.prepare_scalar_cancellation(
15155                        cursor,
15156                        call_kind,
15157                        &self.parallel_group_path,
15158                    ) {
15159                        Ok(true) => {
15160                            self.scheduled = true;
15161                            return Poll::Pending;
15162                        }
15163                        Ok(false) => {}
15164                        Err(error) => return Poll::Ready(Err(error)),
15165                    }
15166                    state.command_cursor += 1;
15167                    if let Some(outcome) = outcome {
15168                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15169                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15170                    }
15171                    state.matched_recorded_pending = true;
15172                    self.scheduled = true;
15173                    return Poll::Pending;
15174                }
15175                other => {
15176                    return Poll::Ready(Err(command_mismatch(
15177                        &other,
15178                        format!("activity:{}", self.activity_type),
15179                    )));
15180                }
15181            }
15182        }
15183
15184        if !self.scheduled {
15185            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15186                Ok(args) => args,
15187                Err(error) => return Poll::Ready(Err(error)),
15188            };
15189            let arguments = normalize_avro_arguments(args);
15190            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15191                Ok(envelope) => envelope,
15192                Err(error) => return Poll::Ready(Err(error)),
15193            };
15194
15195            let mut command = serde_json::Map::from_iter([
15196                (
15197                    "type".to_string(),
15198                    json!(if self.local {
15199                        "record_local_activity"
15200                    } else {
15201                        "schedule_activity"
15202                    }),
15203                ),
15204                (
15205                    "activity_type".to_string(),
15206                    json!(self.activity_type.clone()),
15207                ),
15208                ("queue".to_string(), json!(task_queue)),
15209                ("arguments".to_string(), envelope),
15210            ]);
15211            for (field, value) in [
15212                ("start_to_close_timeout", options.start_to_close_timeout),
15213                (
15214                    "schedule_to_start_timeout",
15215                    options.schedule_to_start_timeout,
15216                ),
15217                (
15218                    "schedule_to_close_timeout",
15219                    options.schedule_to_close_timeout,
15220                ),
15221                ("heartbeat_timeout", options.heartbeat_timeout),
15222            ] {
15223                if let Some(value) = value {
15224                    command.insert(field.to_string(), json!(value));
15225                }
15226            }
15227            if let Some(retry_policy) = &options.retry_policy {
15228                command.insert("retry_policy".to_string(), retry_policy.clone());
15229            }
15230            if let Some(policy) = options.cancellation_policy {
15231                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15232            }
15233            if let Some(session) = current_recorded_options.worker_session {
15234                command.insert("worker_session".into(), session);
15235            }
15236            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15237            ctx.apply_scope_membership(&mut command);
15238            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15239                Ok(true) => {
15240                    self.scheduled = true;
15241                    return Poll::Pending;
15242                }
15243                Ok(false) => {}
15244                Err(error) => return Poll::Ready(Err(error)),
15245            }
15246            if self.local {
15247                command.remove("queue");
15248                command.insert("execution_mode".into(), json!("local"));
15249                let result = Arc::new(Mutex::new(None));
15250                let command_index = state.commands.len();
15251                state.local_activity_requests.push(local_activity::Request {
15252                    command_index,
15253                    options,
15254                    arguments,
15255                    result: result.clone(),
15256                });
15257                self.local_result = Some(result);
15258            }
15259            state.commands.push(Value::Object(command));
15260            self.scheduled = true;
15261        }
15262
15263        Poll::Pending
15264    }
15265}
15266
15267impl Future for ActivityCall {
15268    type Output = Result<Value>;
15269
15270    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15271        match self.poll_avro_value(cx) {
15272            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15273            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15274            Poll::Pending => Poll::Pending,
15275        }
15276    }
15277}
15278
15279/// Future returned by [`WorkflowContext::sleep`].
15280pub struct TimerCall {
15281    ctx: WorkflowContext,
15282    delay_seconds: Option<u64>,
15283    scheduled: bool,
15284    matched_pending: bool,
15285    parallel_group_path: Vec<ParallelGroupMetadata>,
15286}
15287
15288impl Future for TimerCall {
15289    type Output = Result<()>;
15290
15291    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15292        if self.matched_pending {
15293            return Poll::Pending;
15294        }
15295
15296        let ctx = self.ctx.clone();
15297        let Some(requested_delay) = self.delay_seconds else {
15298            return Poll::Ready(Err(Error::TimerDurationOverflow));
15299        };
15300        let mut state = match ctx.state.lock() {
15301            Ok(state) => state,
15302            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15303        };
15304
15305        let cursor = state.command_cursor;
15306        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15307            return Poll::Ready(Err(error));
15308        }
15309        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15310        {
15311            Ok(recorded) => recorded,
15312            Err(error) => return Poll::Ready(Err(error)),
15313        };
15314        if let Some(recorded) = recorded {
15315            match recorded {
15316                RecordedCommand::Timer {
15317                    sequence,
15318                    delay_seconds,
15319                    fired,
15320                    parallel_group_path,
15321                    ..
15322                } => {
15323                    if let Err(error) =
15324                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15325                    {
15326                        return Poll::Ready(Err(error));
15327                    }
15328                    if let Err(error) = ensure_parallel_path_matches(
15329                        sequence,
15330                        parallel_group_path.as_deref(),
15331                        &self.parallel_group_path,
15332                    ) {
15333                        return Poll::Ready(Err(error));
15334                    }
15335                    if delay_seconds != requested_delay {
15336                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15337                            ReplayFailure::new(
15338                                "timer_delay_mismatch",
15339                                Some(sequence),
15340                                Some(format!("timer:{delay_seconds}s")),
15341                                Some(format!("timer:{requested_delay}s")),
15342                                "recorded timer delay differs from the current workflow command",
15343                            ),
15344                        )));
15345                    }
15346                    if let Err(error) =
15347                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
15348                    {
15349                        return Poll::Ready(Err(error));
15350                    }
15351                    match state.prepare_scalar_cancellation(
15352                        cursor,
15353                        CancellationCallKind::Timer,
15354                        &self.parallel_group_path,
15355                    ) {
15356                        Ok(true) => {
15357                            self.scheduled = true;
15358                            self.matched_pending = true;
15359                            return Poll::Pending;
15360                        }
15361                        Ok(false) => {}
15362                        Err(error) => return Poll::Ready(Err(error)),
15363                    }
15364                    state.command_cursor += 1;
15365                    if fired {
15366                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15367                        return Poll::Ready(Ok(()));
15368                    }
15369                    state.matched_recorded_pending = true;
15370                    self.scheduled = true;
15371                    self.matched_pending = true;
15372                    return Poll::Pending;
15373                }
15374                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
15375            }
15376        }
15377
15378        if !self.scheduled {
15379            let mut command = serde_json::Map::from_iter([
15380                ("type".to_string(), json!("start_timer")),
15381                ("delay_seconds".to_string(), json!(requested_delay)),
15382            ]);
15383            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
15384                Ok(Some(proof)) => {
15385                    command.insert("cancellation_cleanup".into(), proof);
15386                }
15387                Ok(None) => {}
15388                Err(error) => return Poll::Ready(Err(error)),
15389            }
15390            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15391            ctx.apply_scope_membership(&mut command);
15392            match state.prepare_scalar_cancellation(
15393                cursor,
15394                CancellationCallKind::Timer,
15395                &self.parallel_group_path,
15396            ) {
15397                Ok(true) => {
15398                    self.scheduled = true;
15399                    self.matched_pending = true;
15400                    return Poll::Pending;
15401                }
15402                Ok(false) => {}
15403                Err(error) => return Poll::Ready(Err(error)),
15404            }
15405            state.commands.push(Value::Object(command));
15406            self.scheduled = true;
15407        }
15408
15409        Poll::Pending
15410    }
15411}
15412
15413/// Future returned by [`WorkflowContext::wait_condition`].
15414pub struct ConditionWaitCall {
15415    ctx: WorkflowContext,
15416    options: ConditionWaitOptions,
15417    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
15418    occurrence_id: Option<String>,
15419    opened_wait: bool,
15420    parallel_group_path: Vec<ParallelGroupMetadata>,
15421}
15422
15423impl Future for ConditionWaitCall {
15424    type Output = Result<ConditionWaitResult>;
15425
15426    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15427        if self.opened_wait {
15428            return Poll::Pending;
15429        }
15430
15431        let options = match self.options.validate() {
15432            Ok(options) => options,
15433            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
15434        };
15435        let ctx = self.ctx.clone();
15436        let occurrence_id = match self.occurrence_id.as_ref() {
15437            Some(occurrence_id) => occurrence_id.clone(),
15438            None => {
15439                let mut state = match ctx.state.lock() {
15440                    Ok(state) => state,
15441                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15442                };
15443                let ordinal = state.condition_wait_occurrence_counter;
15444                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
15445                    Some(next) => next,
15446                    None => {
15447                        return Poll::Ready(Err(Error::WorkerLoop(
15448                            "condition wait occurrence counter overflowed".to_string(),
15449                        )))
15450                    }
15451                };
15452                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
15453                drop(state);
15454                self.occurrence_id = Some(occurrence_id.clone());
15455                occurrence_id
15456            }
15457        };
15458
15459        let recorded_result = {
15460            let mut state = match ctx.state.lock() {
15461                Ok(state) => state,
15462                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15463            };
15464            let initial_cursor = state.command_cursor;
15465            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
15466                return Poll::Ready(Err(error));
15467            }
15468            let recorded = match state
15469                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
15470            {
15471                Ok(recorded) => recorded,
15472                Err(error) => return Poll::Ready(Err(error)),
15473            };
15474            let Some(recorded) = recorded else {
15475                drop(state);
15476                return self.poll_new_condition(options);
15477            };
15478            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
15479                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
15480            }
15481
15482            let mut cursor = state.command_cursor;
15483            let mut result = None;
15484            let mut pending_delivery = false;
15485            loop {
15486                if cursor > initial_cursor
15487                    && matches!(
15488                        state.recorded_commands.get(cursor),
15489                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
15490                    )
15491                {
15492                    break;
15493                }
15494                let recorded = match state
15495                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
15496                {
15497                    Ok(recorded) => recorded,
15498                    Err(error) => return Poll::Ready(Err(error)),
15499                };
15500                let Some(RecordedCommand::ConditionWait {
15501                    sequence,
15502                    occurrence_id: ref recorded_occurrence_id,
15503                    ref condition_key,
15504                    ref predicate_identity,
15505                    timeout_seconds,
15506                    result: recorded_result,
15507                    ref parallel_group_path,
15508                    ..
15509                }) = recorded
15510                else {
15511                    break;
15512                };
15513
15514                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
15515                    break;
15516                }
15517                if let Err(error) = ensure_parallel_path_matches(
15518                    sequence,
15519                    parallel_group_path.as_deref(),
15520                    &self.parallel_group_path,
15521                ) {
15522                    return Poll::Ready(Err(error));
15523                }
15524                if let Err(error) = validate_recorded_condition_wait(
15525                    sequence,
15526                    recorded_occurrence_id,
15527                    condition_key.as_deref(),
15528                    predicate_identity,
15529                    timeout_seconds,
15530                    &occurrence_id,
15531                    &options,
15532                ) {
15533                    return Poll::Ready(Err(error));
15534                }
15535                if result == Some(ConditionWaitResult::TimedOut) {
15536                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15537                        "condition_wait_reopened_after_timeout",
15538                        Some(sequence),
15539                        Some("timed-out condition is terminal".to_string()),
15540                        Some("another physical wait-open".to_string()),
15541                        "condition history reopened one logical wait after its durable timeout",
15542                    ))));
15543                }
15544                if let Err(error) =
15545                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
15546                {
15547                    return Poll::Ready(Err(error));
15548                }
15549                match state.prepare_scalar_cancellation(
15550                    cursor,
15551                    CancellationCallKind::Condition,
15552                    &self.parallel_group_path,
15553                ) {
15554                    Ok(pending) => pending_delivery |= pending,
15555                    Err(error) => return Poll::Ready(Err(error)),
15556                }
15557                result = recorded_result;
15558                if result.is_some() {
15559                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15560                }
15561                cursor += 1;
15562            }
15563            state.command_cursor = cursor;
15564            if pending_delivery {
15565                self.opened_wait = true;
15566                return Poll::Pending;
15567            }
15568            result
15569        };
15570
15571        if let Some(result) = recorded_result {
15572            return Poll::Ready(Ok(result));
15573        }
15574
15575        self.poll_open_condition(options, true)
15576    }
15577}
15578
15579impl ConditionWaitCall {
15580    fn poll_new_condition(
15581        self: Pin<&mut Self>,
15582        options: ValidatedConditionWaitOptions,
15583    ) -> Poll<Result<ConditionWaitResult>> {
15584        self.poll_open_condition(options, false)
15585    }
15586
15587    fn poll_open_condition(
15588        mut self: Pin<&mut Self>,
15589        options: ValidatedConditionWaitOptions,
15590        recorded_wait: bool,
15591    ) -> Poll<Result<ConditionWaitResult>> {
15592        {
15593            let ctx = self.ctx.clone();
15594            let mut state = match ctx.state.lock() {
15595                Ok(state) => state,
15596                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15597            };
15598            let cursor = state.command_cursor;
15599            match state.prepare_scalar_cancellation(
15600                cursor,
15601                CancellationCallKind::Condition,
15602                &self.parallel_group_path,
15603            ) {
15604                Ok(true) => {
15605                    self.opened_wait = true;
15606                    return Poll::Pending;
15607                }
15608                Ok(false) => {}
15609                Err(error) => return Poll::Ready(Err(error)),
15610            }
15611        }
15612        let selection_member = self
15613            .parallel_group_path
15614            .first()
15615            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
15616        match (self.predicate)() {
15617            Ok(true) if !selection_member || recorded_wait => {
15618                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
15619            }
15620            Ok(_) => {}
15621            Err(error) => return Poll::Ready(Err(error)),
15622        }
15623        if options.timeout_seconds == Some(0) && !selection_member {
15624            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15625        }
15626
15627        let ctx = self.ctx.clone();
15628        let mut state = match ctx.state.lock() {
15629            Ok(state) => state,
15630            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15631        };
15632        let mut command = serde_json::Map::from_iter([
15633            ("type".to_string(), json!("open_condition_wait")),
15634            (
15635                "condition_wait_occurrence_id".to_string(),
15636                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15637            ),
15638            ("condition_key".to_string(), json!(options.condition_key)),
15639            (
15640                "condition_definition_fingerprint".to_string(),
15641                json!(options.predicate_identity),
15642            ),
15643        ]);
15644        if let Some(timeout_seconds) = options.timeout_seconds {
15645            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15646        }
15647        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15648        ctx.apply_scope_membership(&mut command);
15649        state.commands.push(Value::Object(command));
15650        drop(state);
15651        self.opened_wait = true;
15652        Poll::Pending
15653    }
15654}
15655
15656fn validate_recorded_condition_wait(
15657    sequence: u64,
15658    recorded_occurrence_id: &str,
15659    recorded_key: Option<&str>,
15660    recorded_predicate_identity: &str,
15661    recorded_timeout_seconds: Option<u64>,
15662    current_occurrence_id: &str,
15663    current: &ValidatedConditionWaitOptions,
15664) -> Result<()> {
15665    if recorded_occurrence_id != current_occurrence_id {
15666        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15667            "condition_wait_occurrence_mismatch",
15668            Some(sequence),
15669            Some(recorded_occurrence_id.to_string()),
15670            Some(current_occurrence_id.to_string()),
15671            "recorded condition occurrence differs from the current authored wait position",
15672        )));
15673    }
15674    if recorded_key != Some(current.condition_key.as_str()) {
15675        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15676            "condition_wait_key_mismatch",
15677            Some(sequence),
15678            recorded_key.map(str::to_string),
15679            Some(current.condition_key.clone()),
15680            "recorded condition identity differs from the current workflow wait",
15681        )));
15682    }
15683    if recorded_predicate_identity != current.predicate_identity {
15684        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15685            "condition_wait_predicate_mismatch",
15686            Some(sequence),
15687            Some(recorded_predicate_identity.to_string()),
15688            Some(current.predicate_identity.clone()),
15689            "recorded condition predicate behavior differs from current workflow code",
15690        )));
15691    }
15692    if recorded_timeout_seconds != current.timeout_seconds {
15693        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15694            "condition_wait_timeout_mismatch",
15695            Some(sequence),
15696            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15697            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15698            "recorded condition timeout differs from the current workflow wait",
15699        )));
15700    }
15701    Ok(())
15702}
15703
15704/// Future returned by [`WorkflowContext::start_child_workflow`].
15705pub struct ChildWorkflowCall {
15706    ctx: WorkflowContext,
15707    workflow_type: String,
15708    options: ChildWorkflowOptions,
15709    args: Option<Result<AvroValue>>,
15710    scheduled: bool,
15711    matched_pending: bool,
15712    parallel_group_path: Vec<ParallelGroupMetadata>,
15713}
15714
15715impl ChildWorkflowCall {
15716    fn poll_avro_value(
15717        mut self: Pin<&mut Self>,
15718        _cx: &mut TaskContext<'_>,
15719    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15720        if self.matched_pending {
15721            return Poll::Pending;
15722        }
15723
15724        let ctx = self.ctx.clone();
15725        let mut state = match ctx.state.lock() {
15726            Ok(state) => state,
15727            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15728        };
15729
15730        let cursor = state.command_cursor;
15731        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15732            return Poll::Ready(Err(error));
15733        }
15734        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15735        {
15736            Ok(recorded) => recorded,
15737            Err(error) => return Poll::Ready(Err(error)),
15738        };
15739        if let Some(recorded) = recorded {
15740            let sequence = recorded.sequence();
15741            match recorded {
15742                RecordedCommand::ChildWorkflow {
15743                    workflow_type,
15744                    policies,
15745                    outcome,
15746                    parallel_group_path,
15747                    ..
15748                } => {
15749                    if let Err(error) = ensure_parallel_path_matches(
15750                        sequence,
15751                        parallel_group_path.as_deref(),
15752                        &self.parallel_group_path,
15753                    ) {
15754                        return Poll::Ready(Err(error));
15755                    }
15756                    if let Some(recorded_type) = workflow_type {
15757                        if recorded_type != self.workflow_type {
15758                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15759                                ReplayFailure::new(
15760                                    "recorded_command_detail_mismatch",
15761                                    Some(sequence),
15762                                    Some(format!("child workflow:{recorded_type}")),
15763                                    Some(format!("child workflow:{}", self.workflow_type)),
15764                                    "recorded child workflow type differs from the current workflow command",
15765                                ),
15766                            )));
15767                        }
15768                    }
15769                    if let Err(error) =
15770                        ensure_child_policies_match(sequence, &policies, &self.options)
15771                    {
15772                        return Poll::Ready(Err(error));
15773                    }
15774                    if let Err(error) =
15775                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15776                    {
15777                        return Poll::Ready(Err(error));
15778                    }
15779                    match state.prepare_scalar_cancellation(
15780                        cursor,
15781                        CancellationCallKind::Child,
15782                        &self.parallel_group_path,
15783                    ) {
15784                        Ok(true) => {
15785                            self.scheduled = true;
15786                            self.matched_pending = true;
15787                            return Poll::Pending;
15788                        }
15789                        Ok(false) => {}
15790                        Err(error) => return Poll::Ready(Err(error)),
15791                    }
15792                    state.command_cursor += 1;
15793                    if let Some(outcome) = outcome {
15794                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15795                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15796                    }
15797                    state.matched_recorded_pending = true;
15798                    self.scheduled = true;
15799                    self.matched_pending = true;
15800                    return Poll::Pending;
15801                }
15802                other => {
15803                    return Poll::Ready(Err(command_mismatch(
15804                        &other,
15805                        format!("child workflow:{}", self.workflow_type),
15806                    )));
15807                }
15808            }
15809        }
15810
15811        if !self.scheduled {
15812            if self.options.task_queue.trim().is_empty() {
15813                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15814                    "task_queue must not be empty".to_string(),
15815                )));
15816            }
15817            for (name, value) in [
15818                (
15819                    "execution_timeout_seconds",
15820                    self.options.execution_timeout_seconds,
15821                ),
15822                ("run_timeout_seconds", self.options.run_timeout_seconds),
15823            ] {
15824                if value == Some(0) {
15825                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15826                        "{name} must be at least 1"
15827                    ))));
15828                }
15829            }
15830
15831            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15832                Ok(args) => args,
15833                Err(error) => return Poll::Ready(Err(error)),
15834            };
15835            let arguments = match encode_typed_envelope(
15836                &normalize_avro_arguments(args),
15837                &state.payload_codec,
15838            ) {
15839                Ok(arguments) => arguments,
15840                Err(error) => return Poll::Ready(Err(error)),
15841            };
15842            let mut command = json!({
15843                "type": "start_child_workflow",
15844                "workflow_type": self.workflow_type,
15845                "queue": self.options.task_queue,
15846                "parent_close_policy": self.options.parent_close_policy.as_str(),
15847                "arguments": arguments,
15848            });
15849            let object = command
15850                .as_object_mut()
15851                .expect("child workflow command is always an object");
15852            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15853                object.insert(
15854                    "cancellation_policy".to_string(),
15855                    json!(self.options.cancellation_policy.as_str()),
15856                );
15857            }
15858            if let Some(policy) = &self.options.retry_policy {
15859                let mut retry_policy = serde_json::Map::new();
15860                if let Some(max_attempts) = policy.max_attempts {
15861                    if max_attempts == 0 {
15862                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15863                            "retry_policy.max_attempts must be at least 1".to_string(),
15864                        )));
15865                    }
15866                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15867                }
15868                if !policy.backoff_seconds.is_empty() {
15869                    retry_policy
15870                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15871                }
15872                if !policy.non_retryable_error_types.is_empty() {
15873                    retry_policy.insert(
15874                        "non_retryable_error_types".to_string(),
15875                        json!(policy.non_retryable_error_types),
15876                    );
15877                }
15878                if retry_policy.is_empty() {
15879                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15880                        "retry_policy must configure at least one field".to_string(),
15881                    )));
15882                }
15883                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15884            }
15885            if let Some(seconds) = self.options.execution_timeout_seconds {
15886                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15887            }
15888            if let Some(seconds) = self.options.run_timeout_seconds {
15889                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15890            }
15891            apply_parallel_group_path(object, &self.parallel_group_path);
15892            ctx.apply_scope_membership(object);
15893            match state.prepare_scalar_cancellation(
15894                cursor,
15895                CancellationCallKind::Child,
15896                &self.parallel_group_path,
15897            ) {
15898                Ok(true) => {
15899                    self.scheduled = true;
15900                    self.matched_pending = true;
15901                    return Poll::Pending;
15902                }
15903                Ok(false) => {}
15904                Err(error) => return Poll::Ready(Err(error)),
15905            }
15906            state.commands.push(command);
15907            self.scheduled = true;
15908        }
15909
15910        Poll::Pending
15911    }
15912}
15913
15914impl Future for ChildWorkflowCall {
15915    type Output = Result<ChildWorkflowResult>;
15916
15917    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15918        match self.poll_avro_value(cx) {
15919            Poll::Ready(Ok(result)) => match result.result.into_json() {
15920                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15921                    parent: result.parent,
15922                    child: result.child,
15923                    child_workflow_type: result.child_workflow_type,
15924                    result: projected,
15925                })),
15926                Err(error) => Poll::Ready(Err(error)),
15927            },
15928            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15929            Poll::Pending => Poll::Pending,
15930        }
15931    }
15932}
15933
15934fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15935    Error::NonDeterministicReplay(ReplayFailure::new(
15936        "recorded_command_mismatch",
15937        Some(recorded.sequence()),
15938        Some(recorded.shape().to_string()),
15939        Some(actual.into()),
15940        "current workflow command does not match the recorded durable command sequence",
15941    ))
15942}
15943
15944pub struct SignalCall {
15945    ctx: WorkflowContext,
15946    signal_name: String,
15947    runtime_reserved_allowed: bool,
15948    opened_wait: bool,
15949    matched_pending: bool,
15950    parallel_group_path: Vec<ParallelGroupMetadata>,
15951}
15952
15953impl SignalCall {
15954    fn poll_avro_value(
15955        mut self: Pin<&mut Self>,
15956        _cx: &mut TaskContext<'_>,
15957    ) -> Poll<Result<Vec<AvroValue>>> {
15958        if self.matched_pending {
15959            return Poll::Pending;
15960        }
15961        if !self.runtime_reserved_allowed {
15962            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15963                return Poll::Ready(Err(error));
15964            }
15965        }
15966
15967        let ctx = self.ctx.clone();
15968        let mut state = match ctx.state.lock() {
15969            Ok(state) => state,
15970            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15971        };
15972
15973        let cursor = state.command_cursor;
15974        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15975            return Poll::Ready(Err(error));
15976        }
15977        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15978        {
15979            Ok(recorded) => recorded,
15980            Err(error) => return Poll::Ready(Err(error)),
15981        };
15982        if let Some(recorded) = recorded {
15983            match recorded {
15984                RecordedCommand::SignalWait {
15985                    sequence,
15986                    signal_name,
15987                    value,
15988                    parallel_group_path,
15989                } => {
15990                    if let Err(error) = ensure_parallel_path_matches(
15991                        sequence,
15992                        parallel_group_path.as_deref(),
15993                        &self.parallel_group_path,
15994                    ) {
15995                        return Poll::Ready(Err(error));
15996                    }
15997                    if signal_name != self.signal_name {
15998                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15999                            ReplayFailure::new(
16000                                "recorded_command_detail_mismatch",
16001                                Some(sequence),
16002                                Some(format!("signal wait:{signal_name}")),
16003                                Some(format!("signal wait:{}", self.signal_name)),
16004                                "recorded signal name differs from the current workflow command",
16005                            ),
16006                        )));
16007                    }
16008
16009                    if let Err(error) =
16010                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16011                    {
16012                        return Poll::Ready(Err(error));
16013                    }
16014                    match state.prepare_scalar_cancellation(
16015                        cursor,
16016                        CancellationCallKind::Signal,
16017                        &self.parallel_group_path,
16018                    ) {
16019                        Ok(true) => {
16020                            self.opened_wait = true;
16021                            self.matched_pending = true;
16022                            return Poll::Pending;
16023                        }
16024                        Ok(false) => {}
16025                        Err(error) => return Poll::Ready(Err(error)),
16026                    }
16027                    state.command_cursor += 1;
16028                    if let Some(value) = value {
16029                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
16030                        return Poll::Ready(Ok(value));
16031                    }
16032                    if state
16033                        .resume_signal
16034                        .as_ref()
16035                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16036                    {
16037                        let signal = state
16038                            .resume_signal
16039                            .take()
16040                            .expect("matching resume signal is present");
16041                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
16042                        return Poll::Ready(Ok(signal.arguments));
16043                    }
16044
16045                    state.matched_recorded_pending = true;
16046                    self.opened_wait = true;
16047                    self.matched_pending = true;
16048                    return Poll::Pending;
16049                }
16050                other => {
16051                    return Poll::Ready(Err(command_mismatch(
16052                        &other,
16053                        format!("signal wait:{}", self.signal_name),
16054                    )));
16055                }
16056            }
16057        }
16058
16059        match state.prepare_scalar_cancellation(
16060            cursor,
16061            CancellationCallKind::Signal,
16062            &self.parallel_group_path,
16063        ) {
16064            Ok(true) => {
16065                self.opened_wait = true;
16066                self.matched_pending = true;
16067                return Poll::Pending;
16068            }
16069            Ok(false) => {}
16070            Err(error) => return Poll::Ready(Err(error)),
16071        }
16072
16073        if state
16074            .resume_signal
16075            .as_ref()
16076            .is_some_and(|signal| signal.signal_name == self.signal_name)
16077        {
16078            let signal = state
16079                .resume_signal
16080                .take()
16081                .expect("matching resume signal is present");
16082            state.unavailable_cancellation_boundary(&self.parallel_group_path);
16083            return Poll::Ready(Ok(signal.arguments));
16084        }
16085
16086        if !self.opened_wait {
16087            let mut command = serde_json::Map::from_iter([
16088                ("type".to_string(), json!("open_signal_wait")),
16089                ("signal_name".to_string(), json!(self.signal_name)),
16090            ]);
16091            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16092            ctx.apply_scope_membership(&mut command);
16093            state.commands.push(Value::Object(command));
16094            self.opened_wait = true;
16095        }
16096
16097        Poll::Pending
16098    }
16099}
16100
16101impl Future for SignalCall {
16102    type Output = Result<Vec<Value>>;
16103
16104    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16105        match self.poll_avro_value(cx) {
16106            Poll::Ready(Ok(values)) => Poll::Ready(
16107                values
16108                    .into_iter()
16109                    .map(AvroValue::into_json)
16110                    .collect::<Result<Vec<_>>>(),
16111            ),
16112            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16113            Poll::Pending => Poll::Pending,
16114        }
16115    }
16116}
16117
16118#[derive(Clone, Debug)]
16119pub struct ActivityContext {
16120    client: Client,
16121    pub task_id: String,
16122    pub activity_attempt_id: String,
16123    pub lease_owner: String,
16124    pub activity_type: String,
16125    pub attempt_number: u64,
16126    pub task_queue: String,
16127    pub worker_id: String,
16128    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16129    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16130    worker_session: Option<WorkerSession>,
16131}
16132
16133impl ActivityContext {
16134    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16135        if let Some(heartbeats) = &self.local_heartbeats {
16136            return heartbeats
16137                .lock()
16138                .map_err(|_| Error::WorkflowStatePoisoned)?
16139                .record(details);
16140        }
16141        if let Some(guard) = &self.claim_guard {
16142            return guard.heartbeat(self, details).await;
16143        }
16144        if let Some(session) = &self.worker_session {
16145            if !session.active() {
16146                return Err(Error::ActivityExecutionAbandoned(
16147                    "worker-session lease or TTL is no longer active".into(),
16148                ));
16149            }
16150            let result = self
16151                .client
16152                .heartbeat_activity_task_value(
16153                    &self.task_id,
16154                    &self.activity_attempt_id,
16155                    &self.lease_owner,
16156                    details,
16157                )
16158                .await;
16159            return worker_session::settle_activity_heartbeat(
16160                session,
16161                result,
16162                &self.task_id,
16163                &self.activity_attempt_id,
16164                &self.lease_owner,
16165            );
16166        }
16167        self.client
16168            .heartbeat_activity_task(
16169                &self.task_id,
16170                &self.activity_attempt_id,
16171                &self.lease_owner,
16172                details,
16173            )
16174            .await
16175    }
16176}
16177
16178fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
16179    validate_payload_codec(codec)?;
16180    match value {
16181        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
16182            value, codec,
16183        )?)),
16184        None => Ok(AvroValue::Array(Vec::new())),
16185    }
16186}
16187
16188fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
16189    let Some(signal_name) = task
16190        .signal_name
16191        .as_deref()
16192        .filter(|value| !value.is_empty())
16193    else {
16194        return Ok(None);
16195    };
16196    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
16197    let AvroValue::Array(arguments) = decoded else {
16198        unreachable!("normalize_avro_arguments always returns an array");
16199    };
16200
16201    Ok(Some(ResumeSignal {
16202        signal_name: signal_name.to_string(),
16203        arguments,
16204    }))
16205}
16206
16207fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
16208    validate_payload_codec(&task.payload_codec)?;
16209    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
16210    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
16211    for event in &task.history_events {
16212        validate_history_event_payloads(event, &task.payload_codec)?;
16213    }
16214    Ok(())
16215}
16216
16217fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
16218    validate_payload_codec(&task.payload_codec)?;
16219    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
16220}
16221
16222fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
16223    validate_payload_codec(&task.payload_codec)?;
16224    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
16225    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
16226    for event in &task.history_events {
16227        validate_history_event_payloads(event, &task.payload_codec)?;
16228    }
16229
16230    let Some(export) = task.history_export.as_ref() else {
16231        return Ok(());
16232    };
16233    let export_codec = match export.get("payloads") {
16234        Some(payloads) => declared_payload_codec(payloads, "codec")?,
16235        None => None,
16236    }
16237    .unwrap_or(&task.payload_codec);
16238    validate_payload_codec(export_codec)?;
16239
16240    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
16241        for event in events {
16242            let event_type = event
16243                .get("event_type")
16244                .or_else(|| event.get("type"))
16245                .and_then(Value::as_str)
16246                .unwrap_or_default();
16247            if let Some(payload) = event.get("payload") {
16248                validate_history_payloads(event_type, payload, export_codec)?;
16249            }
16250        }
16251    }
16252    for signal in export
16253        .get("signals")
16254        .and_then(Value::as_array)
16255        .into_iter()
16256        .flatten()
16257    {
16258        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
16259        validate_payload_codec(codec)?;
16260        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
16261    }
16262    for activity in export
16263        .get("activities")
16264        .and_then(Value::as_array)
16265        .into_iter()
16266        .flatten()
16267    {
16268        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
16269        validate_payload_codec(codec)?;
16270        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
16271        validate_optional_inbound_payload(activity.get("result"), codec)?;
16272    }
16273    Ok(())
16274}
16275
16276fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
16277    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
16278}
16279
16280fn validate_history_payloads(
16281    event_type: &str,
16282    payload: &Value,
16283    fallback_codec: &str,
16284) -> Result<()> {
16285    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
16286    validate_payload_codec(codec)?;
16287    for field in history_payload_fields(event_type) {
16288        validate_optional_inbound_payload(payload.get(*field), codec)?;
16289    }
16290    Ok(())
16291}
16292
16293const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
16294
16295fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
16296    match event_type {
16297        "ActivityCompleted" => &["result"],
16298        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
16299        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
16300        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
16301        "ChildRunCompleted" => &["result", "output"],
16302        "WorkflowCompleted" => &["output"],
16303        "ServiceCallStarted"
16304        | "ServiceCallCompleted"
16305        | "ServiceCallFailed"
16306        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
16307        _ => &[],
16308    }
16309}
16310
16311fn signal_history_payload(payload: &Value) -> Option<&Value> {
16312    SIGNAL_HISTORY_PAYLOAD_FIELDS
16313        .iter()
16314        .find_map(|field| payload.get(*field))
16315}
16316
16317fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
16318    match value.get(field) {
16319        None => Ok(None),
16320        Some(Value::String(codec)) => Ok(Some(codec)),
16321        Some(_) => Err(invalid_payload_envelope()),
16322    }
16323}
16324
16325fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
16326    validate_payload_codec(codec)?;
16327    if let Some(value) = value.filter(|value| !value.is_null()) {
16328        decode_wire_avro_value(value, codec)?;
16329    }
16330    Ok(())
16331}
16332
16333fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
16334    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
16335        invalid_recorded_history(
16336            "parallel_group_metadata_invalid",
16337            sequence,
16338            "non-empty parallel_group_id",
16339            &payload.to_string(),
16340            "parallel-group history is missing its stable identity",
16341        )
16342    })?;
16343    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
16344        invalid_recorded_history(
16345            "parallel_group_metadata_invalid",
16346            sequence,
16347            "activity, child, timer, signal, condition, or mixed group kind",
16348            &payload.to_string(),
16349            "parallel-group history is missing its group kind",
16350        )
16351    })?;
16352    if !matches!(
16353        kind.as_str(),
16354        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
16355    ) {
16356        return Err(invalid_recorded_history(
16357            "parallel_group_metadata_invalid",
16358            sequence,
16359            "activity, child, timer, signal, condition, or mixed group kind",
16360            &kind,
16361            "parallel-group history contains an unsupported group kind",
16362        ));
16363    }
16364    let base_sequence = payload
16365        .get("parallel_group_base_sequence")
16366        .and_then(value_as_u64)
16367        .filter(|value| *value > 0)
16368        .ok_or_else(|| {
16369            invalid_recorded_history(
16370                "parallel_group_metadata_invalid",
16371                sequence,
16372                "positive parallel_group_base_sequence",
16373                &payload.to_string(),
16374                "parallel-group history contains an invalid base sequence",
16375            )
16376        })?;
16377    let size = payload
16378        .get("parallel_group_size")
16379        .and_then(value_as_u64)
16380        .and_then(|value| usize::try_from(value).ok())
16381        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
16382        .ok_or_else(|| {
16383            invalid_recorded_history(
16384                "parallel_group_metadata_invalid",
16385                sequence,
16386                "bounded positive parallel_group_size",
16387                &payload.to_string(),
16388                "parallel-group history contains an invalid group size",
16389            )
16390        })?;
16391    let index = payload
16392        .get("parallel_group_index")
16393        .and_then(value_as_u64)
16394        .and_then(|value| usize::try_from(value).ok())
16395        .filter(|value| *value < size)
16396        .ok_or_else(|| {
16397            invalid_recorded_history(
16398                "parallel_group_metadata_invalid",
16399                sequence,
16400                "parallel_group_index within group bounds",
16401                &payload.to_string(),
16402                "parallel-group history contains an invalid member index",
16403            )
16404        })?;
16405    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
16406        return Err(invalid_recorded_history(
16407            "parallel_group_metadata_invalid",
16408            sequence,
16409            "base sequence plus member index equals workflow sequence",
16410            &payload.to_string(),
16411            "parallel-group path does not preserve durable workflow position",
16412        ));
16413    }
16414    let mode = payload
16415        .get("parallel_group_mode")
16416        .and_then(Value::as_str)
16417        .unwrap_or("all");
16418    if !matches!(mode, "all" | "select") {
16419        return Err(invalid_recorded_history(
16420            "parallel_group_metadata_invalid",
16421            sequence,
16422            "parallel group mode all or select",
16423            mode,
16424            "parallel-group history contains an unsupported group mode",
16425        ));
16426    }
16427    let expected_id = if mode == "select" {
16428        format!("select-calls:{base_sequence}:{size}")
16429    } else {
16430        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
16431    };
16432    if group_id != expected_id {
16433        return Err(invalid_recorded_history(
16434            "parallel_group_metadata_invalid",
16435            sequence,
16436            &expected_id,
16437            &group_id,
16438            "parallel-group history contains an incompatible stable group ID",
16439        ));
16440    }
16441    let selection_member_key = if mode == "select" {
16442        Some(selection_key_from_value(
16443            payload.get("selection_member_key"),
16444            sequence,
16445        )?)
16446    } else {
16447        None
16448    };
16449    let selection_member_index = if mode == "select" {
16450        Some(required_parallel_usize(
16451            payload,
16452            "selection_member_index",
16453            sequence,
16454        )?)
16455    } else {
16456        None
16457    };
16458    let selection_member_base_sequence = if mode == "select" {
16459        Some(
16460            payload
16461                .get("selection_member_base_sequence")
16462                .and_then(value_as_u64)
16463                .filter(|value| *value >= base_sequence)
16464                .ok_or_else(|| {
16465                    invalid_recorded_history(
16466                        "parallel_group_metadata_invalid",
16467                        sequence,
16468                        "selection member base within its group",
16469                        &payload.to_string(),
16470                        "selection history contains an invalid member base sequence",
16471                    )
16472                })?,
16473        )
16474    } else {
16475        None
16476    };
16477    let selection_member_size = if mode == "select" {
16478        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
16479        if member_size == 0 {
16480            return Err(invalid_recorded_history(
16481                "parallel_group_metadata_invalid",
16482                sequence,
16483                "positive selection member size",
16484                &payload.to_string(),
16485                "selection history contains an invalid member size",
16486            ));
16487        }
16488        Some(member_size)
16489    } else {
16490        None
16491    };
16492    let selection_member_kind = if mode == "select" {
16493        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
16494            invalid_recorded_history(
16495                "parallel_group_metadata_invalid",
16496                sequence,
16497                "selection member operation kind",
16498                &payload.to_string(),
16499                "selection history is missing its authored member kind",
16500            )
16501        })?;
16502        if !matches!(
16503            kind.as_str(),
16504            "activity" | "child" | "timer" | "signal" | "condition" | "group"
16505        ) {
16506            return Err(invalid_recorded_history(
16507                "parallel_group_metadata_invalid",
16508                sequence,
16509                "activity, child, timer, signal, condition, or group selection member kind",
16510                &kind,
16511                "selection history contains an unsupported member kind",
16512            ));
16513        }
16514        Some(kind)
16515    } else {
16516        None
16517    };
16518    if let (Some(member_base), Some(member_size)) =
16519        (selection_member_base_sequence, selection_member_size)
16520    {
16521        let member_end = member_base
16522            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
16523            .ok_or_else(|| {
16524                invalid_recorded_history(
16525                    "parallel_group_metadata_invalid",
16526                    sequence,
16527                    "bounded selection member range",
16528                    &payload.to_string(),
16529                    "selection member range overflowed",
16530                )
16531            })?;
16532        let group_end = base_sequence
16533            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
16534            .unwrap_or(u64::MAX);
16535        if sequence < member_base || sequence >= member_end || member_end > group_end {
16536            return Err(invalid_recorded_history(
16537                "parallel_group_metadata_invalid",
16538                sequence,
16539                "workflow sequence within one bounded selection member",
16540                &payload.to_string(),
16541                "selection member range does not contain its durable leaf",
16542            ));
16543        }
16544    }
16545    Ok(ParallelGroupMetadata {
16546        parallel_group_id: group_id,
16547        parallel_group_kind: kind,
16548        parallel_group_base_sequence: base_sequence,
16549        parallel_group_size: size,
16550        parallel_group_index: index,
16551        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
16552        selection_member_key,
16553        selection_member_index,
16554        selection_member_base_sequence,
16555        selection_member_size,
16556        selection_member_kind,
16557    })
16558}
16559
16560fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
16561    payload
16562        .get(field)
16563        .and_then(value_as_u64)
16564        .and_then(|value| usize::try_from(value).ok())
16565        .ok_or_else(|| {
16566            invalid_recorded_history(
16567                "parallel_group_metadata_invalid",
16568                sequence,
16569                &format!("non-negative integer {field}"),
16570                &payload.to_string(),
16571                "selection history contains invalid member metadata",
16572            )
16573        })
16574}
16575
16576fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
16577    match value {
16578        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
16579        Some(value) => value_as_u64(value)
16580            .and_then(|value| usize::try_from(value).ok())
16581            .map(SelectionKey::Index)
16582            .ok_or_else(|| {
16583                invalid_recorded_history(
16584                    "selection_member_key_invalid",
16585                    sequence,
16586                    "non-empty string or non-negative integer member key",
16587                    &value.to_string(),
16588                    "selection history contains an invalid member key",
16589                )
16590            }),
16591        None => Err(invalid_recorded_history(
16592            "selection_member_key_missing",
16593            sequence,
16594            "selection_member_key",
16595            "<missing>",
16596            "selection history is missing its stable member key",
16597        )),
16598    }
16599}
16600
16601fn recorded_parallel_group_path(
16602    events: &[&HistoryEvent],
16603    sequence: u64,
16604) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16605    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
16606    for event in events {
16607        let payload = &event.payload;
16608        let has_metadata = payload.get("parallel_group_path").is_some()
16609            || payload.get("parallel_group_id").is_some()
16610            || payload.get("parallel_group_kind").is_some()
16611            || payload.get("parallel_group_base_sequence").is_some()
16612            || payload.get("parallel_group_size").is_some()
16613            || payload.get("parallel_group_index").is_some()
16614            || payload.get("parallel_group_mode").is_some()
16615            || payload.get("selection_member_key").is_some();
16616        if !has_metadata {
16617            continue;
16618        }
16619
16620        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16621        let path = match payload.get("parallel_group_path") {
16622            None => vec![top_level.clone()],
16623            Some(Value::Array(entries)) if !entries.is_empty() => entries
16624                .iter()
16625                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16626                .collect::<Result<Vec<_>>>()?,
16627            Some(value) => {
16628                return Err(invalid_recorded_history(
16629                    "parallel_group_metadata_invalid",
16630                    sequence,
16631                    "non-empty parallel_group_path list",
16632                    &value.to_string(),
16633                    "parallel-group history contains an invalid group path",
16634                ));
16635            }
16636        };
16637        if path.last() != Some(&top_level) {
16638            return Err(invalid_recorded_history(
16639                "parallel_group_metadata_invalid",
16640                sequence,
16641                &serde_json::to_string(&path.last()).unwrap_or_default(),
16642                &serde_json::to_string(&top_level).unwrap_or_default(),
16643                "parallel-group top-level fields do not match the innermost path entry",
16644            ));
16645        }
16646        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16647            return Err(invalid_recorded_history(
16648                "parallel_group_history_conflict",
16649                sequence,
16650                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16651                &serde_json::to_string(&path).unwrap_or_default(),
16652                "parallel-group metadata changed between scheduling and resolution history",
16653            ));
16654        }
16655        recorded = Some(path);
16656    }
16657    Ok(recorded)
16658}
16659
16660fn recorded_commands(
16661    events: &[HistoryEvent],
16662    fallback_codec: &str,
16663    parent: WorkflowIdentity,
16664) -> Result<Vec<RecordedCommand>> {
16665    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16666    let mut last_new_sequence = None;
16667
16668    for event in events {
16669        let is_activity = matches!(
16670            event.event_type.as_str(),
16671            "ActivityScheduled"
16672                | "ActivityStarted"
16673                | "ActivityHeartbeatRecorded"
16674                | "ActivityRetryScheduled"
16675                | "ActivityCompleted"
16676                | "ActivityFailed"
16677                | "ActivityCancelled"
16678                | "ActivityTimedOut"
16679        );
16680        let is_workflow_timer = matches!(
16681            event.event_type.as_str(),
16682            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16683        ) && !is_internal_timer_event(event);
16684        let is_child_workflow = matches!(
16685            event.event_type.as_str(),
16686            "ChildWorkflowScheduled"
16687                | "ChildRunStarted"
16688                | "ChildRunCompleted"
16689                | "ChildRunFailed"
16690                | "ChildRunCancelled"
16691                | "ChildRunTerminated"
16692        );
16693        let is_signal_wait = is_recorded_signal_wait_event(event);
16694        let is_condition_wait = is_recorded_condition_wait_event(event);
16695        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16696        let is_side_effect = event.event_type == "SideEffectRecorded";
16697        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16698        let is_memo = event.event_type == "MemoUpserted";
16699        let is_service_operation = nexus::is_service_event(event);
16700        if !is_activity
16701            && !is_workflow_timer
16702            && !is_child_workflow
16703            && !is_signal_wait
16704            && !is_condition_wait
16705            && !is_search_attributes
16706            && !is_side_effect
16707            && !is_version_marker
16708            && !is_memo
16709            && !is_service_operation
16710        {
16711            continue;
16712        }
16713
16714        let sequence = durable_event_sequence(event).ok_or_else(|| {
16715            Error::NonDeterministicReplay(ReplayFailure::new(
16716                "durable_command_sequence_missing",
16717                None,
16718                Some("positive workflow sequence".to_string()),
16719                Some(event.event_type.clone()),
16720                "durable command history event has no workflow sequence",
16721            ))
16722        })?;
16723        if sequence == 0 {
16724            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16725                "durable_command_sequence_invalid",
16726                Some(sequence),
16727                Some("positive workflow sequence".to_string()),
16728                Some(sequence.to_string()),
16729                "durable command history uses an invalid workflow sequence",
16730            )));
16731        }
16732        if !events_by_sequence.contains_key(&sequence) {
16733            if let Some(previous) = last_new_sequence {
16734                if sequence < previous {
16735                    return Err(invalid_recorded_history(
16736                        "durable_command_sequence_mismatch",
16737                        sequence,
16738                        &format!("workflow sequence greater than {previous}"),
16739                        &sequence.to_string(),
16740                        "durable commands are not strictly ordered by their recorded workflow sequence",
16741                    ));
16742                }
16743            }
16744            last_new_sequence = Some(sequence);
16745        }
16746        events_by_sequence.entry(sequence).or_default().push(event);
16747    }
16748
16749    let commands: Vec<RecordedCommand> = events_by_sequence
16750        .into_iter()
16751        .map(|(sequence, sequence_events)| {
16752            let activity_events: Vec<_> = sequence_events
16753                .iter()
16754                .copied()
16755                .filter(|event| event.event_type.starts_with("Activity"))
16756                .collect();
16757            let timer_events: Vec<_> = sequence_events
16758                .iter()
16759                .copied()
16760                .filter(|event| event.event_type.starts_with("Timer"))
16761                .collect();
16762            let child_events: Vec<_> = sequence_events
16763                .iter()
16764                .copied()
16765                .filter(|event| {
16766                    event.event_type == "ChildWorkflowScheduled"
16767                        || event.event_type.starts_with("ChildRun")
16768                })
16769                .collect();
16770            let signal_wait_events: Vec<_> = sequence_events
16771                .iter()
16772                .copied()
16773                .filter(|event| is_recorded_signal_wait_event(event))
16774                .collect();
16775            let condition_wait_events: Vec<_> = sequence_events
16776                .iter()
16777                .copied()
16778                .filter(|event| is_recorded_condition_wait_event(event))
16779                .collect();
16780            let search_attribute_events: Vec<_> = sequence_events
16781                .iter()
16782                .copied()
16783                .filter(|event| event.event_type == "SearchAttributesUpserted")
16784                .collect();
16785            let side_effect_events: Vec<_> = sequence_events
16786                .iter()
16787                .copied()
16788                .filter(|event| event.event_type == "SideEffectRecorded")
16789                .collect();
16790            let version_marker_events: Vec<_> = sequence_events
16791                .iter()
16792                .copied()
16793                .filter(|event| event.event_type == "VersionMarkerRecorded")
16794                .collect();
16795            let memo_events: Vec<_> = sequence_events
16796                .iter()
16797                .copied()
16798                .filter(|event| event.event_type == "MemoUpserted")
16799                .collect();
16800            let service_events: Vec<_> = sequence_events.iter().copied()
16801                .filter(|event| nexus::is_service_event(event)).collect();
16802
16803            let command_kind_count = usize::from(!activity_events.is_empty())
16804                + usize::from(!timer_events.is_empty())
16805                + usize::from(!child_events.is_empty())
16806                + usize::from(!signal_wait_events.is_empty())
16807                + usize::from(!condition_wait_events.is_empty())
16808                + usize::from(!search_attribute_events.is_empty())
16809                + usize::from(!side_effect_events.is_empty())
16810                + usize::from(!version_marker_events.is_empty())
16811                + usize::from(!memo_events.is_empty())
16812                + usize::from(!service_events.is_empty());
16813            if command_kind_count > 1 {
16814                let actual = [
16815                    (!activity_events.is_empty()).then_some("activity"),
16816                    (!timer_events.is_empty()).then_some("timer"),
16817                    (!child_events.is_empty()).then_some("child workflow"),
16818                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16819                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16820                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16821                    (!side_effect_events.is_empty()).then_some("side effect"),
16822                    (!version_marker_events.is_empty()).then_some("version marker"),
16823                    (!memo_events.is_empty()).then_some("memo upsert"),
16824                    (!service_events.is_empty()).then_some("service operation"),
16825                ]
16826                .into_iter()
16827                .flatten()
16828                .collect::<Vec<_>>()
16829                .join(" and ");
16830                return Err(invalid_recorded_history(
16831                    "durable_command_sequence_collision",
16832                    sequence,
16833                    "one durable command kind",
16834                    &actual,
16835                    "one workflow sequence records more than one durable command kind",
16836                ));
16837            }
16838
16839            if !service_events.is_empty() {
16840                return Ok(RecordedCommand::ServiceOperation {
16841                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16842                });
16843            }
16844
16845            if !activity_events.is_empty() {
16846                let parallel_group_path =
16847                    recorded_parallel_group_path(&activity_events, sequence)?;
16848                let scheduled_count = activity_events
16849                    .iter()
16850                    .filter(|event| event.event_type == "ActivityScheduled")
16851                    .count();
16852                if scheduled_count > 1 {
16853                    return Err(invalid_recorded_history(
16854                        "duplicate_activity_schedule",
16855                        sequence,
16856                        "at most one ActivityScheduled event",
16857                        "multiple ActivityScheduled events",
16858                        "activity history schedules more than one command at one workflow sequence",
16859                    ));
16860                }
16861                let activity_type = activity_events.iter().find_map(|event| {
16862                    event
16863                        .payload
16864                        .get("activity_type")
16865                        .or_else(|| event.payload.get("activity_name"))
16866                        .and_then(Value::as_str)
16867                        .map(str::to_string)
16868                });
16869                if activity_events.iter().filter_map(|event| {
16870                    event
16871                        .payload
16872                        .get("activity_type")
16873                        .or_else(|| event.payload.get("activity_name"))
16874                        .and_then(Value::as_str)
16875                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16876                    return Err(invalid_recorded_history(
16877                        "activity_identity_mismatch",
16878                        sequence,
16879                        activity_type.as_deref().unwrap_or("one activity identity"),
16880                        "conflicting activity identities",
16881                        "activity lifecycle events at one workflow sequence disagree on identity",
16882                    ));
16883                }
16884                let terminal: Vec<_> = activity_events
16885                    .iter()
16886                    .copied()
16887                    .filter(|event| {
16888                        matches!(
16889                            event.event_type.as_str(),
16890                            "ActivityCompleted"
16891                                | "ActivityFailed"
16892                                | "ActivityCancelled"
16893                                | "ActivityTimedOut"
16894                        )
16895                    })
16896                    .collect();
16897                let duplicate_delivery = terminal.first().is_some_and(|first| {
16898                    terminal.iter().all(|event| {
16899                        event.event_type == first.event_type && event.payload == first.payload
16900                    })
16901                });
16902                if terminal.len() > 1 && !duplicate_delivery {
16903                    return Err(invalid_recorded_history(
16904                        "duplicate_activity_terminal_event",
16905                        sequence,
16906                        "at most one terminal activity event",
16907                        "multiple terminal activity events",
16908                        "activity history settles one command more than once",
16909                    ));
16910                }
16911                let outcome = terminal
16912                    .first()
16913                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16914                    .transpose()?;
16915                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16916                let activity_snapshot = activity_events
16917                    .iter()
16918                    .find(|event| event.event_type == "ActivityScheduled")
16919                    .and_then(|event| event.payload.get("activity"))
16920                    .and_then(Value::as_object);
16921                let options = Some(match activity_snapshot {
16922                    Some(activity) => RecordedActivityOptions {
16923                        task_queue: recorded_optional_string(activity, "queue"),
16924                        execution_mode,
16925                        retry_policy: recorded_activity_retry_snapshot(
16926                            activity.get("retry_policy"),
16927                        ),
16928                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16929                    },
16930                    None => RecordedActivityOptions {
16931                        task_queue: RecordedSnapshotValue::Unknown,
16932                        execution_mode,
16933                        retry_policy: recorded_activity_retry_snapshot(None),
16934                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16935                    },
16936                });
16937                return Ok(RecordedCommand::Activity {
16938                    sequence,
16939                    activity_type,
16940                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16941                    options,
16942                    outcome,
16943                    parallel_group_path,
16944                });
16945            }
16946
16947            if !child_events.is_empty() {
16948                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16949                let scheduled: Vec<_> = child_events
16950                    .iter()
16951                    .copied()
16952                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16953                    .collect();
16954                if scheduled.len() != 1 {
16955                    return Err(invalid_recorded_history(
16956                        "child_workflow_schedule_missing_or_duplicate",
16957                        sequence,
16958                        "one ChildWorkflowScheduled event",
16959                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16960                        "child workflow replay requires exactly one recorded schedule event",
16961                    ));
16962                }
16963                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16964                let workflow_type = child_events.iter().find_map(|event| {
16965                    event
16966                        .payload
16967                        .get("child_workflow_type")
16968                        .or_else(|| event.payload.get("workflow_type"))
16969                        .and_then(Value::as_str)
16970                        .filter(|value| !value.is_empty())
16971                        .map(str::to_string)
16972                });
16973                if child_events
16974                    .iter()
16975                    .filter_map(|event| {
16976                        event
16977                            .payload
16978                            .get("child_workflow_type")
16979                            .or_else(|| event.payload.get("workflow_type"))
16980                            .and_then(Value::as_str)
16981                    })
16982                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
16983                {
16984                    return Err(invalid_recorded_history(
16985                        "child_workflow_identity_mismatch",
16986                        sequence,
16987                        workflow_type
16988                            .as_deref()
16989                            .unwrap_or("one child workflow type"),
16990                        "conflicting child workflow types",
16991                        "child workflow lifecycle events at one sequence disagree on type",
16992                    ));
16993                }
16994                let mut outcomes = child_workflow_outcomes(
16995                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
16996                    fallback_codec,
16997                    parent.clone(),
16998                )?;
16999                let terminal_events = child_events
17000                    .iter()
17001                    .copied()
17002                    .filter(|event| event.event_type.starts_with("ChildRun"))
17003                    .collect::<Vec<_>>();
17004                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
17005                    terminal_events.iter().all(|event| {
17006                        event.event_type == first.event_type && event.payload == first.payload
17007                    })
17008                });
17009                if outcomes.len() > 1 && !duplicate_delivery {
17010                    return Err(invalid_recorded_history(
17011                        "duplicate_child_workflow_terminal_event",
17012                        sequence,
17013                        "at most one terminal child event",
17014                        "multiple terminal child events",
17015                        "child workflow history settles one command more than once",
17016                    ));
17017                }
17018                return Ok(RecordedCommand::ChildWorkflow {
17019                    sequence,
17020                    workflow_type,
17021                    policies,
17022                    outcome: outcomes.pop(),
17023                    parallel_group_path,
17024                });
17025            }
17026
17027            if !signal_wait_events.is_empty() {
17028                let opened: Vec<_> = signal_wait_events
17029                    .iter()
17030                    .copied()
17031                    .filter(|event| event.event_type == "SignalWaitOpened")
17032                    .collect();
17033                if opened.len() != 1 {
17034                    return Err(invalid_recorded_history(
17035                        "signal_wait_open_missing_or_duplicate",
17036                        sequence,
17037                        "one SignalWaitOpened event",
17038                        &format!("{} SignalWaitOpened events", opened.len()),
17039                        "signal replay requires exactly one canonical wait-open event",
17040                    ));
17041                }
17042
17043                let applied: Vec<_> = signal_wait_events
17044                    .iter()
17045                    .copied()
17046                    .filter(|event| event.event_type == "SignalApplied")
17047                    .collect();
17048                if applied.len() > 1 {
17049                    return Err(invalid_recorded_history(
17050                        "duplicate_signal_wait_apply",
17051                        sequence,
17052                        "at most one SignalApplied event",
17053                        "multiple SignalApplied events",
17054                        "signal history applies one durable wait more than once",
17055                    ));
17056                }
17057
17058                let signal_names = signal_wait_events
17059                    .iter()
17060                    .map(|event| required_signal_wait_name(event, sequence))
17061                    .collect::<Result<Vec<_>>>()?;
17062                let signal_name = signal_names
17063                    .first()
17064                    .expect("signal wait events are not empty")
17065                    .clone();
17066                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17067                    return Err(invalid_recorded_history(
17068                        "signal_wait_identity_mismatch",
17069                        sequence,
17070                        &signal_name,
17071                        "conflicting signal names",
17072                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17073                    ));
17074                }
17075                let value = applied
17076                    .first()
17077                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17078                    .transpose()?;
17079                return Ok(RecordedCommand::SignalWait {
17080                    sequence,
17081                    signal_name,
17082                    value,
17083                    parallel_group_path: recorded_parallel_group_path(
17084                        &signal_wait_events,
17085                        sequence,
17086                    )?,
17087                });
17088            }
17089
17090            if !condition_wait_events.is_empty() {
17091                return recorded_condition_wait(
17092                    sequence,
17093                    &condition_wait_events,
17094                    events,
17095                );
17096            }
17097
17098            if !search_attribute_events.is_empty() {
17099                if search_attribute_events.len() != 1 {
17100                    return Err(invalid_recorded_history(
17101                        "duplicate_search_attribute_update",
17102                        sequence,
17103                        "one SearchAttributesUpserted event",
17104                        &format!(
17105                            "{} SearchAttributesUpserted events",
17106                            search_attribute_events.len()
17107                        ),
17108                        "search-attribute history records one workflow command more than once",
17109                    ));
17110                }
17111                let payload = &search_attribute_events[0].payload;
17112                let attributes = payload
17113                    .get("attributes")
17114                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17115                    .cloned()
17116                    .ok_or_else(|| {
17117                        invalid_recorded_history(
17118                            "search_attribute_update_missing",
17119                            sequence,
17120                            "non-empty attributes object",
17121                            "missing or invalid attributes",
17122                            "search-attribute history is missing its recorded mutation",
17123                        )
17124                    })?;
17125                let attribute_types =
17126                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17127                return Ok(RecordedCommand::SearchAttributes {
17128                    sequence,
17129                    attributes,
17130                    attribute_types,
17131                });
17132            }
17133
17134            if !side_effect_events.is_empty() {
17135                if side_effect_events.len() != 1 {
17136                    return Err(invalid_recorded_history(
17137                        "duplicate_side_effect_record",
17138                        sequence,
17139                        "one SideEffectRecorded event",
17140                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17141                        "side-effect history records one workflow command more than once",
17142                    ));
17143                }
17144                let event = side_effect_events[0];
17145                let result = event.payload.get("result").ok_or_else(|| {
17146                    invalid_recorded_history(
17147                        "side_effect_result_missing",
17148                        sequence,
17149                        "recorded result payload",
17150                        "missing result",
17151                        "side-effect history is missing its recorded value",
17152                    )
17153                })?;
17154                let has_published_envelope = result.as_str().is_some()
17155                    || result.as_object().is_some_and(|envelope| {
17156                        envelope.get("codec").and_then(Value::as_str).is_some()
17157                            && envelope.get("blob").and_then(Value::as_str).is_some()
17158                    });
17159                if !has_published_envelope {
17160                    return Err(invalid_recorded_history(
17161                        "side_effect_payload_malformed",
17162                        sequence,
17163                        "payload blob or {codec, blob} envelope",
17164                        &result.to_string(),
17165                        "side-effect history result does not use a published payload envelope",
17166                    ));
17167                }
17168                let codec = event
17169                    .payload
17170                    .get("payload_codec")
17171                    .and_then(Value::as_str)
17172                    .unwrap_or(fallback_codec);
17173                let value = decode_wire_avro_value(result, codec).map_err(|error| {
17174                    if error.to_string().contains("unsupported_payload_codec") {
17175                        return error;
17176                    }
17177
17178                    invalid_recorded_history(
17179                        "side_effect_payload_incompatible",
17180                        sequence,
17181                        &format!("valid {codec} payload envelope"),
17182                        &error.to_string(),
17183                        "side-effect history payload cannot be decoded with its recorded codec",
17184                    )
17185                })?;
17186                return Ok(RecordedCommand::SideEffect { sequence, value });
17187            }
17188
17189            if !version_marker_events.is_empty() {
17190                if version_marker_events.len() != 1 {
17191                    return Err(invalid_recorded_history(
17192                        "duplicate_version_marker_record",
17193                        sequence,
17194                        "one VersionMarkerRecorded event",
17195                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
17196                        "version-marker history records one workflow command more than once",
17197                    ));
17198                }
17199                let payload = &version_marker_events[0].payload;
17200                let change_id = payload
17201                    .get("change_id")
17202                    .and_then(Value::as_str)
17203                    .filter(|value| !value.is_empty())
17204                    .map(str::to_string)
17205                    .ok_or_else(|| {
17206                        invalid_recorded_history(
17207                            "version_marker_field_missing",
17208                            sequence,
17209                            "non-empty change_id",
17210                            "missing or invalid change_id",
17211                            "version-marker history is missing its stable change ID",
17212                        )
17213                    })?;
17214                let version = required_version_i32(payload, "version", sequence)?;
17215                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
17216                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
17217                if min_supported > max_supported || version < min_supported || version > max_supported {
17218                    return Err(invalid_recorded_history(
17219                        "version_marker_history_range_invalid",
17220                        sequence,
17221                        "min_supported <= version <= max_supported",
17222                        &format!("{min_supported} <= {version} <= {max_supported}"),
17223                        "recorded version marker contains an internally incompatible range",
17224                    ));
17225                }
17226                return Ok(RecordedCommand::VersionMarker {
17227                    sequence,
17228                    change_id,
17229                    version,
17230                });
17231            }
17232
17233            if !memo_events.is_empty() {
17234                if memo_events.len() != 1 {
17235                    return Err(invalid_recorded_history(
17236                        "duplicate_memo_upsert_record",
17237                        sequence,
17238                        "one MemoUpserted event",
17239                        &format!("{} MemoUpserted events", memo_events.len()),
17240                        "memo history records one workflow update more than once",
17241                    ));
17242                }
17243                let payload = &memo_events[0].payload;
17244                let entries = payload.get("entries").cloned().ok_or_else(|| {
17245                    invalid_recorded_history(
17246                        "memo_entries_missing",
17247                        sequence,
17248                        "memo entries object",
17249                        "missing entries",
17250                        "MemoUpserted history is missing replay identity entries",
17251                    )
17252                })?;
17253                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
17254                    invalid_recorded_history(
17255                        "memo_entries_invalid",
17256                        sequence,
17257                        "valid canonical memo entries",
17258                        &error.to_string(),
17259                        "MemoUpserted history contains invalid replay identity entries",
17260                    )
17261                })?;
17262                let merged = payload.get("merged").cloned().ok_or_else(|| {
17263                    invalid_recorded_history(
17264                        "memo_merged_projection_missing",
17265                        sequence,
17266                        "merged memo projection",
17267                        "missing merged",
17268                        "MemoUpserted history is missing its merged projection",
17269                    )
17270                })?;
17271                decode_memo_history_map(&merged, false).map_err(|error| {
17272                    invalid_recorded_history(
17273                        "memo_merged_projection_invalid",
17274                        sequence,
17275                        "valid merged memo projection",
17276                        &error.to_string(),
17277                        "MemoUpserted history contains an invalid merged projection",
17278                    )
17279                })?;
17280
17281                return Ok(RecordedCommand::Memo { sequence, entries });
17282            }
17283            let scheduled: Vec<_> = timer_events
17284                .iter()
17285                .copied()
17286                .filter(|event| event.event_type == "TimerScheduled")
17287                .collect();
17288            let fired: Vec<_> = timer_events
17289                .iter()
17290                .copied()
17291                .filter(|event| event.event_type == "TimerFired")
17292                .collect();
17293            if scheduled.len() != 1 {
17294                return Err(invalid_recorded_history(
17295                    "timer_schedule_missing_or_duplicate",
17296                    sequence,
17297                    "one TimerScheduled event",
17298                    &format!("{} TimerScheduled events", scheduled.len()),
17299                    "timer replay requires exactly one recorded schedule event",
17300                ));
17301            }
17302            if fired.len() > 1 {
17303                return Err(invalid_recorded_history(
17304                    "duplicate_timer_fire",
17305                    sequence,
17306                    "at most one TimerFired event",
17307                    "multiple TimerFired events",
17308                    "timer history contains more than one fire event for a workflow sequence",
17309                ));
17310            }
17311
17312            let scheduled = scheduled[0];
17313            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17314            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17315            if let Some(fired) = fired.first() {
17316                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17317                if fired_timer_id != timer_id {
17318                    return Err(invalid_recorded_history(
17319                        "timer_identity_mismatch",
17320                        sequence,
17321                        &timer_id,
17322                        &fired_timer_id,
17323                        "TimerFired does not correspond to the recorded TimerScheduled event",
17324                    ));
17325                }
17326                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17327                if fired_delay != delay_seconds {
17328                    return Err(invalid_recorded_history(
17329                        "timer_history_delay_mismatch",
17330                        sequence,
17331                        &delay_seconds.to_string(),
17332                        &fired_delay.to_string(),
17333                        "TimerScheduled and TimerFired record different delays",
17334                    ));
17335                }
17336            }
17337
17338            Ok(RecordedCommand::Timer {
17339                sequence,
17340                delay_seconds,
17341                fired: !fired.is_empty(),
17342                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
17343            })
17344        })
17345        .collect::<Result<_>>()?;
17346
17347    let mut marker_decisions = HashMap::new();
17348    for command in &commands {
17349        if let RecordedCommand::VersionMarker {
17350            sequence,
17351            change_id,
17352            version,
17353        } = command
17354        {
17355            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
17356                if version != first_version {
17357                    return Err(invalid_recorded_history(
17358                        "version_marker_conflict",
17359                        *sequence,
17360                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
17361                        &format!("version {version} at sequence {sequence}"),
17362                        "workflow history contains conflicting decisions for one stable change ID",
17363                    ));
17364                }
17365            } else {
17366                marker_decisions.insert(change_id.clone(), (*version, *sequence));
17367            }
17368        }
17369    }
17370
17371    Ok(commands)
17372}
17373
17374fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
17375    payload
17376        .get(field)
17377        .and_then(Value::as_i64)
17378        .and_then(|value| i32::try_from(value).ok())
17379        .ok_or_else(|| {
17380            invalid_recorded_history(
17381                "version_marker_field_missing",
17382                sequence,
17383                &format!("integer {field}"),
17384                "missing or out-of-range integer",
17385                "version-marker history is missing a required integer field",
17386            )
17387        })
17388}
17389
17390fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
17391    event
17392        .payload
17393        .get("sequence")
17394        .or_else(|| event.payload.get("workflow_sequence"))
17395        .or_else(|| event.raw.get("sequence"))
17396        .or_else(|| event.raw.get("workflow_sequence"))
17397        .and_then(value_as_u64)
17398}
17399
17400fn is_internal_timer_event(event: &HistoryEvent) -> bool {
17401    matches!(
17402        event
17403            .payload
17404            .get("timer_kind")
17405            .or_else(|| event.raw.get("timer_kind"))
17406            .and_then(Value::as_str),
17407        Some("condition_timeout" | "signal_timeout")
17408    )
17409}
17410
17411fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
17412    matches!(
17413        event.event_type.as_str(),
17414        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17415    )
17416}
17417
17418fn recorded_condition_wait(
17419    sequence: u64,
17420    condition_events: &[&HistoryEvent],
17421    all_events: &[HistoryEvent],
17422) -> Result<RecordedCommand> {
17423    let opened = condition_events
17424        .iter()
17425        .copied()
17426        .filter(|event| event.event_type == "ConditionWaitOpened")
17427        .collect::<Vec<_>>();
17428    if opened.len() != 1 {
17429        return Err(invalid_recorded_history(
17430            "condition_wait_open_missing_or_duplicate",
17431            sequence,
17432            "one ConditionWaitOpened event",
17433            &format!("{} ConditionWaitOpened events", opened.len()),
17434            "condition replay requires exactly one canonical wait-open event",
17435        ));
17436    }
17437    let terminal = condition_events
17438        .iter()
17439        .copied()
17440        .filter(|event| {
17441            matches!(
17442                event.event_type.as_str(),
17443                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17444            )
17445        })
17446        .collect::<Vec<_>>();
17447    if terminal.len() > 1 {
17448        return Err(invalid_recorded_history(
17449            "duplicate_condition_wait_terminal_event",
17450            sequence,
17451            "at most one condition terminal event",
17452            "multiple condition terminal events",
17453            "condition history settles one durable wait more than once",
17454        ));
17455    }
17456
17457    let opened = opened[0];
17458    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
17459    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
17460    for event in condition_events
17461        .iter()
17462        .copied()
17463        .filter(|event| !std::ptr::eq(*event, opened))
17464    {
17465        let event_wait_id = required_condition_wait_id(event, sequence)?;
17466        if event_wait_id != condition_wait_id {
17467            return Err(invalid_recorded_history(
17468                "condition_wait_id_mismatch",
17469                sequence,
17470                &condition_wait_id,
17471                &event_wait_id,
17472                "condition lifecycle events at one sequence disagree on wait identity",
17473            ));
17474        }
17475        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
17476        if event_occurrence_id != occurrence_id {
17477            return Err(invalid_recorded_history(
17478                "condition_wait_occurrence_history_mismatch",
17479                sequence,
17480                &occurrence_id,
17481                &event_occurrence_id,
17482                "condition lifecycle events at one sequence disagree on authored occurrence identity",
17483            ));
17484        }
17485    }
17486
17487    let condition_key = optional_non_empty_history_string(opened, "condition_key");
17488    let predicate_identity = opened
17489        .payload
17490        .get("condition_definition_fingerprint")
17491        .and_then(Value::as_str)
17492        .filter(|value| !value.is_empty())
17493        .map(str::to_string)
17494        .ok_or_else(|| {
17495            invalid_recorded_history(
17496                "condition_wait_predicate_fingerprint_missing",
17497                sequence,
17498                "non-empty condition_definition_fingerprint",
17499                &opened.event_type,
17500                "canonical condition history is missing its predicate identity",
17501            )
17502        })?;
17503    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
17504    for event in condition_events
17505        .iter()
17506        .copied()
17507        .filter(|event| !std::ptr::eq(*event, opened))
17508    {
17509        for (field, opened_value) in [
17510            ("condition_key", condition_key.as_deref()),
17511            (
17512                "condition_definition_fingerprint",
17513                Some(predicate_identity.as_str()),
17514            ),
17515        ] {
17516            if let Some(value) = optional_non_empty_history_string(event, field) {
17517                if opened_value.is_some_and(|opened_value| opened_value != value) {
17518                    return Err(invalid_recorded_history(
17519                        "condition_wait_definition_history_mismatch",
17520                        sequence,
17521                        opened_value.unwrap_or_default(),
17522                        &value,
17523                        "condition lifecycle events disagree on the recorded definition",
17524                    ));
17525                }
17526            }
17527        }
17528        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
17529            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
17530                return Err(invalid_recorded_history(
17531                    "condition_wait_definition_history_mismatch",
17532                    sequence,
17533                    &format!("{}s", timeout_seconds.unwrap_or_default()),
17534                    &format!("{event_timeout}s"),
17535                    "condition lifecycle events disagree on the recorded timeout",
17536                ));
17537            }
17538        }
17539    }
17540
17541    let timeout_timer_events = all_events
17542        .iter()
17543        .filter(|event| {
17544            matches!(
17545                event.event_type.as_str(),
17546                "TimerScheduled" | "TimerCancelled" | "TimerFired"
17547            ) && event.payload.get("timer_kind").and_then(Value::as_str)
17548                == Some("condition_timeout")
17549                && event
17550                    .payload
17551                    .get("condition_wait_id")
17552                    .and_then(Value::as_str)
17553                    == Some(condition_wait_id.as_str())
17554        })
17555        .collect::<Vec<_>>();
17556    let scheduled = timeout_timer_events
17557        .iter()
17558        .copied()
17559        .filter(|event| event.event_type == "TimerScheduled")
17560        .collect::<Vec<_>>();
17561    let fired = timeout_timer_events
17562        .iter()
17563        .copied()
17564        .filter(|event| event.event_type == "TimerFired")
17565        .collect::<Vec<_>>();
17566    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
17567        return Err(invalid_recorded_history(
17568            "condition_wait_timeout_history_invalid",
17569            sequence,
17570            "one timeout schedule and at most one fire",
17571            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
17572            "condition timeout history has a missing or duplicate lifecycle event",
17573        ));
17574    }
17575    if let Some(scheduled) = scheduled.first() {
17576        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17577        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17578        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
17579            return Err(invalid_recorded_history(
17580                "condition_wait_timeout_delay_mismatch",
17581                sequence,
17582                &format!("{}s", timeout_seconds.unwrap_or_default()),
17583                &format!("{delay_seconds}s"),
17584                "condition timeout timer differs from the wait definition",
17585            ));
17586        }
17587        if let Some(fired) = fired.first() {
17588            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17589            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17590            if fired_timer_id != timer_id || fired_delay != delay_seconds {
17591                return Err(invalid_recorded_history(
17592                    "condition_wait_timeout_identity_mismatch",
17593                    sequence,
17594                    &format!("{timer_id}:{delay_seconds}s"),
17595                    &format!("{fired_timer_id}:{fired_delay}s"),
17596                    "condition timeout fire does not match its durable schedule",
17597                ));
17598            }
17599        }
17600    }
17601
17602    let result = terminal.first().map(|event| {
17603        if event.event_type == "ConditionWaitTimedOut" {
17604            ConditionWaitResult::TimedOut
17605        } else {
17606            ConditionWaitResult::Satisfied
17607        }
17608    });
17609    let result = if !fired.is_empty() {
17610        if result == Some(ConditionWaitResult::Satisfied) {
17611            return Err(invalid_recorded_history(
17612                "condition_wait_terminal_conflict",
17613                sequence,
17614                "one satisfied or timed-out outcome",
17615                "satisfied event and fired timeout",
17616                "condition history records conflicting terminal outcomes",
17617            ));
17618        }
17619        Some(ConditionWaitResult::TimedOut)
17620    } else {
17621        result
17622    };
17623
17624    Ok(RecordedCommand::ConditionWait {
17625        sequence,
17626        occurrence_id,
17627        condition_key,
17628        predicate_identity,
17629        timeout_seconds,
17630        result,
17631        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17632    })
17633}
17634
17635fn recorded_condition_group_path(
17636    condition_events: &[&HistoryEvent],
17637    all_events: &[HistoryEvent],
17638    sequence: u64,
17639) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17640    let opened = condition_events
17641        .iter()
17642        .copied()
17643        .find(|event| event.event_type == "ConditionWaitOpened")
17644        .expect("canonical condition opener is validated first");
17645    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17646    let previous_events = all_events
17647        .iter()
17648        .take_while(|event| !std::ptr::eq(*event, opened))
17649        .collect::<Vec<_>>();
17650    let originals = previous_events
17651        .iter()
17652        .copied()
17653        .filter(|event| event.event_type == "ConditionWaitOpened")
17654        .filter(|event| {
17655            event
17656                .payload
17657                .get("condition_wait_occurrence_id")
17658                .and_then(Value::as_str)
17659                == Some(occurrence.as_str())
17660        })
17661        .collect::<Vec<_>>();
17662    let Some(original) = originals.first().copied() else {
17663        return recorded_parallel_group_path(condition_events, sequence);
17664    };
17665    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17666    if authored_sequence == sequence {
17667        return recorded_parallel_group_path(condition_events, sequence);
17668    }
17669    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17670    if original_path.is_none() {
17671        return recorded_parallel_group_path(condition_events, sequence);
17672    }
17673    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17674    let identity_matches = [
17675        "condition_key",
17676        "condition_definition_fingerprint",
17677        "timeout_seconds",
17678    ]
17679    .iter()
17680    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17681    let previous = originals
17682        .iter()
17683        .copied()
17684        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17685        .max_by_key(|event| durable_event_sequence(event));
17686    let previously_satisfied = previous.is_some_and(|previous| {
17687        previous_events.iter().any(|event| {
17688            event.event_type == "ConditionWaitSatisfied"
17689                && event.payload.get("condition_wait_id")
17690                    == previous.payload.get("condition_wait_id")
17691                && event.payload.get("condition_wait_occurrence_id")
17692                    == previous.payload.get("condition_wait_occurrence_id")
17693                && durable_event_sequence(event) == durable_event_sequence(previous)
17694        })
17695    });
17696    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17697        return Err(invalid_recorded_history(
17698            "condition_wait_group_reopen_mismatch",
17699            sequence,
17700            "same authored condition and group path after a satisfied physical wait",
17701            &opened.payload.to_string(),
17702            "grouped condition reopen has no matching recorded predecessor",
17703        ));
17704    }
17705    Ok(reopened_path)
17706}
17707
17708fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17709    event
17710        .payload
17711        .get("condition_wait_occurrence_id")
17712        .and_then(Value::as_str)
17713        .filter(|value| !value.is_empty())
17714        .map(str::to_string)
17715        .ok_or_else(|| {
17716            invalid_recorded_history(
17717                "condition_wait_occurrence_id_missing",
17718                sequence,
17719                "non-empty condition_wait_occurrence_id",
17720                &event.event_type,
17721                "condition history is missing authored occurrence identity",
17722            )
17723        })
17724}
17725
17726fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17727    event
17728        .payload
17729        .get("condition_wait_id")
17730        .and_then(Value::as_str)
17731        .filter(|value| !value.is_empty())
17732        .map(str::to_string)
17733        .ok_or_else(|| {
17734            invalid_recorded_history(
17735                "condition_wait_id_missing",
17736                sequence,
17737                "non-empty condition_wait_id",
17738                &event.event_type,
17739                "canonical condition history is missing its durable wait identity",
17740            )
17741        })
17742}
17743
17744fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17745    event
17746        .payload
17747        .get(field)
17748        .and_then(Value::as_str)
17749        .filter(|value| !value.is_empty())
17750        .map(str::to_string)
17751}
17752
17753fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17754    match event.payload.get(field) {
17755        None | Some(Value::Null) => Ok(None),
17756        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17757            invalid_recorded_history(
17758                "condition_wait_definition_invalid",
17759                sequence,
17760                &format!("non-negative integer {field}"),
17761                &value.to_string(),
17762                "condition history contains an invalid numeric definition field",
17763            )
17764        }),
17765    }
17766}
17767
17768fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17769    event
17770        .payload
17771        .get("signal_name")
17772        .or_else(|| event.raw.get("signal_name"))
17773        .and_then(Value::as_str)
17774        .filter(|value| !value.is_empty())
17775        .map(str::to_string)
17776        .ok_or_else(|| {
17777            invalid_recorded_history(
17778                "signal_wait_name_missing",
17779                sequence,
17780                "non-empty signal_name",
17781                &event.event_type,
17782                "canonical signal-wait history is missing its signal identity",
17783            )
17784        })
17785}
17786
17787fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17788    // Applying a buffered control-plane signal has no authored call sequence.
17789    // Its outer sequence orders history events and must not become a wait.
17790    if event.event_type == "SignalApplied"
17791        && event
17792            .payload
17793            .get("signal_wait_id")
17794            .and_then(Value::as_str)
17795            .is_some_and(|id| id.starts_with("signal-command:"))
17796        && event.payload.get("sequence").is_none()
17797        && event.payload.get("workflow_sequence").is_none()
17798    {
17799        return false;
17800    }
17801    matches!(
17802        event.event_type.as_str(),
17803        "SignalWaitOpened" | "SignalApplied"
17804    )
17805}
17806
17807fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17808    event
17809        .payload
17810        .get(field)
17811        .and_then(Value::as_str)
17812        .filter(|value| !value.is_empty())
17813        .map(str::to_string)
17814        .ok_or_else(|| {
17815            invalid_recorded_history(
17816                "timer_history_field_missing",
17817                sequence,
17818                field,
17819                &event.event_type,
17820                "timer history is missing a required identity field",
17821            )
17822        })
17823}
17824
17825fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17826    event
17827        .payload
17828        .get(field)
17829        .and_then(value_as_u64)
17830        .ok_or_else(|| {
17831            invalid_recorded_history(
17832                "timer_history_field_missing",
17833                sequence,
17834                field,
17835                &event.event_type,
17836                "timer history is missing a required numeric field",
17837            )
17838        })
17839}
17840
17841fn recorded_search_attribute_types(
17842    payload: &Value,
17843    attributes: &Value,
17844    sequence: u64,
17845) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17846    let Some(raw_types) = payload.get("attribute_types") else {
17847        // This is the explicit compatibility rule for histories recorded
17848        // before typed identity was persisted. Values still constrain replay;
17849        // the unknown type snapshot does not assert a typed match.
17850        return Ok(RecordedSnapshotValue::Unknown);
17851    };
17852    let Some(raw_types) = raw_types.as_object() else {
17853        return Err(invalid_recorded_history(
17854            "search_attribute_types_malformed",
17855            sequence,
17856            "canonical attribute type map",
17857            &raw_types.to_string(),
17858            "search-attribute history contains malformed type identity",
17859        ));
17860    };
17861    let attribute_keys = attributes
17862        .as_object()
17863        .expect("recorded search attributes were validated as an object");
17864    let mut types = BTreeMap::new();
17865    for (key, value) in raw_types {
17866        let Some(attribute_type) = value.as_str() else {
17867            return Err(invalid_recorded_history(
17868                "search_attribute_types_malformed",
17869                sequence,
17870                "canonical string type name",
17871                &value.to_string(),
17872                "search-attribute history contains a non-string type identity",
17873            ));
17874        };
17875        if !attribute_keys.contains_key(key)
17876            || !matches!(
17877                attribute_type,
17878                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17879            )
17880        {
17881            return Err(invalid_recorded_history(
17882                "search_attribute_types_malformed",
17883                sequence,
17884                "canonical types for keys present in attributes",
17885                &format!("{key}:{attribute_type}"),
17886                "search-attribute history contains unsupported or orphaned type identity",
17887            ));
17888        }
17889        types.insert(key.clone(), attribute_type.to_string());
17890    }
17891    Ok(RecordedSnapshotValue::Known(types))
17892}
17893
17894fn invalid_recorded_history(
17895    reason: &str,
17896    sequence: u64,
17897    expected: &str,
17898    actual: &str,
17899    message: &str,
17900) -> Error {
17901    Error::NonDeterministicReplay(ReplayFailure::new(
17902        reason,
17903        Some(sequence),
17904        Some(expected.to_string()),
17905        Some(actual.to_string()),
17906        message,
17907    ))
17908}
17909
17910type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17911
17912fn activity_outcome(
17913    event: &HistoryEvent,
17914    fallback_codec: &str,
17915    recorded_activity_type: Option<String>,
17916) -> Result<ActivityOutcome> {
17917    if event.event_type == "ActivityCompleted" {
17918        let codec = event
17919            .payload
17920            .get("payload_codec")
17921            .and_then(Value::as_str)
17922            .unwrap_or(fallback_codec);
17923        return Ok(Ok(decode_wire_avro_value(
17924            event.payload.get("result").unwrap_or(&Value::Null),
17925            codec,
17926        )?));
17927    }
17928
17929    let payload = &event.payload;
17930    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17931        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17932        "ActivityCancelled" => (
17933            ActivityFailureKind::Cancelled,
17934            "cancelled",
17935            "activity was cancelled",
17936        ),
17937        "ActivityTimedOut" => (
17938            ActivityFailureKind::TimedOut,
17939            "timeout",
17940            "activity timed out",
17941        ),
17942        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17943    };
17944    let exception = payload
17945        .get("exception")
17946        .filter(|value| !value.is_null())
17947        .cloned();
17948    let failure_category = payload_string(payload, "failure_category");
17949    let timeout_kind = payload_string(payload, "timeout_kind");
17950    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17951        ActivityFailureKind::Failed => failure_category
17952            .clone()
17953            .unwrap_or_else(|| fallback_reason.to_string()),
17954        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17955        ActivityFailureKind::TimedOut => timeout_kind
17956            .clone()
17957            .unwrap_or_else(|| fallback_reason.to_string()),
17958    });
17959    let message = payload_string(payload, "message")
17960        .or_else(|| {
17961            exception
17962                .as_ref()
17963                .and_then(|value| payload_string(value, "message"))
17964        })
17965        .unwrap_or_else(|| fallback_message.to_string());
17966
17967    Ok(Err(ActivityFailure {
17968        kind,
17969        reason,
17970        message,
17971        activity_execution_id: payload_string(payload, "activity_execution_id"),
17972        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17973        activity_type: payload_string(payload, "activity_type")
17974            .or_else(|| payload_string(payload, "activity_name"))
17975            .or(recorded_activity_type),
17976        activity_class: payload_string(payload, "activity_class"),
17977        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17978        failure_id: payload_string(payload, "failure_id"),
17979        failure_category,
17980        timeout_kind,
17981        non_retryable: payload
17982            .get("non_retryable")
17983            .and_then(Value::as_bool)
17984            .unwrap_or(false),
17985        exception_type: payload_string(payload, "exception_type").or_else(|| {
17986            exception
17987                .as_ref()
17988                .and_then(|value| payload_string(value, "type"))
17989        }),
17990        exception_class: payload_string(payload, "exception_class").or_else(|| {
17991            exception
17992                .as_ref()
17993                .and_then(|value| payload_string(value, "class"))
17994        }),
17995        code: payload
17996            .get("code")
17997            .filter(|value| !value.is_null())
17998            .cloned(),
17999        exception,
18000    }))
18001}
18002
18003type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
18004
18005fn child_workflow_outcomes(
18006    events: &[HistoryEvent],
18007    fallback_codec: &str,
18008    parent: WorkflowIdentity,
18009) -> Result<Vec<ChildWorkflowOutcome>> {
18010    let mut outcomes = Vec::new();
18011
18012    for event in events {
18013        let kind = match event.event_type.as_str() {
18014            "ChildRunCompleted" => None,
18015            "ChildRunFailed" => Some((
18016                ChildWorkflowFailureKind::Failed,
18017                "child_workflow",
18018                "child workflow failed",
18019            )),
18020            "ChildRunCancelled" => Some((
18021                ChildWorkflowFailureKind::Cancelled,
18022                "cancelled",
18023                "child workflow was cancelled",
18024            )),
18025            "ChildRunTerminated" => Some((
18026                ChildWorkflowFailureKind::Terminated,
18027                "terminated",
18028                "child workflow was terminated",
18029            )),
18030            _ => continue,
18031        };
18032        let payload = &event.payload;
18033        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
18034        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
18035        let child_workflow_type = payload_string(payload, "child_workflow_type");
18036
18037        if let Some((kind, reason, fallback_message)) = kind {
18038            let exception = payload
18039                .get("exception")
18040                .filter(|value| !value.is_null())
18041                .cloned();
18042            let message = payload_string(payload, "message")
18043                .or_else(|| {
18044                    exception
18045                        .as_ref()
18046                        .and_then(|value| payload_string(value, "message"))
18047                })
18048                .unwrap_or_else(|| fallback_message.to_string());
18049            let exception_type = payload_string(payload, "exception_type").or_else(|| {
18050                exception
18051                    .as_ref()
18052                    .and_then(|value| payload_string(value, "type"))
18053            });
18054            let exception_class = payload_string(payload, "exception_class").or_else(|| {
18055                exception
18056                    .as_ref()
18057                    .and_then(|value| payload_string(value, "class"))
18058            });
18059            outcomes.push(Err(ChildWorkflowFailure {
18060                kind,
18061                reason: reason.to_string(),
18062                message,
18063                parent_workflow_id: parent.workflow_id.clone(),
18064                parent_workflow_run_id: parent.run_id.clone(),
18065                child_workflow_id,
18066                child_workflow_run_id,
18067                child_workflow_type,
18068                failure_id: payload_string(payload, "failure_id"),
18069                failure_category: payload_string(payload, "failure_category"),
18070                exception_type,
18071                exception_class,
18072                non_retryable: payload
18073                    .get("non_retryable")
18074                    .and_then(Value::as_bool)
18075                    .unwrap_or(false),
18076                code: payload
18077                    .get("code")
18078                    .filter(|value| !value.is_null())
18079                    .cloned(),
18080                exception,
18081            }));
18082            continue;
18083        }
18084
18085        let codec = payload
18086            .get("payload_codec")
18087            .and_then(Value::as_str)
18088            .unwrap_or(fallback_codec);
18089        let result = payload
18090            .get("result")
18091            .or_else(|| payload.get("output"))
18092            .unwrap_or(&Value::Null);
18093        outcomes.push(Ok(ChildWorkflowAvroResult {
18094            parent: parent.clone(),
18095            child: WorkflowIdentity {
18096                workflow_id: child_workflow_id,
18097                run_id: child_workflow_run_id,
18098            },
18099            child_workflow_type,
18100            result: decode_wire_avro_value(result, codec)?,
18101        }));
18102    }
18103
18104    Ok(outcomes)
18105}
18106
18107fn payload_string(payload: &Value, key: &str) -> Option<String> {
18108    payload
18109        .get(key)
18110        .and_then(Value::as_str)
18111        .filter(|value| !value.is_empty())
18112        .map(str::to_string)
18113}
18114
18115fn recorded_activity_failure_boundary(
18116    ctx: &WorkflowContext,
18117    error: &Error,
18118) -> Option<(u64, String)> {
18119    let Error::ActivityFailed(failure) = error else {
18120        return None;
18121    };
18122    if failure.kind != ActivityFailureKind::Failed {
18123        return None;
18124    }
18125    let activity_execution_id = failure
18126        .activity_execution_id
18127        .as_deref()
18128        .filter(|value| !value.is_empty())?;
18129    let state = ctx.state.lock().ok()?;
18130    let mut matches = state.recorded_commands.iter().filter_map(|command| {
18131        let RecordedCommand::Activity {
18132            sequence,
18133            outcome: Some(Err(recorded_failure)),
18134            ..
18135        } = command
18136        else {
18137            return None;
18138        };
18139        (*sequence > 0 && recorded_failure == failure)
18140            .then_some((*sequence, activity_execution_id.to_string()))
18141    });
18142    let boundary = matches.next()?;
18143    matches.next().is_none().then_some(boundary)
18144}
18145
18146fn workflow_failure_command(
18147    error: &Error,
18148    failed_activity_boundary: Option<(u64, String)>,
18149) -> Value {
18150    let (exception_type, exception_class, properties) = match error {
18151        Error::NexusOperationFailed(failure) => (
18152            "NexusOperationFailed",
18153            "durable_workflow::NexusOperationFailure",
18154            json!({"service_call_id":failure.service_call_id, "status":failure.status,
18155                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
18156        ),
18157        Error::ActivityFailed(failure) => (
18158            match failure.kind {
18159                ActivityFailureKind::Failed => "ActivityFailed",
18160                ActivityFailureKind::Cancelled => "ActivityCancelled",
18161                ActivityFailureKind::TimedOut => "ActivityTimedOut",
18162            },
18163            "durable_workflow::ActivityFailure",
18164            json!({
18165                "reason": failure.reason,
18166                "activity_execution_id": failure.activity_execution_id,
18167                "activity_attempt_id": failure.activity_attempt_id,
18168                "activity_type": failure.activity_type,
18169                "activity_class": failure.activity_class,
18170                "attempt_number": failure.attempt_number,
18171                "failure_id": failure.failure_id,
18172                "failure_category": failure.failure_category,
18173                "timeout_kind": failure.timeout_kind,
18174                "activity_non_retryable": failure.non_retryable,
18175                "activity_exception_type": failure.exception_type,
18176                "activity_exception_class": failure.exception_class,
18177                "activity_code": failure.code,
18178                "activity_exception": failure.exception,
18179            }),
18180        ),
18181        Error::ChildWorkflowFailed(failure) => (
18182            match failure.kind {
18183                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18184                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18185                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18186            },
18187            "durable_workflow::ChildWorkflowFailure",
18188            json!({
18189                "reason": failure.reason,
18190                "parent_workflow_id": failure.parent_workflow_id,
18191                "parent_workflow_run_id": failure.parent_workflow_run_id,
18192                "child_workflow_id": failure.child_workflow_id,
18193                "child_workflow_run_id": failure.child_workflow_run_id,
18194                "child_workflow_type": failure.child_workflow_type,
18195                "failure_id": failure.failure_id,
18196                "failure_category": failure.failure_category,
18197                "child_exception_type": failure.exception_type,
18198                "child_exception_class": failure.exception_class,
18199                "child_non_retryable": failure.non_retryable,
18200                "child_code": failure.code,
18201                "child_exception": failure.exception,
18202            }),
18203        ),
18204        Error::ParallelFailed(failure) => (
18205            "ParallelFailed",
18206            "durable_workflow::ParallelFailure",
18207            json!({
18208                "parallel_group_id": failure.group_id,
18209                "parallel_member_path": failure.member_path,
18210                "parallel_group_path": failure.group_path,
18211                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
18212                "cause_type": workflow_error_type(&failure.cause),
18213                "cause_message": failure.cause.to_string(),
18214            }),
18215        ),
18216        Error::SagaCompensationFailed(failure) => (
18217            "SagaCompensationFailed",
18218            "durable_workflow::SagaCompensationFailure",
18219            json!({
18220                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
18221                "initiating_failure_message": failure.initiating_failure.to_string(),
18222                "compensation_activity_type": failure.compensation_activity_type,
18223                "compensation_registration_order": failure.compensation_registration_order,
18224                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
18225                "compensation_failure_message": failure.compensation_failure.to_string(),
18226            }),
18227        ),
18228        Error::WorkflowCancellationRequested(_) => (
18229            "WorkflowCancellationRequested",
18230            "durable_workflow::WorkflowCancellationRequested",
18231            json!({"reason": "cancelled"}),
18232        ),
18233        Error::CooperativeCancellationRequested(cancellation) => (
18234            "WorkflowCancellationRequested",
18235            "durable_workflow::CooperativeCancellationRequested",
18236            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
18237                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
18238        ),
18239        Error::CancellationScopeRequested(cancellation) => (
18240            "WorkflowCancellationRequested",
18241            "durable_workflow::CancellationScopeRequested",
18242            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
18243                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
18244                "cancellation":cancellation.context.to_value()}),
18245        ),
18246        Error::NonDeterministicReplay(_) => (
18247            "NonDeterministicReplay",
18248            "durable_workflow::Error",
18249            Value::Null,
18250        ),
18251        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
18252    };
18253    let non_retryable = match error {
18254        Error::ActivityFailed(failure) => failure.non_retryable,
18255        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18256        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18257        Error::SagaCompensationFailed(failure) => {
18258            workflow_error_non_retryable(&failure.compensation_failure)
18259        }
18260        Error::WorkflowCancellationRequested(_)
18261        | Error::CooperativeCancellationRequested(_)
18262        | Error::CancellationScopeRequested(_) => true,
18263        Error::NonDeterministicReplay(_) => true,
18264        _ => false,
18265    };
18266
18267    let mut command = json!({
18268        "type": "fail_workflow",
18269        "message": error.to_string(),
18270        "exception_type": exception_type,
18271        "exception_class": exception_class,
18272        "non_retryable": non_retryable,
18273        "exception": {
18274            "type": exception_type,
18275            "class": exception_class,
18276            "message": error.to_string(),
18277            "properties": properties,
18278        }
18279    });
18280
18281    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
18282        command["failed_step_sequence"] = json!(sequence);
18283        command["failed_activity_execution_id"] = json!(activity_execution_id);
18284    }
18285
18286    command
18287}
18288
18289fn workflow_error_type(error: &Error) -> &'static str {
18290    match error {
18291        Error::NexusOperationFailed(_) => "NexusOperationFailed",
18292        Error::ActivityFailed(failure) => match failure.kind {
18293            ActivityFailureKind::Failed => "ActivityFailed",
18294            ActivityFailureKind::Cancelled => "ActivityCancelled",
18295            ActivityFailureKind::TimedOut => "ActivityTimedOut",
18296        },
18297        Error::ChildWorkflowFailed(failure) => match failure.kind {
18298            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18299            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18300            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18301        },
18302        Error::ParallelFailed(_) => "ParallelFailed",
18303        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
18304        Error::WorkflowCancellationRequested(_)
18305        | Error::CooperativeCancellationRequested(_)
18306        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
18307        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
18308        _ => "RustWorkflowError",
18309    }
18310}
18311
18312fn workflow_error_non_retryable(error: &Error) -> bool {
18313    match error {
18314        Error::ActivityFailed(failure) => failure.non_retryable,
18315        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18316        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18317        Error::SagaCompensationFailed(failure) => {
18318            workflow_error_non_retryable(&failure.compensation_failure)
18319        }
18320        Error::WorkflowCancellationRequested(_)
18321        | Error::CooperativeCancellationRequested(_)
18322        | Error::CancellationScopeRequested(_)
18323        | Error::NonDeterministicReplay(_) => true,
18324        _ => false,
18325    }
18326}
18327
18328fn workflow_task_integrity_error(error: &Error) -> bool {
18329    matches!(
18330        error,
18331        Error::NonDeterministicReplay(_)
18332            | Error::Protocol(_)
18333            | Error::CancellationScopeExecutionUnavailable
18334            | Error::MissingWorkflowCommandIdentity
18335            | Error::WorkflowStatePoisoned
18336    )
18337}
18338
18339fn decode_signal_event_arguments(
18340    event: &HistoryEvent,
18341    fallback_codec: &str,
18342) -> Result<Vec<AvroValue>> {
18343    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18344    validate_payload_codec(codec)?;
18345    let raw = signal_history_payload(&event.payload);
18346    let decoded = match raw.filter(|value| !value.is_null()) {
18347        Some(value) => decode_wire_avro_value(value, codec)?,
18348        None => AvroValue::Array(Vec::new()),
18349    };
18350    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18351        unreachable!("normalize_avro_arguments always returns an array");
18352    };
18353    Ok(arguments)
18354}
18355
18356fn decode_update_event_arguments(
18357    event: &HistoryEvent,
18358    fallback_codec: &str,
18359) -> Result<Vec<AvroValue>> {
18360    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18361    validate_payload_codec(codec)?;
18362    let decoded = match event
18363        .payload
18364        .get("arguments")
18365        .filter(|value| !value.is_null())
18366    {
18367        Some(value) => decode_wire_avro_value(value, codec)?,
18368        None => AvroValue::Array(Vec::new()),
18369    };
18370    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18371        unreachable!("normalize_avro_arguments always returns an array");
18372    };
18373    Ok(arguments)
18374}
18375
18376fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18377    let Some(export_events) = task
18378        .history_export
18379        .as_ref()
18380        .and_then(|export| export.get("history_events"))
18381        .and_then(Value::as_array)
18382    else {
18383        return Ok(());
18384    };
18385
18386    if export_events.len() > task.history_events.len() {
18387        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
18388    }
18389
18390    Ok(())
18391}
18392
18393fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18394    let Some(export) = task.history_export.as_ref() else {
18395        return Ok(());
18396    };
18397    let signals = export
18398        .get("signals")
18399        .and_then(Value::as_array)
18400        .cloned()
18401        .unwrap_or_default();
18402    let activities = export
18403        .get("activities")
18404        .and_then(Value::as_array)
18405        .cloned()
18406        .unwrap_or_default();
18407    let export_codec = export
18408        .get("payloads")
18409        .and_then(|payloads| payloads.get("codec"))
18410        .and_then(Value::as_str)
18411        .unwrap_or(&task.payload_codec)
18412        .to_string();
18413    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
18414
18415    for event in &mut task.history_events {
18416        if event.event_type == "ActivityCompleted" {
18417            let sequence = event
18418                .payload
18419                .get("sequence")
18420                .or_else(|| event.payload.get("workflow_sequence"))
18421                .and_then(value_as_u64);
18422            let Some(activity) = sequence.and_then(|sequence| {
18423                activities.iter().find(|activity| {
18424                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
18425                })
18426            }) else {
18427                continue;
18428            };
18429            let Some(payload) = event.payload.as_object_mut() else {
18430                continue;
18431            };
18432            if missing_payload(payload.get("result")) {
18433                if let Some(result) = activity
18434                    .get("result")
18435                    .filter(|value| !missing_payload(Some(value)))
18436                {
18437                    payload.insert("result".to_string(), result.clone());
18438                }
18439            }
18440            for field in ["payload_codec", "activity_type"] {
18441                if payload
18442                    .get(field)
18443                    .and_then(Value::as_str)
18444                    .unwrap_or_default()
18445                    .is_empty()
18446                {
18447                    if let Some(value) = activity.get(field) {
18448                        payload.insert(field.to_string(), value.clone());
18449                    }
18450                }
18451            }
18452            continue;
18453        }
18454
18455        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
18456            continue;
18457        }
18458        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18459        let command_id = event
18460            .payload
18461            .get("workflow_command_id")
18462            .or_else(|| event.raw.get("workflow_command_id"))
18463            .and_then(Value::as_str);
18464        let signal_name = event
18465            .payload
18466            .get("signal_name")
18467            .and_then(Value::as_str)
18468            .unwrap_or_default()
18469            .to_string();
18470        let matched = signals
18471            .iter()
18472            .find(|signal| {
18473                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
18474            })
18475            .or_else(|| {
18476                signals.iter().find(|signal| {
18477                    command_id.is_some()
18478                        && signal.get("command_id").and_then(Value::as_str) == command_id
18479                })
18480            })
18481            .or_else(|| {
18482                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
18483                let signal = signals
18484                    .iter()
18485                    .filter(|signal| {
18486                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
18487                    })
18488                    .nth(*offset);
18489                if signal.is_some() {
18490                    *offset += 1;
18491                }
18492                signal
18493            });
18494        let Some(signal) = matched else {
18495            continue;
18496        };
18497        let signal_codec = signal
18498            .get("payload_codec")
18499            .and_then(Value::as_str)
18500            .unwrap_or(&export_codec);
18501        let Some(payload) = event.payload.as_object_mut() else {
18502            continue;
18503        };
18504        if missing_payload(payload.get("arguments")) {
18505            if let Some(arguments) = signal
18506                .get("arguments")
18507                .filter(|value| !missing_payload(Some(value)))
18508            {
18509                let envelope = match arguments {
18510                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
18511                    other => other.clone(),
18512                };
18513                payload.insert("arguments".to_string(), envelope);
18514            }
18515        }
18516        if payload
18517            .get("payload_codec")
18518            .and_then(Value::as_str)
18519            .unwrap_or_default()
18520            .is_empty()
18521        {
18522            payload.insert("payload_codec".to_string(), json!(signal_codec));
18523        }
18524    }
18525
18526    Ok(())
18527}
18528
18529fn missing_payload(value: Option<&Value>) -> bool {
18530    match value {
18531        None | Some(Value::Null) => true,
18532        Some(Value::String(value)) => value.is_empty(),
18533        Some(_) => false,
18534    }
18535}
18536
18537fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
18538    history_signal_events(
18539        &task.history_events,
18540        task.history_export.as_ref(),
18541        &task.payload_codec,
18542    )
18543}
18544
18545fn history_signal_events(
18546    history_events: &[HistoryEvent],
18547    history_export: Option<&Value>,
18548    payload_codec: &str,
18549) -> Result<Vec<QuerySignal>> {
18550    let export_signals = history_export
18551        .and_then(|export| export.get("signals"))
18552        .and_then(Value::as_array)
18553        .cloned()
18554        .unwrap_or_default();
18555    let export_codec = history_export
18556        .and_then(|export| export.get("payloads"))
18557        .and_then(|payloads| payloads.get("codec"))
18558        .and_then(Value::as_str)
18559        .unwrap_or(payload_codec);
18560    let mut name_offsets: HashMap<String, usize> = HashMap::new();
18561    let mut signals: Vec<QuerySignal> = Vec::new();
18562    let mut signal_indices = HashMap::new();
18563    let mut command_indices = HashMap::new();
18564
18565    for event in history_events {
18566        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
18567            continue;
18568        }
18569
18570        let name = event
18571            .payload
18572            .get("signal_name")
18573            .and_then(Value::as_str)
18574            .unwrap_or_default();
18575        if name.is_empty() {
18576            continue;
18577        }
18578        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18579        let command_id = event
18580            .payload
18581            .get("workflow_command_id")
18582            .or_else(|| event.raw.get("workflow_command_id"))
18583            .and_then(Value::as_str);
18584        let matched_export = export_signals
18585            .iter()
18586            .find(|candidate| {
18587                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
18588            })
18589            .or_else(|| {
18590                export_signals.iter().find(|candidate| {
18591                    command_id.is_some()
18592                        && candidate.get("command_id").and_then(Value::as_str) == command_id
18593                })
18594            })
18595            .or_else(|| {
18596                let offset = name_offsets.entry(name.to_string()).or_default();
18597                let candidate = export_signals
18598                    .iter()
18599                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
18600                    .nth(*offset);
18601                if candidate.is_some() {
18602                    *offset += 1;
18603                }
18604                candidate
18605            });
18606        let codec = event
18607            .payload
18608            .get("payload_codec")
18609            .and_then(Value::as_str)
18610            .or_else(|| {
18611                matched_export
18612                    .and_then(|signal| signal.get("payload_codec"))
18613                    .and_then(Value::as_str)
18614            })
18615            .unwrap_or(export_codec);
18616        let raw_arguments = signal_history_payload(&event.payload)
18617            .filter(|value| !value.is_null())
18618            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
18619        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18620        let workflow_sequence = event
18621            .payload
18622            .get("workflow_sequence")
18623            .and_then(value_as_u64)
18624            .or_else(|| {
18625                matched_export
18626                    .and_then(|signal| signal.get("workflow_sequence"))
18627                    .and_then(value_as_u64)
18628            });
18629
18630        let id = signal_id.or_else(|| {
18631            matched_export
18632                .and_then(|signal| signal.get("id"))
18633                .and_then(Value::as_str)
18634        });
18635        let command_id = command_id.or_else(|| {
18636            matched_export
18637                .and_then(|signal| signal.get("command_id"))
18638                .and_then(Value::as_str)
18639        });
18640        let duplicate = id
18641            .and_then(|id| signal_indices.get(id))
18642            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18643            .copied();
18644        let index = duplicate.unwrap_or(signals.len());
18645        if let Some(index) = duplicate {
18646            let original = &mut signals[index];
18647            let same_arguments = if event.event_type == "SignalApplied" {
18648                if let Some(value) = event.payload.get("value") {
18649                    let expected = match original.avro_arguments.as_slice() {
18650                        [] => AvroValue::Boolean(true),
18651                        [value] => value.clone(),
18652                        values => AvroValue::Array(values.to_vec()),
18653                    };
18654                    let applied = decode_wire_avro_value(value, codec)?;
18655                    applied == expected
18656                        || applied == AvroValue::Array(original.avro_arguments.clone())
18657                } else {
18658                    original.avro_arguments == avro_arguments
18659                }
18660            } else {
18661                original.avro_arguments == avro_arguments
18662            };
18663            if original.name != name
18664                || !same_arguments
18665                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18666            {
18667                return Err(Error::Codec("conflicting committed signal identity".into()));
18668            }
18669            if original.id.is_none() {
18670                original.id = id.map(str::to_string);
18671            }
18672            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18673        } else {
18674            signals.push(QuerySignal {
18675                id: id.map(str::to_string),
18676                name: name.to_string(),
18677                arguments,
18678                avro_arguments,
18679                workflow_sequence,
18680            });
18681        }
18682        if let Some(id) = id {
18683            signal_indices.insert(id.to_string(), index);
18684        }
18685        if let Some(id) = command_id {
18686            command_indices.insert(id.to_string(), index);
18687        }
18688    }
18689
18690    if signals.is_empty() {
18691        for signal in export_signals {
18692            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18693                continue;
18694            }
18695            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18696                continue;
18697            };
18698            let codec = signal
18699                .get("payload_codec")
18700                .and_then(Value::as_str)
18701                .unwrap_or(export_codec);
18702            let (arguments, avro_arguments) =
18703                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18704            signals.push(QuerySignal {
18705                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18706                name: name.to_string(),
18707                arguments,
18708                avro_arguments,
18709                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18710            });
18711        }
18712        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18713    }
18714
18715    Ok(signals)
18716}
18717
18718fn decode_query_signal_arguments(
18719    raw: Option<&Value>,
18720    codec: &str,
18721) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18722    validate_payload_codec(codec)?;
18723    let decoded = match raw.filter(|value| !value.is_null()) {
18724        Some(value) => decode_wire_avro_value(value, codec)?,
18725        None => AvroValue::Array(Vec::new()),
18726    };
18727    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18728        unreachable!("normalize_avro_arguments always returns an array");
18729    };
18730    let arguments = avro_arguments
18731        .iter()
18732        .cloned()
18733        .map(AvroValue::into_json)
18734        .collect::<Result<Vec<_>>>()?;
18735    Ok((arguments, avro_arguments))
18736}
18737
18738fn value_as_u64(value: &Value) -> Option<u64> {
18739    value
18740        .as_u64()
18741        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18742}
18743
18744#[cfg(test)]
18745mod tests {
18746    use super::*;
18747    #[cfg(feature = "telemetry")]
18748    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
18749        tokio::sync::Mutex::const_new(());
18750    mod activity_cancellation_policies;
18751    mod activity_lease_worker;
18752    mod cancellation_scope_admission;
18753    mod cancellation_scope_authoring;
18754    mod cancellation_scope_history;
18755    mod cancellation_scope_opening;
18756    mod cancellation_scope_replay;
18757    mod child_workflow_policies;
18758    mod cooperative_cancellation;
18759    mod local_activity;
18760    mod nexus;
18761    mod runtime_payloads;
18762    mod runtime_uploads;
18763    mod version_marker_contract;
18764    mod worker_capacity;
18765    mod worker_session;
18766    use std::{
18767        fs,
18768        io::{Read, Write},
18769        net::{SocketAddr, TcpListener, TcpStream},
18770        process::Command as ProcessCommand,
18771        sync::atomic::AtomicUsize,
18772        thread,
18773    };
18774
18775    #[derive(Clone, Copy, Debug)]
18776    enum InvalidTaskPayloadCodec {
18777        Missing,
18778        Null,
18779        NonString,
18780    }
18781
18782    impl InvalidTaskPayloadCodec {
18783        fn label(self) -> &'static str {
18784            match self {
18785                Self::Missing => "missing",
18786                Self::Null => "null",
18787                Self::NonString => "non-string",
18788            }
18789        }
18790
18791        fn apply(self, task: &mut Value) {
18792            let task = task.as_object_mut().expect("task fixture object");
18793            match self {
18794                Self::Missing => {
18795                    task.remove("payload_codec");
18796                }
18797                Self::Null => {
18798                    task.insert("payload_codec".to_string(), Value::Null);
18799                }
18800                Self::NonString => {
18801                    task.insert("payload_codec".to_string(), json!(42));
18802                }
18803            }
18804        }
18805    }
18806
18807    fn fixture_envelope(value: Value) -> Value {
18808        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18809    }
18810
18811    fn fixture_blob(value: Value) -> String {
18812        encode_payload(&value, DEFAULT_CODEC)
18813            .expect("encode Avro test fixture")
18814            .blob
18815    }
18816
18817    #[test]
18818    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18819        for base_url in [
18820            "http://127.0.0.1:8080/api",
18821            "http://localhost:8080/api/",
18822            "https://runtime.example.test/namespaces/orders/api",
18823        ] {
18824            let error = Client::builder(base_url)
18825                .build()
18826                .expect_err("SDK-owned /api suffix must be rejected during build");
18827
18828            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18829            assert!(
18830                error.to_string().contains("SDK appends /api automatically"),
18831                "the validation error must explain how to fix the endpoint"
18832            );
18833        }
18834    }
18835
18836    #[test]
18837    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18838        for (base_url, expected) in [
18839            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18840            (
18841                "http://localhost:8080/durable-workflow/",
18842                "http://localhost:8080/durable-workflow",
18843            ),
18844            (
18845                "https://runtime.example.test/namespaces/orders",
18846                "https://runtime.example.test/namespaces/orders",
18847            ),
18848            (
18849                "https://runtime.example.test/gateway/api/namespaces/orders",
18850                "https://runtime.example.test/gateway/api/namespaces/orders",
18851            ),
18852            (
18853                "https://api.example.test/runtime/orders/",
18854                "https://api.example.test/runtime/orders",
18855            ),
18856        ] {
18857            let client = Client::builder(base_url)
18858                .build()
18859                .expect("Server and Cloud runtime base URL must remain valid");
18860
18861            assert_eq!(client.base_url, expected);
18862        }
18863    }
18864
18865    #[test]
18866    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18867        assert_eq!(
18868            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18869            MINIMUM_WORKER_PROTOCOL_VERSION
18870        );
18871        assert_eq!(
18872            workflow_completion_protocol_version(&[json!({
18873                "type": "upsert_search_attributes",
18874                "attributes": {"OrderStatus": "waiting"},
18875            })]),
18876            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18877        );
18878        assert_eq!(
18879            workflow_completion_protocol_version(&[json!({
18880                "type": "upsert_search_attributes",
18881                "attributes": {"OrderStatus": "waiting"},
18882                "attribute_types": {"OrderStatus": "keyword"},
18883            })]),
18884            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18885        );
18886        assert_eq!(
18887            workflow_completion_protocol_version(&[
18888                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18889                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18890            ]),
18891            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18892        );
18893        assert_eq!(
18894            workflow_completion_protocol_version(&[
18895                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18896                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18897            ]),
18898            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18899        );
18900        assert_eq!(
18901            workflow_completion_protocol_version(&[json!({
18902                "type": "open_condition_wait",
18903                "condition_wait_occurrence_id": "rust:condition-wait:0",
18904                "condition_key": "ready",
18905            })]),
18906            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18907        );
18908        assert_eq!(
18909            workflow_completion_protocol_version_with_message_streams(
18910                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18911                true,
18912            ),
18913            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18914        );
18915        assert_eq!(
18916            workflow_completion_protocol_version_with_message_streams(
18917                &[json!({
18918                    "type": "open_condition_wait",
18919                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18920                    "condition_key": "ready",
18921                })],
18922                true,
18923            ),
18924            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18925        );
18926    }
18927
18928    #[test]
18929    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18930        let manifest = portable_worker_affinity_capability_manifest();
18931
18932        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18933            assert_eq!(manifest[capability]["supported"], json!(false));
18934            assert_eq!(
18935                manifest[capability]["minimum_protocol_version"],
18936                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18937            );
18938            assert!(manifest[capability]["reason"]
18939                .as_str()
18940                .is_some_and(|reason| !reason.is_empty()));
18941        }
18942    }
18943
18944    fn typed_fidelity_probe() -> AvroValue {
18945        AvroValue::Map(BTreeMap::from([
18946            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18947            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18948            (
18949                "numeric".to_string(),
18950                AvroValue::Map(BTreeMap::from([
18951                    ("0".to_string(), AvroValue::String("zero".to_string())),
18952                    ("1".to_string(), AvroValue::String("one".to_string())),
18953                ])),
18954            ),
18955            (
18956                "nested".to_string(),
18957                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18958                    "enabled".to_string(),
18959                    AvroValue::Boolean(true),
18960                )]))]),
18961            ),
18962            (
18963                "projection_collisions".to_string(),
18964                AvroValue::Array(projection_collision_probe()),
18965            ),
18966        ]))
18967    }
18968
18969    fn projection_collision_probe() -> Vec<AvroValue> {
18970        vec![
18971            AvroValue::Map(BTreeMap::from([
18972                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18973                (
18974                    "base64".to_string(),
18975                    AvroValue::String("ordinary user text".to_string()),
18976                ),
18977            ])),
18978            AvroValue::Map(BTreeMap::from([
18979                ("$type".to_string(), AvroValue::String("map".to_string())),
18980                (
18981                    "entries".to_string(),
18982                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
18983                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
18984                        (
18985                            "value".to_string(),
18986                            AvroValue::String("user map".to_string()),
18987                        ),
18988                    ]))]),
18989                ),
18990            ])),
18991        ]
18992    }
18993
18994    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18995    struct TypedContract {
18996        nested: TypedNested,
18997        mode: TypedMode,
18998        optional: Option<String>,
18999        absent: Option<String>,
19000        items: Vec<i64>,
19001        labels: BTreeMap<String, String>,
19002        bytes: serde_bytes::ByteBuf,
19003        signed: i64,
19004        finite: f64,
19005    }
19006
19007    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19008    struct TypedNested {
19009        enabled: bool,
19010    }
19011
19012    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19013    enum TypedMode {
19014        Detailed { label: String },
19015    }
19016
19017    fn typed_contract() -> TypedContract {
19018        TypedContract {
19019            nested: TypedNested { enabled: true },
19020            mode: TypedMode::Detailed {
19021                label: "compiler-checked".to_string(),
19022            },
19023            optional: Some("present".to_string()),
19024            absent: None,
19025            items: vec![i64::MIN, 0, i64::MAX],
19026            labels: BTreeMap::from([
19027                ("language".to_string(), "rust".to_string()),
19028                ("wire".to_string(), "avro".to_string()),
19029            ]),
19030            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
19031            signed: -9_223_372_036_854_775_000,
19032            finite: 12.5,
19033        }
19034    }
19035
19036    #[derive(Clone, Debug, Default, PartialEq)]
19037    struct ReplayCounterState {
19038        loaded: Option<String>,
19039        count: i64,
19040        finished: bool,
19041    }
19042
19043    fn replay_counter_worker() -> Worker {
19044        let client = Client::new("http://127.0.0.1:8080").expect("client");
19045        let mut worker = Worker::new(client, "rust-workers");
19046        worker.register_replayed_workflow(
19047            "replay-counter",
19048            ReplayCounterState::default,
19049            |ctx, _input, state| async move {
19050                let loaded = ctx.activity("load-counter", json!([])).await?;
19051                state.update(|current| {
19052                    current.loaded = loaded.as_str().map(str::to_string);
19053                })?;
19054                for _ in 0..2 {
19055                    let signal = ctx.wait_signal("increment").await?;
19056                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
19057                    state.update(|current| current.count += amount)?;
19058                }
19059                state.update(|current| current.finished = true)?;
19060                state.read(|current| Ok(json!(current.count)))?
19061            },
19062        );
19063        worker.register_replayed_query::<ReplayCounterState, _, _>(
19064            "replay-counter",
19065            "current",
19066            |_ctx, state, _args| async move {
19067                Ok(json!({
19068                    "loaded": state.loaded,
19069                    "count": state.count,
19070                    "finished": state.finished,
19071                }))
19072            },
19073        );
19074        worker.register_replayed_query::<ReplayCounterState, _, _>(
19075            "replay-counter",
19076            "detached-mutation",
19077            |_ctx, state, _args| async move {
19078                let mut detached = (*state).clone();
19079                detached.count = 999;
19080                Ok(json!(detached.count))
19081            },
19082        );
19083        worker.register_replayed_query::<ReplayCounterState, _, _>(
19084            "replay-counter",
19085            "failed-mutation",
19086            |_ctx, state, _args| async move {
19087                let mut detached = (*state).clone();
19088                detached.count = 999;
19089                Err(Error::WorkerLoop("query refused".to_string()))
19090            },
19091        );
19092        worker
19093    }
19094
19095    fn replay_counter_query(
19096        query_name: &str,
19097        history_events: Value,
19098        run_status: &str,
19099    ) -> QueryTask {
19100        let arguments = fixture_envelope(json!([]));
19101        serde_json::from_value(json!({
19102            "query_task_id": format!("query-{query_name}"),
19103            "workflow_type": "replay-counter",
19104            "query_name": query_name,
19105            "payload_codec": DEFAULT_CODEC,
19106            "workflow_arguments": arguments.clone(),
19107            "query_arguments": arguments,
19108            "history_events": history_events,
19109            "run_status": run_status,
19110        }))
19111        .expect("query task")
19112    }
19113
19114    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
19115        workflow_context_with_codec(history, DEFAULT_CODEC)
19116    }
19117
19118    fn workflow_context_with_codec(
19119        history: Vec<HistoryEvent>,
19120        payload_codec: &str,
19121    ) -> WorkflowContext {
19122        WorkflowContext {
19123            cancellation_scope_id: "root".into(),
19124            state: Arc::new(Mutex::new(
19125                WorkflowState::new_with_identity(
19126                    history,
19127                    None,
19128                    None,
19129                    "rust-workers".to_string(),
19130                    payload_codec.to_string(),
19131                    None,
19132                )
19133                .expect("valid workflow history"),
19134            )),
19135        }
19136    }
19137
19138    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
19139        HistoryEvent {
19140            event_type: event_type.to_string(),
19141            payload,
19142            raw: HashMap::new(),
19143        }
19144    }
19145
19146    fn parallel_path_entry(
19147        kind: &str,
19148        base: u64,
19149        size: usize,
19150        index: usize,
19151    ) -> ParallelGroupMetadata {
19152        parallel_group_entry(base, size, index, kind)
19153    }
19154
19155    fn parallel_history_event(
19156        event_type: &str,
19157        sequence: u64,
19158        identity_field: &str,
19159        identity: &str,
19160        path: Vec<ParallelGroupMetadata>,
19161        result: Option<Value>,
19162    ) -> HistoryEvent {
19163        let mut payload = serde_json::Map::from_iter([
19164            ("sequence".to_string(), json!(sequence)),
19165            (identity_field.to_string(), json!(identity)),
19166        ]);
19167        let inner = path.last().expect("parallel history path");
19168        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
19169        payload.insert("parallel_group_path".to_string(), json!(path));
19170        if let Some(result) = result {
19171            let field = if event_type == "ChildRunCompleted" {
19172                "result"
19173            } else {
19174                "result"
19175            };
19176            payload.insert(field.to_string(), fixture_envelope(result));
19177            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
19178        }
19179        history_event(event_type, Value::Object(payload))
19180    }
19181
19182    fn nested_parallel_operations() -> Vec<ParallelOperation> {
19183        vec![
19184            ParallelOperation::activity("first", json!([])),
19185            ParallelOperation::group(vec![
19186                ParallelOperation::child_workflow(
19187                    "second",
19188                    ChildWorkflowOptions::new("child-workers"),
19189                    json!([]),
19190                ),
19191                ParallelOperation::activity("third", json!([])),
19192            ]),
19193        ]
19194    }
19195
19196    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
19197        let outer = [
19198            parallel_path_entry("mixed", 1, 3, 0),
19199            parallel_path_entry("mixed", 1, 3, 1),
19200            parallel_path_entry("mixed", 1, 3, 2),
19201        ];
19202        [
19203            vec![outer[0].clone()],
19204            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
19205            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
19206        ]
19207    }
19208
19209    #[test]
19210    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
19211        let ctx = workflow_context(Vec::new());
19212        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19213        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19214
19215        assert!(matches!(
19216            call.as_mut().poll(&mut task_context),
19217            Poll::Pending
19218        ));
19219        let commands = ctx.take_commands().expect("parallel commands");
19220        assert_eq!(
19221            commands
19222                .iter()
19223                .map(|command| command["type"].as_str().unwrap_or_default())
19224                .collect::<Vec<_>>(),
19225            [
19226                "schedule_activity",
19227                "start_child_workflow",
19228                "schedule_activity"
19229            ]
19230        );
19231        let paths = nested_parallel_paths();
19232        for (command, path) in commands.iter().zip(paths) {
19233            assert_eq!(command["parallel_group_path"], json!(path));
19234            assert_eq!(
19235                command["parallel_group_id"],
19236                json!(path.last().expect("inner group").parallel_group_id)
19237            );
19238        }
19239    }
19240
19241    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
19242        let paths = nested_parallel_paths();
19243        let third = parallel_history_event(
19244            "ActivityCompleted",
19245            3,
19246            "activity_type",
19247            "third",
19248            paths[2].clone(),
19249            Some(json!("three")),
19250        );
19251        vec![
19252            parallel_history_event(
19253                "ActivityCompleted",
19254                1,
19255                "activity_type",
19256                "first",
19257                paths[0].clone(),
19258                Some(json!("one")),
19259            ),
19260            parallel_history_event(
19261                "ChildWorkflowScheduled",
19262                2,
19263                "child_workflow_type",
19264                "second",
19265                paths[1].clone(),
19266                None,
19267            ),
19268            parallel_history_event(
19269                "ChildRunCompleted",
19270                2,
19271                "child_workflow_type",
19272                "second",
19273                paths[1].clone(),
19274                Some(json!("two")),
19275            ),
19276            third.clone(),
19277            third,
19278        ]
19279    }
19280
19281    #[test]
19282    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
19283        for _restart_or_completed_replay in 0..2 {
19284            let ctx = workflow_context(completed_nested_parallel_history());
19285            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19286            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19287            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
19288                panic!("completed nested parallel history must replay");
19289            };
19290            assert_eq!(
19291                results,
19292                vec![
19293                    ParallelResult::Activity(json!("one")),
19294                    ParallelResult::Group(vec![
19295                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
19296                            parent: WorkflowIdentity {
19297                                workflow_id: None,
19298                                run_id: None,
19299                            },
19300                            child: WorkflowIdentity {
19301                                workflow_id: None,
19302                                run_id: None,
19303                            },
19304                            child_workflow_type: Some("second".to_string()),
19305                            result: json!("two"),
19306                        }),
19307                        ParallelResult::Activity(json!("three")),
19308                    ]),
19309                ]
19310            );
19311            assert!(ctx.take_commands().expect("commands").is_empty());
19312            ctx.ensure_history_consumed().expect("history consumed");
19313        }
19314    }
19315
19316    #[test]
19317    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
19318        let paths = nested_parallel_paths();
19319        let history = vec![
19320            parallel_history_event(
19321                "ActivityCompleted",
19322                1,
19323                "activity_type",
19324                "first",
19325                paths[0].clone(),
19326                Some(json!("one")),
19327            ),
19328            parallel_history_event(
19329                "ChildWorkflowScheduled",
19330                2,
19331                "child_workflow_type",
19332                "second",
19333                paths[1].clone(),
19334                None,
19335            ),
19336            parallel_history_event(
19337                "ChildRunFailed",
19338                2,
19339                "child_workflow_type",
19340                "second",
19341                paths[1].clone(),
19342                None,
19343            ),
19344            parallel_history_event(
19345                "ActivityCompleted",
19346                3,
19347                "activity_type",
19348                "third",
19349                paths[2].clone(),
19350                Some(json!("late")),
19351            ),
19352        ];
19353        let ctx = workflow_context(history);
19354        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19355        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19356        let outcome = call.as_mut().poll(&mut task_context);
19357        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
19358            panic!("one failed child must return a typed partial failure: {outcome:?}");
19359        };
19360        assert_eq!(failure.member_path, [1, 0]);
19361        assert_eq!(failure.group_id, "parallel-calls:1:3");
19362        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
19363        assert_eq!(
19364            failure
19365                .completed
19366                .iter()
19367                .map(|completion| completion.member_path.clone())
19368                .collect::<Vec<_>>(),
19369            [vec![0], vec![1, 1]]
19370        );
19371    }
19372
19373    #[test]
19374    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
19375        let paths = nested_parallel_paths();
19376        let history = vec![
19377            parallel_history_event(
19378                "ActivityScheduled",
19379                1,
19380                "activity_type",
19381                "first",
19382                paths[0].clone(),
19383                None,
19384            ),
19385            parallel_history_event(
19386                "ChildWorkflowScheduled",
19387                2,
19388                "child_workflow_type",
19389                "second",
19390                paths[1].clone(),
19391                None,
19392            ),
19393            parallel_history_event(
19394                "ActivityScheduled",
19395                3,
19396                "activity_type",
19397                "third",
19398                paths[2].clone(),
19399                None,
19400            ),
19401        ];
19402        for _restart in 0..2 {
19403            let ctx = workflow_context(history.clone());
19404            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19405            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19406            let outcome = call.as_mut().poll(&mut task_context);
19407            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
19408            assert!(ctx.take_commands().expect("commands").is_empty());
19409        }
19410    }
19411
19412    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
19413        vec![selection_group_entry(
19414            1,
19415            2,
19416            index,
19417            "activity",
19418            &SelectionMemberMetadata {
19419                key: SelectionKey::Name(key.to_string()),
19420                index,
19421                base_sequence: index as u64 + 1,
19422                size: 1,
19423                kind: "activity".to_string(),
19424            },
19425        )]
19426    }
19427
19428    fn selection_activity_event(
19429        event_type: &str,
19430        index: usize,
19431        key: &str,
19432        result: Option<Value>,
19433    ) -> HistoryEvent {
19434        let sequence = index as u64 + 1;
19435        let mut event = parallel_history_event(
19436            event_type,
19437            sequence,
19438            "activity_type",
19439            &format!("{key}-activity"),
19440            selection_path(index, key),
19441            result,
19442        );
19443        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
19444        event.raw.insert(
19445            "id".to_string(),
19446            json!(if event_type == "ActivityCompleted" {
19447                format!("event-{key}")
19448            } else {
19449                format!("{event_type}-{key}")
19450            }),
19451        );
19452        event
19453    }
19454
19455    fn selection_winner_marker() -> HistoryEvent {
19456        history_event(
19457            "SelectionResolved",
19458            json!({
19459                "selection_group_id": "select-calls:1:2",
19460                "selection_group_base_sequence": 1,
19461                "selection_group_size": 2,
19462                "member_key": "fast",
19463                "member_index": 1,
19464                "member_base_sequence": 2,
19465                "member_size": 1,
19466                "operation_kind": "activity",
19467                "operation_identity": "activity-fast",
19468                "outcome": "completed",
19469                "resolution_event_id": "event-fast",
19470                "resolution_event_type": "ActivityCompleted",
19471            }),
19472        )
19473    }
19474
19475    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
19476        ctx.select_keyed(vec![
19477            (
19478                "slow",
19479                ParallelOperation::activity_with_options(
19480                    "slow-activity",
19481                    ActivityOptions::new().task_queue("default"),
19482                    json!([]),
19483                ),
19484            ),
19485            (
19486                "fast",
19487                ParallelOperation::activity_with_options(
19488                    "fast-activity",
19489                    ActivityOptions::new().task_queue("default"),
19490                    json!([]),
19491                ),
19492            ),
19493        ])
19494    }
19495
19496    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
19497        let ctx = workflow_context(history);
19498        let mut call = Box::pin(keyed_activity_selection(&ctx));
19499        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19500        let selected = match call.as_mut().poll(&mut task_context) {
19501            Poll::Ready(Ok(selected)) => selected,
19502            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
19503            Poll::Pending => panic!("persisted selection winner must replay without pending"),
19504        };
19505        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
19506        assert_eq!(
19507            selected.value,
19508            Some(ParallelResult::Activity(json!("winner-value")))
19509        );
19510        let slow = selected
19511            .handle(&SelectionKey::Name("slow".to_string()))
19512            .expect("slow handle")
19513            .clone();
19514        let mut await_slow = Box::pin(slow.await_result());
19515        assert!(matches!(
19516            await_slow.as_mut().poll(&mut task_context),
19517            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
19518        ));
19519        assert!(ctx.take_commands().expect("commands").is_empty());
19520    }
19521
19522    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
19523
19524    fn canonical_selection_history() -> Vec<HistoryEvent> {
19525        const FIXTURE: &[u8] =
19526            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
19527        assert_eq!(
19528            format!("{:x}", Sha256::digest(FIXTURE)),
19529            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19530        );
19531        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
19532
19533        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
19534    }
19535
19536    #[test]
19537    fn selection_fresh_process_entrypoint() {
19538        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
19539            return;
19540        };
19541        let persisted = fs::read(path).expect("persisted selection history");
19542        assert_eq!(
19543            format!("{:x}", Sha256::digest(&persisted)),
19544            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19545        );
19546        let fixture: Value =
19547            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
19548        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
19549            .expect("valid persisted selection history");
19550
19551        assert_persisted_selection_replay(history);
19552    }
19553
19554    #[test]
19555    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
19556        let ctx = workflow_context(Vec::new());
19557        let mut call = Box::pin(keyed_activity_selection(&ctx));
19558        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19559
19560        assert!(matches!(
19561            call.as_mut().poll(&mut task_context),
19562            Poll::Pending
19563        ));
19564        let commands = ctx.take_commands().expect("selection commands");
19565        assert_eq!(commands.len(), 2);
19566        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
19567        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
19568        assert!(commands.iter().all(|command| {
19569            command["parallel_group_id"] == json!("select-calls:1:2")
19570                && command["parallel_group_mode"] == json!("select")
19571        }));
19572    }
19573
19574    #[test]
19575    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
19576        let ctx = workflow_context(Vec::new());
19577        let mut invalid = Box::pin(ctx.select_keyed(vec![(
19578            "",
19579            ParallelOperation::activity("invalid", json!([])),
19580        )]));
19581        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19582        assert!(matches!(
19583            invalid.as_mut().poll(&mut task_context),
19584            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
19585                reason: "selection_key_invalid",
19586                ..
19587            })))
19588        ));
19589
19590        for invalid_key in [json!(""), json!(-1)] {
19591            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
19592            event.payload["selection_member_key"] = invalid_key.clone();
19593            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
19594            assert!(matches!(
19595                WorkflowState::new_with_identity(
19596                    vec![event],
19597                    None,
19598                    None,
19599                    "rust-workers".to_string(),
19600                    DEFAULT_CODEC.to_string(),
19601                    None,
19602                ),
19603                Err(Error::NonDeterministicReplay(_))
19604            ));
19605        }
19606    }
19607
19608    #[test]
19609    fn selection_preserves_valid_named_and_numeric_keys() {
19610        let ctx = workflow_context(Vec::new());
19611        let mut selection = Box::pin(ctx.select_keyed(vec![
19612            (
19613                SelectionKey::Index(0),
19614                ParallelOperation::activity("numeric", json!([])),
19615            ),
19616            (
19617                SelectionKey::Name("named".to_string()),
19618                ParallelOperation::timer(Duration::from_secs(1)),
19619            ),
19620        ]));
19621        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19622
19623        assert!(matches!(
19624            selection.as_mut().poll(&mut task_context),
19625            Poll::Pending
19626        ));
19627        let commands = ctx.take_commands().expect("selection commands");
19628        assert_eq!(commands[0]["selection_member_key"], json!(0));
19629        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19630    }
19631
19632    #[test]
19633    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19634        let history = canonical_selection_history();
19635        assert_persisted_selection_replay(history.clone());
19636
19637        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19638            .join("tests/fixtures/durable_selection_runtime_history.json");
19639        let output =
19640            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19641                .args([
19642                    "--exact",
19643                    "tests::selection_fresh_process_entrypoint",
19644                    "--nocapture",
19645                ])
19646                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19647                .output()
19648                .expect("run fresh selection replay process");
19649
19650        assert!(
19651            output.status.success(),
19652            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19653            String::from_utf8_lossy(&output.stdout),
19654            String::from_utf8_lossy(&output.stderr),
19655        );
19656    }
19657
19658    #[test]
19659    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19660        let mut history = canonical_selection_history();
19661        history.retain(|event| event.event_type != "SelectionResolved");
19662        let ctx = workflow_context(history);
19663        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19664        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19665
19666        assert!(matches!(
19667            selection.as_mut().poll(&mut task_context),
19668            Poll::Pending
19669        ));
19670        assert!(ctx.take_commands().expect("commands").is_empty());
19671        assert!(
19672            ctx.matched_recorded_pending()
19673                .expect("selection pending state"),
19674            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19675        );
19676    }
19677
19678    #[test]
19679    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19680        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19681            ("ConditionWaitSatisfied", true, None),
19682            ("ConditionWaitTimedOut", false, Some(0)),
19683        ] {
19684            let member = SelectionMemberMetadata {
19685                key: SelectionKey::Name("condition".to_string()),
19686                index: 0,
19687                base_sequence: 1,
19688                size: 1,
19689                kind: "condition".to_string(),
19690            };
19691            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19692            let mut payload = json!({
19693                "sequence": 1,
19694                "condition_wait_id": "condition-1",
19695                "condition_wait_occurrence_id": "rust:condition-wait:0",
19696                "condition_key": "ready",
19697                "condition_definition_fingerprint": "sha256:ready-v1",
19698                "parallel_group_path": path,
19699            });
19700            payload
19701                .as_object_mut()
19702                .expect("condition history payload")
19703                .extend(
19704                    serde_json::to_value(&path[0])
19705                        .expect("condition selection metadata")
19706                        .as_object()
19707                        .expect("condition selection metadata object")
19708                        .clone(),
19709                );
19710            if let Some(timeout_seconds) = timeout_seconds {
19711                payload["timeout_seconds"] = json!(timeout_seconds);
19712            }
19713            let history = vec![
19714                history_event("ConditionWaitOpened", payload.clone()),
19715                history_event(terminal_event, payload),
19716            ];
19717            let ctx = workflow_context(history);
19718            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19719            if timeout_seconds.is_some() {
19720                options = options.timeout(Duration::ZERO);
19721            }
19722            let mut selection = Box::pin(ctx.select_keyed(vec![(
19723                "condition",
19724                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19725            )]));
19726            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19727
19728            assert!(matches!(
19729                selection.as_mut().poll(&mut task_context),
19730                Poll::Pending
19731            ));
19732            assert!(ctx.take_commands().expect("commands").is_empty());
19733            assert!(
19734                ctx.matched_recorded_pending()
19735                    .expect("condition selection pending state"),
19736                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19737            );
19738        }
19739    }
19740
19741    #[test]
19742    fn selection_immediate_condition_members_open_a_durable_wait() {
19743        for predicate_satisfied in [true, false] {
19744            let ctx = workflow_context(Vec::new());
19745            let mut selection = Box::pin(ctx.select_keyed(vec![(
19746                "condition",
19747                ParallelOperation::condition(
19748                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19749                    move || Ok(predicate_satisfied),
19750                ),
19751            )]));
19752            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19753
19754            assert!(matches!(
19755                selection.as_mut().poll(&mut task_context),
19756                Poll::Pending
19757            ));
19758            let commands = ctx.take_commands().expect("condition selection command");
19759            assert_eq!(commands.len(), 1);
19760            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19761            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19762            assert_eq!(
19763                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19764                json!("select")
19765            );
19766        }
19767    }
19768
19769    #[test]
19770    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19771        let history = vec![
19772            selection_activity_event("ActivityScheduled", 0, "slow", None),
19773            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19774            selection_winner_marker(),
19775        ];
19776        let ctx = workflow_context(history.clone());
19777        let mut call = Box::pin(keyed_activity_selection(&ctx));
19778        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19779        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19780            panic!("winner must replay");
19781        };
19782        let slow = selected
19783            .handle(&SelectionKey::Name("slow".to_string()))
19784            .expect("slow handle")
19785            .clone();
19786        let mut cancel = Box::pin(slow.cancel());
19787        assert!(matches!(
19788            cancel.as_mut().poll(&mut task_context),
19789            Poll::Ready(Ok(()))
19790        ));
19791        assert!(matches!(
19792            cancel.as_mut().poll(&mut task_context),
19793            Poll::Ready(Ok(()))
19794        ));
19795        let mut outcome = Box::pin(slow.await_result());
19796        assert!(matches!(
19797            outcome.as_mut().poll(&mut task_context),
19798            Poll::Pending
19799        ));
19800        let commands = ctx.take_commands().expect("cancel command");
19801        assert_eq!(commands.len(), 1);
19802        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19803        assert_eq!(commands[0]["member_key"], json!("slow"));
19804
19805        let mut cancelled_history = history;
19806        cancelled_history.push(history_event(
19807            "SelectionOperationCancelled",
19808            json!({
19809                "selection_group_id": "select-calls:1:2",
19810                "member_key": "slow",
19811                "member_index": 0,
19812                "member_base_sequence": 1,
19813                "member_size": 1,
19814                "operation_kind": "activity",
19815                "operation_identity": "activity-slow",
19816                "cancelled_at": "2026-08-27T00:00:00Z",
19817            }),
19818        ));
19819        let replayed = workflow_context(cancelled_history);
19820        let mut call = Box::pin(keyed_activity_selection(&replayed));
19821        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19822            panic!("winner must replay after cancellation");
19823        };
19824        let slow = selected
19825            .handle(&SelectionKey::Name("slow".to_string()))
19826            .expect("slow handle")
19827            .clone();
19828        let mut cancel = Box::pin(slow.cancel());
19829        assert!(matches!(
19830            cancel.as_mut().poll(&mut task_context),
19831            Poll::Ready(Ok(()))
19832        ));
19833        assert!(replayed.take_commands().expect("commands").is_empty());
19834    }
19835
19836    #[test]
19837    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19838        let base_history = vec![
19839            selection_activity_event("ActivityScheduled", 0, "slow", None),
19840            selection_activity_event("ActivityScheduled", 1, "fast", None),
19841            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19842            selection_winner_marker(),
19843        ];
19844        for (field, corrupt) in [
19845            ("member_key", json!("fast")),
19846            ("member_index", json!(1)),
19847            ("member_base_sequence", json!(3)),
19848            ("member_size", json!(2)),
19849            ("operation_kind", json!("timer")),
19850            ("operation_identity", json!("forged")),
19851        ] {
19852            let mut cancellation = json!({
19853                "selection_group_id": "select-calls:1:2",
19854                "member_key": "slow",
19855                "member_index": 0,
19856                "member_base_sequence": 1,
19857                "member_size": 1,
19858                "operation_kind": "activity",
19859                "operation_identity": "activity-slow",
19860            });
19861            cancellation[field] = corrupt;
19862            let mut history = base_history.clone();
19863            history.push(history_event("SelectionOperationCancelled", cancellation));
19864            let ctx = workflow_context(history);
19865            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19866            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19867
19868            assert!(matches!(
19869                selection.as_mut().poll(&mut task_context),
19870                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19871            ));
19872        }
19873    }
19874
19875    #[test]
19876    fn selection_child_identity_prefers_the_durable_run_id() {
19877        let ctx = workflow_context(vec![history_event(
19878            "ChildWorkflowScheduled",
19879            json!({
19880                "sequence": 1,
19881                "child_workflow_type": "child",
19882                "child_workflow_instance_id": "child-instance",
19883                "child_workflow_run_id": "child-run",
19884            }),
19885        )]);
19886        let state = ctx.state.lock().expect("workflow state");
19887
19888        assert_eq!(
19889            selection_operation_identity(&state, "child", 1, 1),
19890            "child-run"
19891        );
19892    }
19893
19894    #[test]
19895    fn selection_activity_identity_requires_canonical_execution_id() {
19896        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19897        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19898        let mut fast_completed =
19899            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19900        for event in [&mut fast_open, &mut fast_completed] {
19901            event
19902                .payload
19903                .as_object_mut()
19904                .expect("activity payload")
19905                .remove("activity_execution_id");
19906            event.payload["activity_id"] = json!("forged-activity-id");
19907        }
19908        let mut marker = selection_winner_marker();
19909        marker.payload["operation_identity"] = json!("forged-activity-id");
19910        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19911        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19912        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19913
19914        assert!(matches!(
19915            selection.as_mut().poll(&mut task_context),
19916            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19917        ));
19918    }
19919
19920    #[test]
19921    fn selection_completion_before_cancellation_remains_awaitable() {
19922        let history = vec![
19923            selection_activity_event("ActivityScheduled", 0, "slow", None),
19924            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19925            selection_winner_marker(),
19926            selection_activity_event(
19927                "ActivityCompleted",
19928                0,
19929                "slow",
19930                Some(json!("completed-first")),
19931            ),
19932        ];
19933        let ctx = workflow_context(history);
19934        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19935        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19936        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19937            panic!("winner must replay");
19938        };
19939        let slow = selected
19940            .handle(&SelectionKey::Name("slow".to_string()))
19941            .expect("slow handle")
19942            .clone();
19943        let mut cancel = Box::pin(slow.cancel());
19944        assert!(matches!(
19945            cancel.as_mut().poll(&mut task_context),
19946            Poll::Ready(Ok(()))
19947        ));
19948        let mut await_slow = Box::pin(slow.await_result());
19949        assert!(matches!(
19950            await_slow.as_mut().poll(&mut task_context),
19951            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19952        ));
19953        let commands = ctx.take_commands().expect("commands");
19954        assert!(commands.is_empty());
19955    }
19956
19957    #[test]
19958    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19959        let nested_member = SelectionMemberMetadata {
19960            key: SelectionKey::Name("nested".to_string()),
19961            index: 0,
19962            base_sequence: 1,
19963            size: 2,
19964            kind: "group".to_string(),
19965        };
19966        let deadline_member = SelectionMemberMetadata {
19967            key: SelectionKey::Name("deadline".to_string()),
19968            index: 1,
19969            base_sequence: 3,
19970            size: 1,
19971            kind: "timer".to_string(),
19972        };
19973        let nested_paths = [
19974            vec![
19975                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19976                parallel_group_entry(1, 2, 0, "activity"),
19977            ],
19978            vec![
19979                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19980                parallel_group_entry(1, 2, 1, "activity"),
19981            ],
19982        ];
19983        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
19984        let mut timer_fired = parallel_history_event(
19985            "TimerFired",
19986            3,
19987            "timer_id",
19988            "timer-3",
19989            deadline_path.clone(),
19990            None,
19991        );
19992        timer_fired.payload["delay_seconds"] = json!(0);
19993        timer_fired
19994            .raw
19995            .insert("id".to_string(), json!("timer-fired"));
19996        let mut timer_scheduled = parallel_history_event(
19997            "TimerScheduled",
19998            3,
19999            "timer_id",
20000            "timer-3",
20001            deadline_path,
20002            None,
20003        );
20004        timer_scheduled.payload["delay_seconds"] = json!(0);
20005        let history = vec![
20006            parallel_history_event(
20007                "ActivityScheduled",
20008                1,
20009                "activity_type",
20010                "nested-first",
20011                nested_paths[0].clone(),
20012                None,
20013            ),
20014            parallel_history_event(
20015                "ActivityScheduled",
20016                2,
20017                "activity_type",
20018                "nested-second",
20019                nested_paths[1].clone(),
20020                None,
20021            ),
20022            timer_scheduled,
20023            timer_fired,
20024            history_event(
20025                "SelectionResolved",
20026                json!({
20027                    "selection_group_id": "select-calls:1:3",
20028                    "selection_group_base_sequence": 1,
20029                    "selection_group_size": 3,
20030                    "member_key": "deadline",
20031                    "member_index": 1,
20032                    "member_base_sequence": 3,
20033                    "member_size": 1,
20034                    "operation_kind": "timer",
20035                    "operation_identity": "timer-3",
20036                    "outcome": "completed",
20037                    "resolution_event_id": "timer-fired",
20038                    "resolution_event_type": "TimerFired",
20039                }),
20040            ),
20041            parallel_history_event(
20042                "ActivityFailed",
20043                2,
20044                "activity_type",
20045                "nested-second",
20046                nested_paths[1].clone(),
20047                None,
20048            ),
20049        ];
20050        let ctx = workflow_context(history);
20051        let mut selection = Box::pin(ctx.select_keyed(vec![
20052            (
20053                "nested",
20054                ParallelOperation::group(vec![
20055                    ParallelOperation::activity("nested-first", json!([])),
20056                    ParallelOperation::activity("nested-second", json!([])),
20057                ]),
20058            ),
20059            ("deadline", ParallelOperation::timer(Duration::ZERO)),
20060        ]));
20061        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20062        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20063            panic!("deadline winner must replay");
20064        };
20065        let nested = selected
20066            .handle(&SelectionKey::Name("nested".to_string()))
20067            .expect("nested handle")
20068            .clone();
20069        let mut cancel = Box::pin(nested.cancel());
20070        assert!(matches!(
20071            cancel.as_mut().poll(&mut task_context),
20072            Poll::Ready(Ok(()))
20073        ));
20074        let mut await_nested = Box::pin(nested.await_result());
20075
20076        assert!(matches!(
20077            await_nested.as_mut().poll(&mut task_context),
20078            Poll::Ready(Err(Error::ActivityFailed(_)))
20079        ));
20080        assert!(ctx.take_commands().expect("commands").is_empty());
20081    }
20082
20083    #[test]
20084    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
20085        let ctx = workflow_context(Vec::new());
20086        let mut call = Box::pin(ctx.select(vec![
20087            ParallelOperation::child_workflow(
20088                "child",
20089                ChildWorkflowOptions::new("children"),
20090                json!([]),
20091            ),
20092            ParallelOperation::timer(Duration::from_secs(30)),
20093            ParallelOperation::signal("approval"),
20094            ParallelOperation::condition(
20095                ConditionWaitOptions::new("ready", "sha256:ready"),
20096                || Ok(false),
20097            ),
20098            ParallelOperation::group(vec![
20099                ParallelOperation::activity("nested-one", json!([])),
20100                ParallelOperation::activity("nested-two", json!([])),
20101            ]),
20102        ]));
20103        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20104        assert!(matches!(
20105            call.as_mut().poll(&mut task_context),
20106            Poll::Pending
20107        ));
20108        let commands = ctx.take_commands().expect("selection commands");
20109        assert_eq!(
20110            commands
20111                .iter()
20112                .map(|command| command["type"].as_str().unwrap_or_default())
20113                .collect::<Vec<_>>(),
20114            [
20115                "start_child_workflow",
20116                "start_timer",
20117                "open_signal_wait",
20118                "open_condition_wait",
20119                "schedule_activity",
20120                "schedule_activity",
20121            ]
20122        );
20123        assert!(commands.iter().all(|command| {
20124            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
20125        }));
20126        assert_eq!(
20127            commands[4]["parallel_group_path"].as_array().map(Vec::len),
20128            Some(2)
20129        );
20130        assert_eq!(
20131            commands[4]["parallel_group_path"][0]["selection_member_kind"],
20132            json!("group")
20133        );
20134        assert_eq!(
20135            commands[5]["parallel_group_path"][0]["selection_member_kind"],
20136            json!("group")
20137        );
20138
20139        let one_leaf_ctx = workflow_context(Vec::new());
20140        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
20141            ParallelOperation::activity("nested-only", json!([])),
20142        ])]));
20143        assert!(matches!(
20144            one_leaf.as_mut().poll(&mut task_context),
20145            Poll::Pending
20146        ));
20147        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
20148        assert_eq!(one_leaf_commands.len(), 1);
20149        assert_eq!(
20150            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
20151            json!("group")
20152        );
20153        assert_eq!(
20154            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
20155            json!(1)
20156        );
20157    }
20158
20159    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
20160        let mut saga = ctx.saga();
20161        let outcome = async {
20162            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20163            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20164            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
20165            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
20166            ctx.activity("trip.charge", json!([])).await?;
20167            Ok(json!({"status": "booked"}))
20168        }
20169        .await;
20170        saga.finish(outcome).await
20171    }
20172
20173    fn saga_activity(
20174        event_type: &str,
20175        sequence: u64,
20176        activity_type: &str,
20177        result: Option<Value>,
20178    ) -> HistoryEvent {
20179        let mut payload = json!({
20180            "sequence": sequence,
20181            "activity_type": activity_type,
20182            "message": format!("{activity_type} failed"),
20183            "exception_type": "PlannedFailure",
20184            "non_retryable": true,
20185        });
20186        if let Some(result) = result {
20187            payload["result"] = fixture_envelope(result);
20188        }
20189        history_event(event_type, payload)
20190    }
20191
20192    #[test]
20193    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
20194        let completed_hotel_compensation = saga_activity(
20195            "ActivityCompleted",
20196            4,
20197            "trip.cancel-hotel",
20198            Some(Value::Null),
20199        );
20200        let history = vec![
20201            saga_activity(
20202                "ActivityCompleted",
20203                1,
20204                "trip.reserve-flight",
20205                Some(json!("flight-1")),
20206            ),
20207            saga_activity(
20208                "ActivityCompleted",
20209                2,
20210                "trip.reserve-hotel",
20211                Some(json!("hotel-1")),
20212            ),
20213            saga_activity("ActivityFailed", 3, "trip.charge", None),
20214            completed_hotel_compensation.clone(),
20215            completed_hotel_compensation,
20216        ];
20217
20218        for _restart in 0..2 {
20219            let ctx = workflow_context(history.clone());
20220            let mut future = Box::pin(trip_saga(ctx.clone()));
20221            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20222            assert!(matches!(
20223                future.as_mut().poll(&mut task_context),
20224                Poll::Pending
20225            ));
20226            let commands = ctx.take_commands().expect("compensation command");
20227            assert_eq!(commands.len(), 1);
20228            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20229        }
20230    }
20231
20232    #[test]
20233    fn saga_compensation_failure_preserves_both_typed_failures() {
20234        let history = vec![
20235            saga_activity(
20236                "ActivityCompleted",
20237                1,
20238                "trip.reserve-flight",
20239                Some(json!("flight-1")),
20240            ),
20241            saga_activity(
20242                "ActivityCompleted",
20243                2,
20244                "trip.reserve-hotel",
20245                Some(json!("hotel-1")),
20246            ),
20247            saga_activity("ActivityFailed", 3, "trip.charge", None),
20248            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
20249        ];
20250        let ctx = workflow_context(history);
20251        let mut future = Box::pin(trip_saga(ctx));
20252        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20253        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
20254            future.as_mut().poll(&mut task_context)
20255        else {
20256            panic!("compensation failure must remain structured");
20257        };
20258        assert!(matches!(
20259            *failure.initiating_failure,
20260            Error::ActivityFailed(_)
20261        ));
20262        assert!(matches!(
20263            *failure.compensation_failure,
20264            Error::ActivityFailed(_)
20265        ));
20266        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
20267        assert_eq!(failure.compensation_registration_order, 2);
20268    }
20269
20270    #[test]
20271    fn saga_compensates_cooperative_cancellation() {
20272        let ctx = workflow_context(vec![saga_activity(
20273            "ActivityCompleted",
20274            1,
20275            "trip.reserve-flight",
20276            Some(json!("flight-1")),
20277        )]);
20278        ctx.state.lock().expect("state").cancel_requested = true;
20279        let run = {
20280            let ctx = ctx.clone();
20281            async move {
20282                let mut saga = ctx.saga();
20283                let outcome = async {
20284                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20285                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20286                    ctx.throw_if_cancellation_requested()?;
20287                    Ok(json!("unexpected"))
20288                }
20289                .await;
20290                saga.finish(outcome).await
20291            }
20292        };
20293        let mut future = Box::pin(run);
20294        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20295        assert!(matches!(
20296            future.as_mut().poll(&mut task_context),
20297            Poll::Pending
20298        ));
20299        let commands = ctx.take_commands().expect("cancellation compensation");
20300        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20301    }
20302
20303    #[test]
20304    fn optional_task_observability_fields_round_trip_without_interpretation() {
20305        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
20306        let dispatch = json!({"task_id": "other-task"});
20307        let links = json!({"links": []});
20308        let mut value = json!({
20309            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
20310            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
20311        });
20312        let workflow: WorkflowTask =
20313            serde_json::from_value(value.clone()).expect("legacy workflow task");
20314        let activity: ActivityTask =
20315            serde_json::from_value(value.clone()).expect("legacy activity task");
20316        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
20317        assert!(workflow.observability_context.is_none());
20318        assert!(activity.observability_context.is_none());
20319        assert!(query.observability_context.is_none());
20320        assert!(activity.workflow_id.is_none());
20321        assert!(activity.run_id.is_none());
20322        assert!(activity.activity_execution_id.is_none());
20323
20324        value["observability_context"] = context.clone();
20325        value["dispatch_observability_context"] = dispatch.clone();
20326        value["observability_links"] = links.clone();
20327        value["workflow_id"] = json!("workflow-id");
20328        value["run_id"] = json!("run-id");
20329        value["activity_execution_id"] = json!("activity-id");
20330        let workflow: WorkflowTask =
20331            serde_json::from_value(value.clone()).expect("workflow metadata");
20332        let activity: ActivityTask =
20333            serde_json::from_value(value.clone()).expect("activity metadata");
20334        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
20335        for fields in [
20336            (
20337                workflow.observability_context,
20338                workflow.dispatch_observability_context,
20339                workflow.observability_links,
20340            ),
20341            (
20342                activity.observability_context,
20343                activity.dispatch_observability_context,
20344                activity.observability_links,
20345            ),
20346            (
20347                query.observability_context,
20348                query.dispatch_observability_context,
20349                query.observability_links,
20350            ),
20351        ] {
20352            assert_eq!(
20353                fields,
20354                (
20355                    Some(context.clone()),
20356                    Some(dispatch.clone()),
20357                    Some(links.clone())
20358                )
20359            );
20360        }
20361        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
20362        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
20363        assert_eq!(
20364            activity.activity_execution_id.as_deref(),
20365            Some("activity-id")
20366        );
20367    }
20368
20369    fn workflow_task(
20370        workflow_type: &str,
20371        history_events: Vec<HistoryEvent>,
20372        payload_codec: &str,
20373    ) -> WorkflowTask {
20374        WorkflowTask {
20375            task_id: format!("wft-{workflow_type}"),
20376            observability_context: None,
20377            dispatch_observability_context: None,
20378            observability_links: None,
20379            workflow_command_id: None,
20380            workflow_id: Some(format!("wf-{workflow_type}")),
20381            run_id: Some(format!("run-{workflow_type}")),
20382            workflow_type: workflow_type.to_string(),
20383            cancel_requested: false,
20384            payload_codec: payload_codec.to_string(),
20385            arguments: Some(
20386                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
20387            ),
20388            total_history_events: Some(history_events.len() as u64),
20389            history_size_bytes: None,
20390            continue_as_new_recommended: None,
20391            history_budget_pressure: None,
20392            history_events,
20393            next_history_page_token: None,
20394            workflow_task_attempt: 1,
20395            workflow_signal_id: None,
20396            signal_name: None,
20397            signal_arguments: None,
20398            workflow_update_id: None,
20399            update_name: None,
20400            lease_owner: Some("rust-worker".to_string()),
20401        }
20402    }
20403
20404    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20405    struct SideEffectProbe {
20406        request_id: String,
20407        attempt: u32,
20408    }
20409
20410    #[test]
20411    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
20412        let calls = AtomicUsize::new(0);
20413        let ctx = workflow_context(Vec::new());
20414        let value = ctx
20415            .side_effect(|| {
20416                calls.fetch_add(1, Ordering::SeqCst);
20417                SideEffectProbe {
20418                    request_id: "request-42".to_string(),
20419                    attempt: 3,
20420                }
20421            })
20422            .expect("first side effect");
20423        assert_eq!(value.attempt, 3);
20424        assert_eq!(calls.load(Ordering::SeqCst), 1);
20425        let commands = ctx.take_commands().expect("commands");
20426        assert_eq!(commands.len(), 1);
20427        assert_eq!(commands[0]["type"], "record_side_effect");
20428        assert_eq!(
20429            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20430            serde_json::to_value(&value).expect("value")
20431        );
20432
20433        let replay = workflow_context(vec![history_event(
20434            "SideEffectRecorded",
20435            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20436        )]);
20437        let replayed: SideEffectProbe = replay
20438            .side_effect(|| {
20439                calls.fetch_add(1, Ordering::SeqCst);
20440                panic!("committed side-effect callbacks must not run during replay")
20441            })
20442            .expect("replayed side effect");
20443        assert_eq!(replayed, value);
20444        assert_eq!(calls.load(Ordering::SeqCst), 1);
20445        assert!(replay.take_commands().expect("commands").is_empty());
20446        replay.ensure_history_consumed().expect("history consumed");
20447    }
20448
20449    #[test]
20450    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
20451        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20452        let value = ctx
20453            .side_effect(|| SideEffectProbe {
20454                request_id: "avro-request".to_string(),
20455                attempt: 1,
20456            })
20457            .expect("Avro side effect");
20458        let uuid = ctx.uuid_v4().expect("deterministic UUID");
20459        let commands = ctx.take_commands().expect("commands");
20460        assert_eq!(commands.len(), 2);
20461        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
20462        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
20463        assert_eq!(
20464            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20465            serde_json::to_value(&value).expect("value")
20466        );
20467
20468        let replay = workflow_context_with_codec(
20469            vec![
20470                history_event(
20471                    "SideEffectRecorded",
20472                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20473                ),
20474                history_event(
20475                    "SideEffectRecorded",
20476                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
20477                ),
20478            ],
20479            DEFAULT_CODEC,
20480        );
20481        let replayed: SideEffectProbe = replay
20482            .side_effect(|| panic!("Avro callback must not run"))
20483            .expect("replayed Avro value");
20484        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
20485        assert_eq!(replayed, value);
20486        assert_eq!(replayed_uuid, uuid);
20487        assert!(replay.take_commands().expect("commands").is_empty());
20488    }
20489
20490    #[test]
20491    fn typed_side_effect_replay_preserves_bytes_and_maps() {
20492        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20493        let value = ctx
20494            .side_effect_avro_value(typed_fidelity_probe)
20495            .expect("typed side effect");
20496        let commands = ctx.take_commands().expect("side-effect command");
20497        assert_eq!(
20498            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20499                .expect("recorded side effect"),
20500            value
20501        );
20502
20503        let replay = workflow_context_with_codec(
20504            vec![history_event(
20505                "SideEffectRecorded",
20506                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20507            )],
20508            DEFAULT_CODEC,
20509        );
20510        assert_eq!(
20511            replay
20512                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
20513                .expect("replayed typed side effect"),
20514            value
20515        );
20516    }
20517
20518    #[test]
20519    fn ordered_side_effects_share_the_durable_command_stream() {
20520        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
20521        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
20522        let ctx = workflow_context(vec![
20523            history_event(
20524                "SideEffectRecorded",
20525                json!({"sequence": 1, "result": first}),
20526            ),
20527            history_event(
20528                "SideEffectRecorded",
20529                json!({"sequence": 2, "result": second}),
20530            ),
20531        ]);
20532        let first: String = ctx
20533            .side_effect(|| panic!("first callback must not run"))
20534            .expect("first replay");
20535        let second: i32 = ctx
20536            .side_effect(|| panic!("second callback must not run"))
20537            .expect("second replay");
20538        assert_eq!(first, "first");
20539        assert_eq!(second, 29);
20540        ctx.ensure_history_consumed().expect("ordered history");
20541
20542        let reordered = workflow_context(vec![history_event(
20543            "VersionMarkerRecorded",
20544            json!({
20545                "sequence": 1,
20546                "change_id": "before-side-effect",
20547                "version": 1,
20548                "min_supported": 1,
20549                "max_supported": 1,
20550            }),
20551        )]);
20552        let error = reordered
20553            .side_effect(|| "new".to_string())
20554            .expect_err("command reordering must fail");
20555        assert!(matches!(
20556            error,
20557            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20558                if reason == "recorded_command_mismatch"
20559        ));
20560    }
20561
20562    #[test]
20563    fn legacy_patch_preserves_pending_and_completed_activity_history() {
20564        for completed in [false, true] {
20565            let mut history = vec![history_event(
20566                "ActivityScheduled",
20567                json!({"sequence": 1, "activity_type": "old"}),
20568            )];
20569            if completed {
20570                history.push(history_event(
20571                    "ActivityCompleted",
20572                    json!({
20573                        "sequence": 1,
20574                        "activity_type": "old",
20575                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
20576                    }),
20577                ));
20578            }
20579            for _cold_replay in 0..2 {
20580                let ctx = workflow_context(history.clone());
20581                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
20582                assert!(!ctx.patched("added-step").expect("same frozen decision"));
20583                ctx.deprecate_patch("added-step")
20584                    .expect("retained boundary");
20585                let mut activity = Box::pin(ctx.activity("old", json!([])));
20586                let mut context = TaskContext::from_waker(noop_waker_ref());
20587                match activity.as_mut().poll(&mut context) {
20588                    Poll::Ready(result) => {
20589                        assert!(completed);
20590                        assert_eq!(result.expect("recorded result"), json!(41));
20591                        ctx.ensure_history_consumed().expect("old command retained");
20592                    }
20593                    Poll::Pending => assert!(!completed),
20594                }
20595                assert!(ctx.take_commands().expect("commands").is_empty());
20596            }
20597        }
20598    }
20599
20600    #[test]
20601    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
20602        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
20603        assert!(!ctx.patched("added-step").expect("legacy completed run"));
20604        ctx.deprecate_patch("added-step")
20605            .expect("same legacy decision");
20606        assert!(ctx.take_commands().expect("commands").is_empty());
20607        ctx.ensure_history_consumed().expect("completed history");
20608    }
20609
20610    #[test]
20611    fn legacy_patch_rejects_a_range_without_the_original_branch() {
20612        let ctx = workflow_context(vec![history_event(
20613            "ActivityScheduled",
20614            json!({"sequence": 1, "activity_type": "old"}),
20615        )]);
20616        let error = ctx
20617            .get_version("added-step", 0, 1)
20618            .expect_err("legacy is unsupported");
20619        assert!(matches!(
20620            error,
20621            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20622                if reason == "version_marker_incompatible_range"
20623        ));
20624        assert!(!ctx
20625            .patched("supported-step")
20626            .expect("failed check did not consume history"));
20627        assert!(ctx.take_commands().expect("commands").is_empty());
20628    }
20629
20630    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20631        let mut event = history_event(
20632            "VersionMarkerRecorded",
20633            json!({
20634                "sequence": sequence,
20635                "change_id": "retained-patch",
20636                "version": version,
20637                "min_supported": -1,
20638                "max_supported": 1,
20639            }),
20640        );
20641        event.raw.insert("timestamp".into(), json!(time));
20642        event
20643    }
20644
20645    #[test]
20646    fn retained_patch_markers_preserve_each_original_boundary() {
20647        for completed in [false, true] {
20648            let mut history = vec![
20649                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20650                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20651                history_event(
20652                    "ActivityScheduled",
20653                    json!({"sequence": 3, "activity_type": "old"}),
20654                ),
20655            ];
20656            if completed {
20657                history.push(history_event(
20658                    "ActivityCompleted",
20659                    json!({
20660                        "sequence": 3,
20661                        "activity_type": "old",
20662                        "result": fixture_envelope(json!(41)),
20663                    }),
20664                ));
20665            }
20666            for _cold_replay in 0..2 {
20667                let ctx = workflow_context(history.clone());
20668                assert!(ctx.patched("retained-patch").unwrap());
20669                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20670                assert!(ctx.patched("retained-patch").unwrap());
20671                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20672                ctx.deprecate_patch("retained-patch").unwrap();
20673                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20674                let mut activity = Box::pin(ctx.activity("old", json!([])));
20675                let mut context = TaskContext::from_waker(noop_waker_ref());
20676                match activity.as_mut().poll(&mut context) {
20677                    Poll::Ready(result) => {
20678                        assert!(completed);
20679                        assert_eq!(result.unwrap(), json!(41));
20680                        ctx.ensure_history_consumed().unwrap();
20681                    }
20682                    Poll::Pending => assert!(!completed),
20683                }
20684                assert!(ctx.take_commands().unwrap().is_empty());
20685                let state = ctx.state.lock().unwrap();
20686                for (actual, original) in state.history_events.iter().zip(&history) {
20687                    assert_eq!(actual.payload, original.payload);
20688                    assert_eq!(actual.raw, original.raw);
20689                }
20690            }
20691        }
20692    }
20693
20694    #[test]
20695    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20696        let ctx = workflow_context(vec![
20697            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20698            history_event(
20699                "SideEffectRecorded",
20700                json!({
20701                    "sequence": 2, "result": fixture_envelope(json!("between")),
20702                }),
20703            ),
20704            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20705            history_event(
20706                "VersionMarkerRecorded",
20707                json!({
20708                    "sequence": 4, "change_id": "other-patch", "version": 1,
20709                    "min_supported": -1, "max_supported": 1,
20710                }),
20711            ),
20712        ]);
20713        assert!(ctx.patched("retained-patch").unwrap());
20714        assert!(ctx.patched("retained-patch").unwrap());
20715        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20716        assert_eq!(
20717            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20718            "between"
20719        );
20720        ctx.deprecate_patch("retained-patch").unwrap();
20721        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20722        ctx.deprecate_patch("retained-patch").unwrap();
20723        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20724        assert!(ctx.patched("other-patch").unwrap());
20725        ctx.ensure_history_consumed().unwrap();
20726        assert!(ctx.take_commands().unwrap().is_empty());
20727    }
20728
20729    #[test]
20730    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20731        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20732        alias.payload["max_supported"] = json!(3);
20733        let ctx = workflow_context(vec![
20734            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20735            alias,
20736        ]);
20737        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20738        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20739        assert!(matches!(error,
20740            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20741                if reason == "version_marker_incompatible_range"));
20742        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20743        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20744        ctx.ensure_history_consumed().unwrap();
20745        assert!(ctx.take_commands().unwrap().is_empty());
20746    }
20747
20748    #[test]
20749    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20750        let ctx = workflow_context(Vec::new());
20751        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20752        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20753        assert!(ctx.patched("new-search").expect("patch"));
20754        ctx.deprecate_patch("new-search").expect("deprecate patch");
20755        let commands = ctx.take_commands().expect("commands");
20756        assert_eq!(commands.len(), 2);
20757        assert_eq!(commands[0]["type"], "record_version_marker");
20758        assert_eq!(commands[0]["version"], 2);
20759        assert_eq!(commands[1]["change_id"], "new-search");
20760
20761        let replay = workflow_context(vec![history_event(
20762            "VersionMarkerRecorded",
20763            json!({
20764                "sequence": 1,
20765                "change_id": "checkout-v2",
20766                "version": 2,
20767                "min_supported": 1,
20768                "max_supported": 2,
20769            }),
20770        )]);
20771        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20772        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20773        assert!(replay.take_commands().expect("commands").is_empty());
20774        replay.ensure_history_consumed().expect("history consumed");
20775    }
20776
20777    #[test]
20778    fn version_markers_reject_incompatible_or_malformed_history() {
20779        let incompatible = workflow_context(vec![history_event(
20780            "VersionMarkerRecorded",
20781            json!({
20782                "sequence": 1,
20783                "change_id": "checkout-v2",
20784                "version": 1,
20785                "min_supported": 1,
20786                "max_supported": 2,
20787            }),
20788        )]);
20789        let error = incompatible
20790            .get_version("checkout-v2", 2, 3)
20791            .expect_err("old version is unsupported");
20792        assert!(matches!(
20793            error,
20794            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20795                if reason == "version_marker_incompatible_range"
20796        ));
20797
20798        for (history, reason) in [
20799            (
20800                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20801                "side_effect_result_missing",
20802            ),
20803            (
20804                vec![history_event(
20805                    "SideEffectRecorded",
20806                    json!({
20807                        "sequence": 1,
20808                        "result": {"codec": "avro", "blob": "not-base64"},
20809                    }),
20810                )],
20811                "side_effect_payload_incompatible",
20812            ),
20813            (
20814                vec![history_event(
20815                    "SideEffectRecorded",
20816                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20817                )],
20818                "side_effect_payload_malformed",
20819            ),
20820            (
20821                vec![history_event(
20822                    "VersionMarkerRecorded",
20823                    json!({
20824                        "sequence": 1,
20825                        "change_id": "change",
20826                        "version": 1,
20827                        "min_supported": 2,
20828                        "max_supported": 1,
20829                    }),
20830                )],
20831                "version_marker_history_range_invalid",
20832            ),
20833        ] {
20834            let error = WorkflowState::new(
20835                history,
20836                "rust-workers".to_string(),
20837                DEFAULT_CODEC.to_string(),
20838                None,
20839            )
20840            .expect_err("malformed history must fail");
20841            assert!(matches!(
20842                error,
20843                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20844                    if actual == reason
20845            ));
20846        }
20847    }
20848
20849    #[test]
20850    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20851        let history = vec![history_event(
20852            "SearchAttributesUpserted",
20853            json!({
20854                "sequence": 1,
20855                "attributes": {"customer_tier": "gold"},
20856                "attribute_types": {"customer_tier": "keyword"},
20857                "merged": {"customer_tier": "gold"}
20858            }),
20859        )];
20860
20861        let matching = workflow_context(history.clone());
20862        matching
20863            .upsert_search_attributes(
20864                SearchAttributeUpdate::new()
20865                    .keyword("customer_tier", "gold")
20866                    .expect("keyword update"),
20867            )
20868            .expect("matching typed update must replay");
20869        matching
20870            .ensure_history_consumed()
20871            .expect("history consumed");
20872
20873        let changed_type = workflow_context(history.clone());
20874        let error = changed_type
20875            .upsert_search_attributes(
20876                SearchAttributeUpdate::new()
20877                    .string("customer_tier", "gold")
20878                    .expect("string update"),
20879            )
20880            .expect_err("same JSON value with a different declaration must be nondeterministic");
20881        let Error::NonDeterministicReplay(failure) = error else {
20882            panic!("typed identity drift must be a replay failure");
20883        };
20884        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20885        assert_eq!(failure.sequence, Some(1));
20886
20887        let changed_value = workflow_context(history);
20888        let error = changed_value
20889            .upsert_search_attributes(
20890                SearchAttributeUpdate::new()
20891                    .keyword("customer_tier", "platinum")
20892                    .expect("keyword update"),
20893            )
20894            .expect_err("changed values must be nondeterministic");
20895        let Error::NonDeterministicReplay(failure) = error else {
20896            panic!("value drift must be a replay failure");
20897        };
20898        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20899    }
20900
20901    #[test]
20902    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20903        let history = vec![history_event(
20904            "SearchAttributesUpserted",
20905            json!({
20906                "sequence": 1,
20907                "attributes": {"customer_tier": "gold"},
20908                "merged": {"customer_tier": "gold"}
20909            }),
20910        )];
20911
20912        for update in [
20913            SearchAttributeUpdate::new()
20914                .keyword("customer_tier", "gold")
20915                .expect("keyword update"),
20916            SearchAttributeUpdate::new()
20917                .string("customer_tier", "gold")
20918                .expect("string update"),
20919        ] {
20920            let restarted = workflow_context(history.clone());
20921            restarted
20922                .upsert_search_attributes(update)
20923                .expect("legacy history constrains values but has unknown type identity");
20924            restarted
20925                .ensure_history_consumed()
20926                .expect("history consumed");
20927        }
20928    }
20929
20930    #[test]
20931    fn search_attribute_command_emits_canonical_types() {
20932        let ctx = workflow_context(Vec::new());
20933        ctx.upsert_search_attributes(
20934            SearchAttributeUpdate::new()
20935                .keyword("customer_tier", "gold")
20936                .expect("keyword update")
20937                .int("attempts", 3)
20938                .expect("int update")
20939                .delete("obsolete")
20940                .expect("delete update"),
20941        )
20942        .expect("valid search attributes");
20943
20944        assert_eq!(
20945            ctx.take_commands().expect("commands"),
20946            vec![json!({
20947                "type": "upsert_search_attributes",
20948                "attributes": {
20949                    "attempts": 3,
20950                    "customer_tier": "gold",
20951                    "obsolete": null
20952                },
20953                "attribute_types": {
20954                    "attempts": "int",
20955                    "customer_tier": "keyword"
20956                }
20957            })]
20958        );
20959    }
20960
20961    #[test]
20962    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20963        let duplicate_side_effect = WorkflowState::new(
20964            vec![
20965                history_event(
20966                    "SideEffectRecorded",
20967                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
20968                ),
20969                history_event(
20970                    "SideEffectRecorded",
20971                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
20972                ),
20973            ],
20974            "rust-workers".to_string(),
20975            DEFAULT_CODEC.to_string(),
20976            None,
20977        )
20978        .expect_err("duplicate side effect");
20979        assert!(matches!(
20980            duplicate_side_effect,
20981            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20982                if reason == "duplicate_side_effect_record"
20983        ));
20984
20985        let marker = |sequence, version| {
20986            history_event(
20987                "VersionMarkerRecorded",
20988                json!({
20989                    "sequence": sequence,
20990                    "change_id": "same-change",
20991                    "version": version,
20992                    "min_supported": -1,
20993                    "max_supported": 1,
20994                }),
20995            )
20996        };
20997        let duplicate_marker = WorkflowState::new(
20998            vec![marker(1, 1), marker(3, -1)],
20999            "rust-workers".to_string(),
21000            DEFAULT_CODEC.to_string(),
21001            None,
21002        )
21003        .expect_err("conflicting marker");
21004        assert!(matches!(
21005            duplicate_marker,
21006            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21007                if reason == "version_marker_conflict"
21008        ));
21009    }
21010
21011    #[test]
21012    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
21013        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
21014        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21015        invalid_alias.payload["max_supported"] = json!(0);
21016        for (history, expected_reason) in [
21017            (
21018                vec![marker.clone(), marker.clone()],
21019                "duplicate_version_marker_record",
21020            ),
21021            (
21022                vec![marker, invalid_alias],
21023                "version_marker_history_range_invalid",
21024            ),
21025        ] {
21026            let error =
21027                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
21028                    .expect_err("invalid historical alias");
21029            assert!(matches!(error,
21030                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
21031                    if reason == expected_reason));
21032        }
21033    }
21034
21035    #[test]
21036    fn retained_patch_aliases_require_the_original_call_boundary() {
21037        let ctx = workflow_context(vec![
21038            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21039            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21040        ]);
21041        assert!(ctx.patched("retained-patch").unwrap());
21042        assert!(ctx.ensure_history_consumed().is_err());
21043        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21044        ctx.deprecate_patch("retained-patch").unwrap();
21045        ctx.ensure_history_consumed().unwrap();
21046        assert!(ctx.take_commands().unwrap().is_empty());
21047    }
21048
21049    #[test]
21050    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
21051        let ctx = workflow_context(vec![
21052            history_event(
21053                "SideEffectRecorded",
21054                json!({
21055                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
21056                }),
21057            ),
21058            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21059        ]);
21060        assert!(!ctx.patched("retained-patch").unwrap());
21061        assert_eq!(
21062            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21063            "old-operation"
21064        );
21065        let error = ctx.patched("retained-patch").unwrap_err();
21066        assert!(matches!(error,
21067            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21068                if reason == "version_marker_conflict"));
21069        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21070        assert!(ctx.take_commands().unwrap().is_empty());
21071    }
21072
21073    #[test]
21074    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
21075        let mut state = WorkflowState::new(
21076            Vec::new(),
21077            "rust-workers".to_string(),
21078            DEFAULT_CODEC.to_string(),
21079            None,
21080        )
21081        .expect("workflow state");
21082        state.workflow_command_identity = "command-7".to_string();
21083        let context = WorkflowContext {
21084            state: Arc::new(Mutex::new(state)),
21085            cancellation_scope_id: "root".into(),
21086        };
21087        let item =
21088            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
21089
21090        context
21091            .append_workflow_stream("output", &[item], Some(10))
21092            .expect("append command");
21093        context
21094            .error_workflow_stream("output", "producer failed", None)
21095            .expect("error command");
21096        let commands = context.take_commands().expect("commands");
21097
21098        assert_eq!(commands[0]["type"], "record_side_effect");
21099        assert_eq!(
21100            commands[0]["workflow_stream"]["command_identity"],
21101            "command-7"
21102        );
21103        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
21104        assert_eq!(
21105            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21106            "dw-stream:command-7:0:0"
21107        );
21108        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
21109
21110        let recorded = history_event(
21111            "SideEffectRecorded",
21112            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
21113        );
21114        let mut replay_state = WorkflowState::new(
21115            vec![recorded],
21116            "rust-workers".to_string(),
21117            DEFAULT_CODEC.to_string(),
21118            None,
21119        )
21120        .expect("replay state");
21121        replay_state.workflow_command_identity = "command-7".to_string();
21122        let replay_context = WorkflowContext {
21123            state: Arc::new(Mutex::new(replay_state)),
21124            cancellation_scope_id: "root".into(),
21125        };
21126        replay_context
21127            .append_workflow_stream(
21128                "output",
21129                &[WorkflowStreamAppendItem::from_reference(
21130                    "s3://bucket/item.avro",
21131                )],
21132                Some(10),
21133            )
21134            .expect("replayed append");
21135        assert!(replay_context
21136            .take_commands()
21137            .expect("replayed commands")
21138            .is_empty());
21139    }
21140
21141    #[test]
21142    fn workflow_stream_authoring_requires_server_durable_command_identity() {
21143        let context = workflow_context(Vec::new());
21144        let error = context
21145            .append_workflow_stream(
21146                "output",
21147                &[WorkflowStreamAppendItem::from_reference(
21148                    "s3://bucket/item.avro",
21149                )],
21150                None,
21151            )
21152            .expect_err("stream append without durable command identity must fail closed");
21153
21154        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
21155        assert!(context.take_commands().expect("commands").is_empty());
21156    }
21157
21158    #[test]
21159    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
21160        let client = Client::builder("http://localhost:8080").build().unwrap();
21161        let mut worker = Worker::new(client, "rust-workers");
21162        worker.register_workflow("streams.worker", |ctx, _| async move {
21163            ctx.append_workflow_stream(
21164                "output",
21165                &[WorkflowStreamAppendItem::new(json!("hello"))?],
21166                None,
21167            )?;
21168            ctx.close_workflow_stream("output", None)?;
21169            Ok(json!("done"))
21170        });
21171        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
21172            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21173            task.workflow_command_id = command_id.clone();
21174            let expected_identity = command_id
21175                .as_deref()
21176                .filter(|id| !id.is_empty())
21177                .unwrap_or(&task.task_id)
21178                .to_string();
21179            let commands = worker
21180                .execute_workflow_task(task)
21181                .expect("ordinary worker stream output");
21182            assert_eq!(commands.len(), 3);
21183            assert_eq!(
21184                commands[0]["workflow_stream"]["command_identity"],
21185                expected_identity
21186            );
21187            assert_eq!(
21188                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21189                format!("dw-stream:{expected_identity}:0:0")
21190            );
21191            assert_eq!(
21192                commands[1]["workflow_stream"]["command_identity"],
21193                expected_identity
21194            );
21195            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
21196            let history = commands[..2]
21197                .iter()
21198                .enumerate()
21199                .map(|(index, command)| {
21200                    history_event(
21201                        "SideEffectRecorded",
21202                        json!({"sequence":index + 1,"result":command["result"]}),
21203                    )
21204                })
21205                .collect();
21206            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
21207            replay.task_id = "replacement-task".to_string();
21208            let replayed = worker
21209                .execute_workflow_task(replay)
21210                .expect("replacement worker consumes recorded stream effects");
21211            assert_eq!(replayed.len(), 1);
21212            assert_eq!(replayed[0]["type"], "complete_workflow");
21213        }
21214        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21215        missing.task_id.clear();
21216        assert!(matches!(
21217            worker.execute_workflow_task(missing),
21218            Err(Error::MissingWorkflowCommandIdentity)
21219        ));
21220    }
21221
21222    #[test]
21223    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
21224        fn worker(calls: Arc<AtomicUsize>) -> Worker {
21225            let client = Client::new("http://127.0.0.1:8080").expect("client");
21226            let mut worker = Worker::new(client, "rust-workers");
21227            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
21228                let calls = Arc::clone(&calls);
21229                async move {
21230                    let captured = ctx.side_effect(|| {
21231                        calls.fetch_add(1, Ordering::SeqCst);
21232                        "captured-once".to_string()
21233                    })?;
21234                    let version = ctx.get_version("cold-restart", 1, 2)?;
21235                    Ok(json!({"captured": captured, "version": version}))
21236                }
21237            });
21238            worker
21239        }
21240
21241        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
21242            WorkflowTask {
21243                task_id: "wft-side-effect-version".to_string(),
21244                observability_context: None,
21245                dispatch_observability_context: None,
21246                observability_links: None,
21247                workflow_command_id: None,
21248                workflow_id: Some("wf-side-effect-version".to_string()),
21249                run_id: Some("run-side-effect-version".to_string()),
21250                workflow_type: "rust.side-effect-version".to_string(),
21251                cancel_requested: false,
21252                payload_codec: DEFAULT_CODEC.to_string(),
21253                arguments: Some(
21254                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
21255                ),
21256                history_events,
21257                total_history_events: None,
21258                history_size_bytes: None,
21259                continue_as_new_recommended: None,
21260                history_budget_pressure: None,
21261                next_history_page_token: None,
21262                workflow_task_attempt: 1,
21263                workflow_signal_id: None,
21264                signal_name: None,
21265                signal_arguments: None,
21266                workflow_update_id: None,
21267                update_name: None,
21268                lease_owner: Some("rust-worker".to_string()),
21269            }
21270        }
21271
21272        let calls = Arc::new(AtomicUsize::new(0));
21273        let initial = worker(Arc::clone(&calls))
21274            .execute_workflow_task(task(Vec::new()))
21275            .expect("initial execution");
21276        assert_eq!(
21277            initial
21278                .iter()
21279                .map(|command| &command["type"])
21280                .collect::<Vec<_>>(),
21281            vec![
21282                "record_side_effect",
21283                "record_version_marker",
21284                "complete_workflow"
21285            ]
21286        );
21287        assert_eq!(calls.load(Ordering::SeqCst), 1);
21288
21289        let restarted = worker(Arc::clone(&calls));
21290        let replayed = restarted
21291            .execute_workflow_task(task(vec![
21292                history_event(
21293                    "SideEffectRecorded",
21294                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
21295                ),
21296                history_event(
21297                    "VersionMarkerRecorded",
21298                    json!({
21299                        "sequence": 2,
21300                        "change_id": "cold-restart",
21301                        "version": 2,
21302                        "min_supported": 1,
21303                        "max_supported": 2,
21304                    }),
21305                ),
21306            ]))
21307            .expect("cold replay");
21308        assert_eq!(replayed.len(), 1);
21309        assert_eq!(replayed[0]["type"], "complete_workflow");
21310        assert_eq!(calls.load(Ordering::SeqCst), 1);
21311    }
21312
21313    #[test]
21314    fn side_effect_replay_rejects_changed_rust_value_type() {
21315        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
21316        let ctx = workflow_context(vec![history_event(
21317            "SideEffectRecorded",
21318            json!({"sequence": 1, "result": result}),
21319        )]);
21320        let error = ctx
21321            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
21322            .expect_err("changed type must fail replay");
21323        assert!(matches!(
21324            error,
21325            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21326                if reason == "side_effect_type_mismatch"
21327        ));
21328    }
21329
21330    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
21331        vec![
21332            history_event(
21333                "ActivityScheduled",
21334                json!({
21335                    "sequence": 1,
21336                    "activity_type": "flaky",
21337                    "activity_execution_id": "act-1",
21338                    "activity": {
21339                        "id": "act-1",
21340                        "sequence": 1,
21341                        "type": "flaky",
21342                        "queue": "critical-activities",
21343                        "execution_mode": null,
21344                        "retry_policy": {
21345                            "snapshot_version": 1,
21346                            "max_attempts": 3,
21347                            "backoff_seconds": [2, 4],
21348                            "start_to_close_timeout": 30,
21349                            "schedule_to_start_timeout": 5,
21350                            "schedule_to_close_timeout": 90,
21351                            "heartbeat_timeout": 10,
21352                            "non_retryable_error_types": ["PermanentError"]
21353                        }
21354                    }
21355                }),
21356            ),
21357            history_event(
21358                "ActivityStarted",
21359                json!({
21360                    "sequence": 1,
21361                    "activity_type": "flaky",
21362                    "activity_execution_id": "act-1",
21363                    "activity_attempt_id": "attempt-1",
21364                    "attempt_number": 1
21365                }),
21366            ),
21367            history_event(
21368                "ActivityRetryScheduled",
21369                json!({
21370                    "sequence": 1,
21371                    "activity_type": "flaky",
21372                    "activity_execution_id": "act-1",
21373                    "activity_attempt_id": "attempt-1",
21374                    "attempt_number": 1,
21375                    "retry_after_attempt": 1,
21376                    "retry_backoff_seconds": 2,
21377                    "failure_category": "activity",
21378                    "exception_type": "TransientError"
21379                }),
21380            ),
21381            history_event(
21382                "ActivityStarted",
21383                json!({
21384                    "sequence": 1,
21385                    "activity_type": "flaky",
21386                    "activity_execution_id": "act-1",
21387                    "activity_attempt_id": "attempt-2",
21388                    "attempt_number": 2
21389                }),
21390            ),
21391            history_event(
21392                "ActivityCompleted",
21393                json!({
21394                    "sequence": 1,
21395                    "activity_type": "flaky",
21396                    "activity_execution_id": "act-1",
21397                    "activity_attempt_id": "attempt-2",
21398                    "attempt_number": 2,
21399                    "payload_codec": DEFAULT_CODEC,
21400                    "result": fixture_envelope(json!({"status":"recovered"}))
21401                }),
21402            ),
21403        ]
21404    }
21405
21406    fn retry_activity_options() -> ActivityOptions {
21407        ActivityOptions::new()
21408            .task_queue("critical-activities")
21409            .retry_policy(
21410                ActivityRetryPolicy::new(3)
21411                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
21412                    .non_retryable_error_type("PermanentError"),
21413            )
21414            .start_to_close_timeout(Duration::from_secs(30))
21415            .schedule_to_start_timeout(Duration::from_secs(5))
21416            .schedule_to_close_timeout(Duration::from_secs(90))
21417            .heartbeat_timeout(Duration::from_secs(10))
21418    }
21419
21420    #[test]
21421    fn fixed_avro_value_round_trips_json_values() {
21422        let value = json!({"greeting": "hello", "count": 3, "ok": true});
21423        let envelope = PayloadEnvelope::avro(&value).expect("encode");
21424        assert_eq!(envelope.codec, DEFAULT_CODEC);
21425        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
21426    }
21427
21428    #[tokio::test]
21429    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
21430        let client = Client::new("http://127.0.0.1:8080").expect("client");
21431        let mut worker = Worker::new(client, "rust-workers");
21432        worker.register_typed_workflow(
21433            "typed.contract.workflow",
21434            |_ctx, input: TypedContract| async move { Ok(input) },
21435        );
21436        worker.register_typed_activity(
21437            "typed.contract.activity",
21438            |_ctx, input: TypedContract| async move { Ok(input) },
21439        );
21440
21441        let expected = typed_contract();
21442        let arguments = AvroValue::Array(vec![
21443            AvroValue::from_serialize(&expected).expect("typed request")
21444        ]);
21445        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
21446        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
21447        workflow.arguments = Some(envelope.clone());
21448        let commands = worker
21449            .execute_workflow_task(workflow)
21450            .expect("typed workflow task");
21451        let workflow_result: TypedContract =
21452            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21453                .expect("workflow result envelope")
21454                .deserialize()
21455                .expect("workflow result type");
21456        assert_eq!(workflow_result, expected);
21457
21458        let activity = ActivityTask {
21459            task_id: "typed-contract-activity".to_string(),
21460            workflow_id: None,
21461            run_id: None,
21462            activity_execution_id: None,
21463            observability_context: None,
21464            dispatch_observability_context: None,
21465            observability_links: None,
21466            activity_attempt_id: Some("typed-contract-attempt".to_string()),
21467            attempt_id: None,
21468            activity_type: "typed.contract.activity".to_string(),
21469            payload_codec: DEFAULT_CODEC.to_string(),
21470            arguments: Some(envelope),
21471            attempt_number: 1,
21472            lease_owner: Some("rust-worker".to_string()),
21473        };
21474        let activity_result: TypedContract = worker
21475            .execute_activity_task(activity)
21476            .await
21477            .expect("typed activity task")
21478            .deserialize()
21479            .expect("activity result type");
21480        assert_eq!(activity_result, expected);
21481    }
21482
21483    #[test]
21484    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
21485        let calls = Arc::new(AtomicUsize::new(0));
21486        let observed = Arc::clone(&calls);
21487        let client = Client::new("http://127.0.0.1:8080").expect("client");
21488        let mut worker = Worker::new(client.clone(), "rust-workers");
21489        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
21490            observed.fetch_add(1, Ordering::SeqCst);
21491            async move { Ok(input) }
21492        });
21493        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
21494        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
21495        let original = task.clone();
21496        let error = worker
21497            .execute_workflow_task(task)
21498            .expect_err("incompatible entry must refuse the task, not fail the run");
21499        assert_eq!(calls.load(Ordering::SeqCst), 0);
21500        assert!(error
21501            .to_string()
21502            .contains("workflow_entry_arguments_mismatch:"));
21503        assert!(!error.to_string().contains("private-original-value"));
21504
21505        let mut compatible = Worker::new(client, "rust-workers");
21506        compatible
21507            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
21508        let commands = compatible
21509            .execute_workflow_task(original)
21510            .expect("same recorded input");
21511        assert_eq!(commands[0]["type"], "complete_workflow");
21512        assert_eq!(
21513            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
21514            json!("private-original-value")
21515        );
21516    }
21517
21518    #[test]
21519    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
21520        let factories = Arc::new(AtomicUsize::new(0));
21521        let observed = Arc::clone(&factories);
21522        let client = Client::new("http://127.0.0.1:8080").expect("client");
21523        let mut worker = Worker::new(client, "rust-workers");
21524        worker.register_typed_replayed_workflow(
21525            "entry.replayed",
21526            move || {
21527                observed.fetch_add(1, Ordering::SeqCst);
21528                ()
21529            },
21530            |_ctx, _input: i64, _state| async move {
21531                panic!("body must not start");
21532                #[allow(unreachable_code)]
21533                Ok(0_i64)
21534            },
21535        );
21536        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
21537        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
21538        let error = worker
21539            .execute_workflow_task(task)
21540            .expect_err("entry refusal");
21541        assert_eq!(factories.load(Ordering::SeqCst), 0);
21542        assert!(error
21543            .to_string()
21544            .contains("workflow_entry_arguments_mismatch:"));
21545        assert!(!error.to_string().contains("private-replayed-value"));
21546
21547        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
21548        let Err(error) = replay(
21549            workflow_context(Vec::new()),
21550            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
21551        ) else {
21552            panic!("query replay must refuse before creating application state");
21553        };
21554        assert_eq!(factories.load(Ordering::SeqCst), 0);
21555        assert!(!error.to_string().contains("private-replayed-value"));
21556    }
21557
21558    #[test]
21559    fn typed_entry_deserializes_once_before_entering_application_code() {
21560        static DECODES: AtomicUsize = AtomicUsize::new(0);
21561        struct Counted(i64);
21562        impl<'de> Deserialize<'de> for Counted {
21563            fn deserialize<D: Deserializer<'de>>(
21564                deserializer: D,
21565            ) -> std::result::Result<Self, D::Error> {
21566                DECODES.fetch_add(1, Ordering::SeqCst);
21567                i64::deserialize(deserializer).map(Self)
21568            }
21569        }
21570        DECODES.store(0, Ordering::SeqCst);
21571        let client = Client::new("http://127.0.0.1:8080").expect("client");
21572        let mut worker = Worker::new(client, "rust-workers");
21573        worker.register_typed_workflow(
21574            "entry.once",
21575            |_ctx, input: Counted| async move { Ok(input.0) },
21576        );
21577        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
21578        task.arguments = Some(fixture_envelope(json!([7])));
21579        let commands = worker.execute_workflow_task(task).expect("typed result");
21580        assert_eq!(commands[0]["type"], "complete_workflow");
21581        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
21582    }
21583
21584    #[test]
21585    fn typed_entry_body_input_error_remains_a_business_failure() {
21586        let client = Client::new("http://127.0.0.1:8080").expect("client");
21587        let mut worker = Worker::new(client, "rust-workers");
21588        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
21589            Err::<i64, _>(handler_type_error::<i64>(
21590                HandlerKind::Workflow,
21591                "entry.body",
21592                HandlerValueKind::Input,
21593                "deliberate body error",
21594            ))
21595        });
21596        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
21597        task.arguments = Some(fixture_envelope(json!([7])));
21598        let commands = worker
21599            .execute_workflow_task(task)
21600            .expect("business failure command");
21601        assert_eq!(commands[0]["type"], "fail_workflow");
21602        assert!(commands[0]["message"]
21603            .as_str()
21604            .unwrap()
21605            .contains("deliberate body error"));
21606    }
21607
21608    #[test]
21609    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
21610        let client = Client::new("http://127.0.0.1:8080").expect("client");
21611        let mut worker = Worker::new(client, "rust-workers");
21612        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
21613            Err::<i64, _>(handler_type_error::<i64>(
21614                HandlerKind::Workflow,
21615                "entry.body.refusal",
21616                HandlerValueKind::Input,
21617                "workflow_entry_arguments_mismatch: deliberate body error",
21618            ))
21619        });
21620        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
21621        task.arguments = Some(fixture_envelope(json!([7])));
21622        let commands = worker
21623            .execute_workflow_task(task)
21624            .expect("business failure");
21625        assert_eq!(commands[0]["type"], "fail_workflow");
21626    }
21627
21628    #[tokio::test]
21629    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21630        let client = Client::new("http://127.0.0.1:8080").expect("client");
21631        let mut worker = Worker::new(client, "rust-workers");
21632        worker.register_typed_workflow(
21633            "typed.shape.workflow",
21634            |_ctx, input: TypedContract| async move { Ok(input) },
21635        );
21636        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21637            Ok(f64::NAN)
21638        });
21639
21640        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21641        workflow.arguments = Some(
21642            encode_typed_envelope(
21643                &AvroValue::Array(vec![
21644                    AvroValue::String("first".to_string()),
21645                    AvroValue::String("second".to_string()),
21646                ]),
21647                DEFAULT_CODEC,
21648            )
21649            .expect("malformed typed arguments"),
21650        );
21651        let error = worker
21652            .execute_workflow_task(workflow)
21653            .expect_err("entry shape mismatch refuses the task");
21654        let message = error.to_string();
21655        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21656        assert!(message.contains("typed.shape.workflow"));
21657        assert!(message.contains(type_name::<TypedContract>()));
21658
21659        let activity = ActivityTask {
21660            task_id: "typed-unsupported-activity".to_string(),
21661            workflow_id: None,
21662            run_id: None,
21663            activity_execution_id: None,
21664            observability_context: None,
21665            dispatch_observability_context: None,
21666            observability_links: None,
21667            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21668            attempt_id: None,
21669            activity_type: "typed.unsupported.activity".to_string(),
21670            payload_codec: DEFAULT_CODEC.to_string(),
21671            arguments: Some(
21672                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21673                    .expect("unit arguments"),
21674            ),
21675            attempt_number: 1,
21676            lease_owner: Some("rust-worker".to_string()),
21677        };
21678        let Error::HandlerType {
21679            handler_kind,
21680            handler_name,
21681            value_kind,
21682            rust_type,
21683            message,
21684        } = worker
21685            .execute_activity_task(activity)
21686            .await
21687            .expect_err("non-finite handler output must fail")
21688        else {
21689            panic!("expected contextual handler type failure");
21690        };
21691        assert_eq!(handler_kind, HandlerKind::Activity);
21692        assert_eq!(handler_name, "typed.unsupported.activity");
21693        assert_eq!(value_kind, HandlerValueKind::Result);
21694        assert_eq!(rust_type, type_name::<f64>());
21695        assert!(message.contains("non_finite_float"));
21696    }
21697
21698    #[tokio::test]
21699    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21700        #[derive(Clone, Default)]
21701        struct State {
21702            observed: Option<TypedContract>,
21703        }
21704
21705        let client = Client::new("http://127.0.0.1:8080").expect("client");
21706        let mut worker = Worker::new(client, "rust-workers");
21707        worker.register_typed_replayed_workflow(
21708            "typed.contract.replayed",
21709            State::default,
21710            |ctx, input: TypedContract, state| async move {
21711                let result: TypedContract =
21712                    ctx.activity_typed("typed.contract.activity", input).await?;
21713                state.update(|current| current.observed = Some(result.clone()))?;
21714                Ok(result)
21715            },
21716        );
21717        worker.register_replayed_query::<State, _, _>(
21718            "typed.contract.replayed",
21719            "observed",
21720            |_ctx, state, _args| async move {
21721                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21722            },
21723        );
21724
21725        let expected = typed_contract();
21726        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21727        let workflow_arguments =
21728            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21729                .expect("workflow arguments");
21730        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21731        let task = QueryTask {
21732            query_task_id: "typed-replay-query".to_string(),
21733            observability_context: None,
21734            dispatch_observability_context: None,
21735            observability_links: None,
21736            query_task_attempt: 1,
21737            lease_owner: Some("rust-worker".to_string()),
21738            workflow_id: Some("typed-replay".to_string()),
21739            run_id: Some("typed-replay-run".to_string()),
21740            workflow_type: "typed.contract.replayed".to_string(),
21741            query_name: "observed".to_string(),
21742            payload_codec: DEFAULT_CODEC.to_string(),
21743            workflow_arguments: Some(workflow_arguments),
21744            query_arguments: Some(
21745                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21746                    .expect("query arguments"),
21747            ),
21748            history_events: vec![
21749                history_event(
21750                    "ActivityScheduled",
21751                    json!({
21752                        "sequence": 1,
21753                        "activity_type": "typed.contract.activity"
21754                    }),
21755                ),
21756                history_event(
21757                    "ActivityCompleted",
21758                    json!({
21759                        "sequence": 1,
21760                        "activity_type": "typed.contract.activity",
21761                        "payload_codec": DEFAULT_CODEC,
21762                        "result": result
21763                    }),
21764                ),
21765            ],
21766            history_export: None,
21767            run_status: Some("completed".to_string()),
21768        };
21769
21770        assert_eq!(
21771            worker
21772                .execute_query_task(task)
21773                .await
21774                .expect("typed replay query")
21775                .deserialize::<i64>()
21776                .expect("query result"),
21777            expected.signed
21778        );
21779    }
21780
21781    #[tokio::test]
21782    async fn update_context_preserves_workflow_input_and_committed_signals() {
21783        let client = Client::new("http://127.0.0.1:8080").expect("client");
21784        let mut worker = Worker::new(client, "rust-workers");
21785        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21786        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21787        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21788        let expected_input = workflow_input.clone();
21789        let expected_signals = signal_arguments.clone();
21790        let handler = move |context: QueryContext, arguments: AvroValue| {
21791            let expected_input = expected_input.clone();
21792            let expected_signals = expected_signals.clone();
21793            async move {
21794                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21795                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21796                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21797                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21798                assert_eq!(
21799                    context.signals_avro_value("changed"),
21800                    vec![expected_signals.clone()]
21801                );
21802                assert_eq!(
21803                    context.signals("changed"),
21804                    vec![expected_signals
21805                        .into_iter()
21806                        .map(AvroValue::into_json)
21807                        .collect::<Result<Vec<_>>>()?]
21808                );
21809                assert_eq!(
21810                    context.signal_events()[0].id.as_deref(),
21811                    Some("signal-original")
21812                );
21813                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21814                Ok(arguments)
21815            }
21816        };
21817        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21818        worker.register_update_avro_value("snapshot", "inspect", handler);
21819        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21820        let update_envelope =
21821            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21822        let mut task = workflow_task(
21823            "snapshot",
21824            vec![
21825                history_event(
21826                    "SignalReceived",
21827                    json!({
21828                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21829                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21830                    }),
21831                ),
21832                history_event(
21833                    "UpdateAccepted",
21834                    json!({
21835                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21836                    }),
21837                ),
21838            ],
21839            DEFAULT_CODEC,
21840        );
21841        task.arguments =
21842            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21843        task.workflow_update_id = Some("update-original".into());
21844        task.update_name = Some("inspect".into());
21845        let query = QueryTask {
21846            query_task_id: "query-snapshot".into(),
21847            observability_context: None,
21848            dispatch_observability_context: None,
21849            observability_links: None,
21850            query_task_attempt: 1,
21851            lease_owner: None,
21852            workflow_id: task.workflow_id.clone(),
21853            run_id: task.run_id.clone(),
21854            workflow_type: task.workflow_type.clone(),
21855            query_name: "inspect".into(),
21856            payload_codec: DEFAULT_CODEC.into(),
21857            workflow_arguments: task.arguments.clone(),
21858            query_arguments: Some(update_envelope),
21859            history_events: task.history_events.clone(),
21860            history_export: None,
21861            run_status: Some("running".into()),
21862        };
21863        assert_eq!(
21864            worker
21865                .execute_query_task(query)
21866                .await
21867                .expect("query snapshot"),
21868            update_arguments
21869        );
21870        for _ in 0..2 {
21871            let commands = worker
21872                .execute_workflow_task(task.clone())
21873                .expect("cold update snapshot");
21874            assert_eq!(commands[0]["type"], "complete_update");
21875            assert_eq!(commands[0]["update_id"], "update-original");
21876            assert_eq!(
21877                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21878                    .expect("update result"),
21879                update_arguments
21880            );
21881        }
21882    }
21883
21884    #[test]
21885    fn committed_signal_snapshot_counts_identities_once() {
21886        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21887        let received = history_event(
21888            "SignalReceived",
21889            json!({
21890                "signal_id": "signal-first", "workflow_command_id": "command-first",
21891                "signal_name": "changed", "arguments": arguments.clone(),
21892            }),
21893        );
21894        let applied = history_event(
21895            "SignalApplied",
21896            json!({
21897                "signal_id": "signal-first", "workflow_command_id": "command-first",
21898                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21899            }),
21900        );
21901        let distinct = history_event(
21902            "SignalReceived",
21903            json!({
21904                "signal_id": "signal-second", "workflow_command_id": "command-second",
21905                "signal_name": "changed", "arguments": arguments,
21906            }),
21907        );
21908        let history = vec![received.clone(), applied.clone(), distinct];
21909        let signals =
21910            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21911        assert_eq!(signals.len(), 2);
21912        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21913        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21914        assert_eq!(signals[0].workflow_sequence, Some(1));
21915        assert_eq!(signals[0].arguments, signals[1].arguments);
21916        let mut command_only = received.clone();
21917        command_only
21918            .payload
21919            .as_object_mut()
21920            .expect("payload")
21921            .remove("signal_id");
21922        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21923            .expect("command identity");
21924        assert_eq!(signals.len(), 1);
21925        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21926        let mut conflicting = applied;
21927        conflicting.payload["value"] =
21928            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21929        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21930    }
21931
21932    #[test]
21933    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21934        for arguments in [
21935            vec![],
21936            vec![AvroValue::Array(vec![
21937                AvroValue::Long(1),
21938                AvroValue::Long(2),
21939            ])],
21940            vec![AvroValue::Bytes(vec![0, 255])],
21941            vec![AvroValue::Null],
21942            vec![AvroValue::Boolean(false)],
21943            vec![
21944                AvroValue::Long(1),
21945                AvroValue::Array(vec![AvroValue::Long(2)]),
21946            ],
21947        ] {
21948            let applied = match arguments.as_slice() {
21949                [] => AvroValue::Boolean(true),
21950                [value] => value.clone(),
21951                values => AvroValue::Array(values.to_vec()),
21952            };
21953            for applied in [applied, AvroValue::Array(arguments.clone())] {
21954                let events = vec![
21955                    history_event(
21956                        "SignalReceived",
21957                        json!({
21958                            "signal_id": "original", "signal_name": "changed",
21959                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
21960                        }),
21961                    ),
21962                    history_event(
21963                        "SignalApplied",
21964                        json!({
21965                            "signal_id": "original", "signal_name": "changed",
21966                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
21967                        }),
21968                    ),
21969                ];
21970                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
21971                    .expect("canonical signal snapshot");
21972                assert_eq!(signals.len(), 1);
21973                assert_eq!(signals[0].avro_arguments, arguments);
21974            }
21975        }
21976    }
21977
21978    #[tokio::test]
21979    async fn update_context_rejects_malformed_snapshot_before_handler() {
21980        let client = Client::new("http://127.0.0.1:8080").expect("client");
21981        let mut worker = Worker::new(client, "rust-workers");
21982        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21983        let calls = Arc::new(AtomicUsize::new(0));
21984        let observed = Arc::clone(&calls);
21985        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
21986            observed.fetch_add(1, Ordering::SeqCst);
21987            async { Ok(Value::Null) }
21988        });
21989        let mut task = workflow_task(
21990            "snapshot",
21991            vec![history_event(
21992                "UpdateAccepted",
21993                json!({
21994                    "update_id": "update-original", "update_name": "inspect",
21995                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
21996                }),
21997            )],
21998            DEFAULT_CODEC,
21999        );
22000        task.workflow_update_id = Some("update-original".into());
22001        task.update_name = Some("inspect".into());
22002        let mut bad_input = task.clone();
22003        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
22004        assert!(worker.execute_workflow_task(bad_input).is_err());
22005        task.history_events.insert(0, history_event("SignalReceived", json!({
22006            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
22007        })));
22008        assert!(worker.execute_workflow_task(task).is_err());
22009        assert_eq!(calls.load(Ordering::SeqCst), 0);
22010    }
22011
22012    #[tokio::test]
22013    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
22014        let client = Client::new("http://127.0.0.1:8080").expect("client");
22015        let mut worker = Worker::new(client, "rust-workers");
22016        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
22017        worker
22018            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
22019        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
22020            Ok(input)
22021        });
22022        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
22023            Ok(input)
22024        });
22025        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
22026            Ok(AvroValue::Array(
22027                ctx.wait_signal_avro_value("changed").await?,
22028            ))
22029        });
22030
22031        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
22032        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
22033
22034        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
22035        workflow.arguments = Some(envelope.clone());
22036        let commands = worker
22037            .execute_workflow_task(workflow)
22038            .expect("typed workflow task");
22039        assert_eq!(commands[0]["type"], "complete_workflow");
22040        assert_eq!(
22041            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22042                .expect("typed workflow result"),
22043            arguments
22044        );
22045
22046        let activity = ActivityTask {
22047            task_id: "activity-typed".to_string(),
22048            workflow_id: None,
22049            run_id: None,
22050            activity_execution_id: None,
22051            observability_context: None,
22052            dispatch_observability_context: None,
22053            observability_links: None,
22054            activity_attempt_id: Some("attempt-typed".to_string()),
22055            attempt_id: None,
22056            activity_type: "typed.activity".to_string(),
22057            payload_codec: DEFAULT_CODEC.to_string(),
22058            arguments: Some(envelope.clone()),
22059            attempt_number: 1,
22060            lease_owner: Some("rust-worker".to_string()),
22061        };
22062        assert_eq!(
22063            worker
22064                .execute_activity_task(activity)
22065                .await
22066                .expect("typed activity result"),
22067            arguments
22068        );
22069
22070        let query = QueryTask {
22071            query_task_id: "query-typed".to_string(),
22072            observability_context: None,
22073            dispatch_observability_context: None,
22074            observability_links: None,
22075            query_task_attempt: 1,
22076            lease_owner: Some("rust-worker".to_string()),
22077            workflow_id: Some("typed-1".to_string()),
22078            run_id: Some("run-typed".to_string()),
22079            workflow_type: "typed.echo".to_string(),
22080            query_name: "inspect".to_string(),
22081            payload_codec: DEFAULT_CODEC.to_string(),
22082            workflow_arguments: Some(
22083                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22084                    .expect("workflow input"),
22085            ),
22086            query_arguments: Some(envelope.clone()),
22087            history_events: Vec::new(),
22088            history_export: None,
22089            run_status: Some("running".to_string()),
22090        };
22091        assert_eq!(
22092            worker
22093                .execute_query_task(query)
22094                .await
22095                .expect("typed query result"),
22096            arguments
22097        );
22098
22099        let mut update = workflow_task(
22100            "typed.echo",
22101            vec![history_event(
22102                "UpdateAccepted",
22103                json!({
22104                    "update_id": "update-typed",
22105                    "update_name": "replace",
22106                    "arguments": envelope.clone(),
22107                }),
22108            )],
22109            DEFAULT_CODEC,
22110        );
22111        update.workflow_update_id = Some("update-typed".to_string());
22112        update.update_name = Some("replace".to_string());
22113        let commands = worker
22114            .execute_workflow_task(update)
22115            .expect("typed update task");
22116        assert_eq!(commands[0]["type"], "complete_update");
22117        assert_eq!(
22118            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22119                .expect("typed update result"),
22120            arguments
22121        );
22122
22123        let mut signal = workflow_task(
22124            "typed.signal",
22125            vec![history_event(
22126                "SignalReceived",
22127                json!({
22128                    "signal_id": "signal-typed",
22129                    "signal_name": "changed",
22130                    "arguments": envelope.clone(),
22131                }),
22132            )],
22133            DEFAULT_CODEC,
22134        );
22135        signal.workflow_signal_id = Some("signal-typed".to_string());
22136        signal.signal_name = Some("changed".to_string());
22137        signal.signal_arguments = Some(envelope);
22138        let commands = worker
22139            .execute_workflow_task(signal)
22140            .expect("typed signal resume");
22141        assert_eq!(
22142            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22143                .expect("typed signal result"),
22144            arguments
22145        );
22146    }
22147
22148    #[tokio::test]
22149    async fn typed_helpers_never_parse_json_inspection_projection() {
22150        let collision_values = projection_collision_probe();
22151        let expected = AvroValue::Array(collision_values.clone());
22152        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
22153
22154        let activity_context = workflow_context_with_codec(
22155            vec![history_event(
22156                "ActivityCompleted",
22157                json!({
22158                    "sequence": 1,
22159                    "activity_type": "collision.activity",
22160                    "payload_codec": DEFAULT_CODEC,
22161                    "result": envelope.clone(),
22162                }),
22163            )],
22164            DEFAULT_CODEC,
22165        );
22166        assert_eq!(
22167            activity_context
22168                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
22169                .await
22170                .expect("typed activity collision result"),
22171            expected
22172        );
22173
22174        let signal_context = workflow_context_with_codec(
22175            vec![
22176                history_event(
22177                    "SignalWaitOpened",
22178                    json!({"sequence": 1, "signal_name": "collision"}),
22179                ),
22180                history_event(
22181                    "SignalApplied",
22182                    json!({
22183                        "sequence": 1,
22184                        "signal_name": "collision",
22185                        "payload_codec": DEFAULT_CODEC,
22186                        "value": envelope.clone(),
22187                    }),
22188                ),
22189            ],
22190            DEFAULT_CODEC,
22191        );
22192        assert_eq!(
22193            signal_context
22194                .wait_signal_avro_value("collision")
22195                .await
22196                .expect("typed signal collision arguments"),
22197            collision_values
22198        );
22199
22200        let child_context = workflow_context_with_codec(
22201            vec![
22202                history_event(
22203                    "ChildWorkflowScheduled",
22204                    json!({
22205                        "sequence": 1,
22206                        "child_workflow_instance_id": "collision-child",
22207                        "child_workflow_run_id": "collision-run",
22208                        "child_workflow_type": "collision.child",
22209                    }),
22210                ),
22211                history_event(
22212                    "ChildRunCompleted",
22213                    json!({
22214                        "sequence": 1,
22215                        "child_workflow_instance_id": "collision-child",
22216                        "child_workflow_run_id": "collision-run",
22217                        "child_workflow_type": "collision.child",
22218                        "payload_codec": DEFAULT_CODEC,
22219                        "result": envelope,
22220                    }),
22221                ),
22222            ],
22223            DEFAULT_CODEC,
22224        );
22225        let child = child_context
22226            .start_child_workflow_avro_value(
22227                "collision.child",
22228                ChildWorkflowOptions::new("collision-workers"),
22229                AvroValue::Array(Vec::new()),
22230            )
22231            .await
22232            .expect("typed child collision result");
22233        assert_eq!(child.result, expected);
22234    }
22235
22236    #[tokio::test]
22237    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
22238        let client = Client::new("http://127.0.0.1:8080").expect("client");
22239        let mut worker = Worker::new(client, "rust-workers");
22240        worker.register_replayed_workflow_avro_value(
22241            "typed.replayed",
22242            || (),
22243            |_ctx, input, _state| async move { Ok(input) },
22244        );
22245        worker.register_replayed_query_avro_value::<(), _, _>(
22246            "typed.replayed",
22247            "inspect",
22248            |ctx, _state, args| async move {
22249                let mut signals = ctx.signals_avro_value("collision");
22250                let signal = signals
22251                    .pop()
22252                    .map(AvroValue::Array)
22253                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
22254                Ok(AvroValue::Array(vec![
22255                    ctx.workflow_input_avro_value().clone(),
22256                    signal,
22257                    args,
22258                ]))
22259            },
22260        );
22261        let arguments = AvroValue::Array(projection_collision_probe());
22262        let signal_arguments =
22263            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
22264        let task = QueryTask {
22265            query_task_id: "query-typed-replay".to_string(),
22266            observability_context: None,
22267            dispatch_observability_context: None,
22268            observability_links: None,
22269            query_task_attempt: 1,
22270            lease_owner: Some("rust-worker".to_string()),
22271            workflow_id: Some("typed-replay".to_string()),
22272            run_id: Some("run-typed-replay".to_string()),
22273            workflow_type: "typed.replayed".to_string(),
22274            query_name: "inspect".to_string(),
22275            payload_codec: DEFAULT_CODEC.to_string(),
22276            workflow_arguments: Some(
22277                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
22278            ),
22279            query_arguments: Some(
22280                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
22281            ),
22282            history_events: vec![history_event(
22283                "SignalReceived",
22284                json!({
22285                    "signal_id": "collision-signal",
22286                    "signal_name": "collision",
22287                    "workflow_sequence": 1,
22288                    "payload_codec": DEFAULT_CODEC,
22289                    "arguments": signal_arguments,
22290                }),
22291            )],
22292            history_export: None,
22293            run_status: Some("completed".to_string()),
22294        };
22295
22296        assert_eq!(
22297            worker
22298                .execute_query_task(task)
22299                .await
22300                .expect("typed replay query"),
22301            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
22302        );
22303    }
22304
22305    #[test]
22306    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
22307        let value = BTreeMap::from([(1_i32, "integer key")]);
22308        let error = PayloadEnvelope::avro(&value)
22309            .expect_err("integer map keys must fail")
22310            .to_string();
22311
22312        assert!(error.contains("invalid_map_key"));
22313    }
22314
22315    #[test]
22316    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
22317        let envelope = PayloadEnvelope {
22318            codec: "json".to_string(),
22319            blob: r#"{"greeting":"hello"}"#.to_string(),
22320        };
22321
22322        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
22323        let diagnostic = error.to_string();
22324        assert!(diagnostic.contains("unsupported_payload_codec"));
22325        assert!(diagnostic.contains("codec=\"avro\""));
22326        assert!(diagnostic.contains("HTTP document transport"));
22327    }
22328
22329    #[test]
22330    fn untagged_json_payload_value_fails_closed() {
22331        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
22332            .expect_err("untagged JSON payload values must fail");
22333        let diagnostic = error.to_string();
22334        assert!(diagnostic.contains("unsupported_payload_codec"));
22335        assert!(diagnostic.contains("untagged durable payload"));
22336        assert!(diagnostic.contains("HTTP document transport"));
22337    }
22338
22339    #[test]
22340    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
22341        let envelope = PayloadEnvelope {
22342            codec: DEFAULT_CODEC.to_string(),
22343            blob: BASE64.encode([0x01]),
22344        };
22345
22346        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
22347        assert!(error.to_string().contains("invalid_payload_framing"));
22348    }
22349
22350    #[tokio::test]
22351    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
22352        let server = MockWorkerServer::start();
22353        let client = Client::builder(server.base_url())
22354            .timeout(Duration::from_secs(2))
22355            .build()
22356            .expect("client");
22357        let invalid_commands = [
22358            json!({
22359                "type": "complete_workflow",
22360                "result": {"codec": "json", "blob": null}
22361            }),
22362            json!({
22363                "type": "schedule_activity",
22364                "arguments": {"codec": "yaml", "blob": "ignored"}
22365            }),
22366            json!({
22367                "type": "start_child_workflow",
22368                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
22369            }),
22370            json!({"type": "continue_as_new", "arguments": []}),
22371            json!({"type": "complete_update"}),
22372            json!({"type": "record_side_effect", "result": null}),
22373            json!({
22374                "type": "start_service_operation",
22375                "payload_codec": DEFAULT_CODEC,
22376                "request_payload": "raw-avro-bytes"
22377            }),
22378        ];
22379
22380        for command in invalid_commands {
22381            let error = client
22382                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
22383                .await
22384                .expect_err("invalid durable payload must fail locally");
22385            let diagnostic = error.to_string();
22386            assert!(
22387                diagnostic.contains("unsupported_payload_codec")
22388                    || diagnostic.contains("invalid_payload_envelope")
22389                    || diagnostic.contains("untagged durable payload"),
22390                "unexpected validation diagnostic: {diagnostic}"
22391            );
22392        }
22393
22394        assert_eq!(
22395            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
22396            0,
22397            "invalid command payloads must not reach HTTP transport"
22398        );
22399    }
22400
22401    #[test]
22402    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
22403        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
22404        let commands = [
22405            json!({"type": "complete_workflow", "result": envelope.clone()}),
22406            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
22407            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
22408            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
22409            json!({"type": "complete_update", "result": envelope.clone()}),
22410            json!({"type": "record_side_effect", "result": envelope.clone()}),
22411            json!({
22412                "type": "start_service_operation",
22413                "payload_codec": DEFAULT_CODEC,
22414                "request_payload": envelope.clone()
22415            }),
22416            json!({
22417                "type": "complete_workflow",
22418                "result": envelope,
22419                "metadata": {
22420                    "codec": "json",
22421                    "payload_codec": "customer-codec",
22422                    "result": {"codec": "yaml", "blob": null}
22423                }
22424            }),
22425        ];
22426
22427        validate_workflow_task_commands(&commands)
22428            .expect("customer metadata must not become a protocol codec declaration");
22429    }
22430
22431    #[test]
22432    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
22433        assert_eq!(
22434            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
22435            AvroValue::Array(Vec::new())
22436        );
22437        assert_eq!(
22438            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
22439            AvroValue::Array(Vec::new())
22440        );
22441
22442        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22443        signal.signal_name = Some("empty-signal".to_string());
22444        signal.signal_arguments = None;
22445        let decoded = decode_resume_signal(&signal)
22446            .expect("valid Avro signal")
22447            .expect("named signal resumes the workflow");
22448        assert!(decoded.arguments.is_empty());
22449    }
22450
22451    #[tokio::test]
22452    async fn malformed_task_level_codecs_become_pre_handler_failures() {
22453        let client = Client::new("http://127.0.0.1:8080").expect("client");
22454        let mut worker = Worker::new(client, "rust-workers");
22455        let handler_calls = Arc::new(AtomicUsize::new(0));
22456
22457        let calls = Arc::clone(&handler_calls);
22458        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22459            calls.fetch_add(1, Ordering::SeqCst);
22460            async move { Ok(Value::Null) }
22461        });
22462        let calls = Arc::clone(&handler_calls);
22463        worker.register_activity("codec.activity", move |_ctx, _args| {
22464            calls.fetch_add(1, Ordering::SeqCst);
22465            async move { Ok(Value::Null) }
22466        });
22467        let calls = Arc::clone(&handler_calls);
22468        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22469            calls.fetch_add(1, Ordering::SeqCst);
22470            async move { Ok(Value::Null) }
22471        });
22472
22473        let mut failures = Vec::new();
22474        for codec_case in [
22475            InvalidTaskPayloadCodec::Missing,
22476            InvalidTaskPayloadCodec::Null,
22477            InvalidTaskPayloadCodec::NonString,
22478        ] {
22479            let mut workflow = json!({
22480                "task_id": format!("workflow-{}", codec_case.label()),
22481                "workflow_type": "codec.workflow"
22482            });
22483            codec_case.apply(&mut workflow);
22484            match serde_json::from_value::<WorkflowTask>(workflow) {
22485                Ok(task) => match worker.execute_workflow_task(task) {
22486                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22487                    outcome => failures.push(format!(
22488                        "workflow {} codec returned {outcome:?}",
22489                        codec_case.label()
22490                    )),
22491                },
22492                Err(error) => failures.push(format!(
22493                    "workflow {} codec failed transport deserialization: {error}",
22494                    codec_case.label()
22495                )),
22496            }
22497
22498            let mut activity = json!({
22499                "task_id": format!("activity-{}", codec_case.label()),
22500                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
22501                "activity_type": "codec.activity",
22502                "attempt_number": 1
22503            });
22504            codec_case.apply(&mut activity);
22505            match serde_json::from_value::<ActivityTask>(activity) {
22506                Ok(task) => match worker.execute_activity_task(task).await {
22507                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22508                    outcome => failures.push(format!(
22509                        "activity {} codec returned {outcome:?}",
22510                        codec_case.label()
22511                    )),
22512                },
22513                Err(error) => failures.push(format!(
22514                    "activity {} codec failed transport deserialization: {error}",
22515                    codec_case.label()
22516                )),
22517            }
22518
22519            let mut query = json!({
22520                "query_task_id": format!("query-{}", codec_case.label()),
22521                "workflow_type": "codec.workflow",
22522                "query_name": "known"
22523            });
22524            codec_case.apply(&mut query);
22525            match serde_json::from_value::<QueryTask>(query) {
22526                Ok(task) => match worker.execute_query_task(task).await {
22527                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
22528                    outcome => failures.push(format!(
22529                        "query {} codec returned {outcome:?}",
22530                        codec_case.label()
22531                    )),
22532                },
22533                Err(error) => failures.push(format!(
22534                    "query {} codec failed transport deserialization: {error}",
22535                    codec_case.label()
22536                )),
22537            }
22538        }
22539
22540        assert!(failures.is_empty(), "{}", failures.join("\n"));
22541        assert_eq!(
22542            handler_calls.load(Ordering::SeqCst),
22543            0,
22544            "invalid task codecs must not invoke a handler"
22545        );
22546    }
22547
22548    #[tokio::test]
22549    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
22550        for codec_case in [
22551            InvalidTaskPayloadCodec::Missing,
22552            InvalidTaskPayloadCodec::Null,
22553            InvalidTaskPayloadCodec::NonString,
22554        ] {
22555            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
22556            let client = Client::builder(server.base_url())
22557                .timeout(Duration::from_secs(2))
22558                .build()
22559                .expect("client");
22560            let mut worker = Worker::new(client, "rust-workers")
22561                .worker_id("codec-worker")
22562                .poll_timeout(Duration::from_millis(10));
22563            let handler_calls = Arc::new(AtomicUsize::new(0));
22564
22565            let calls = Arc::clone(&handler_calls);
22566            worker.register_workflow("codec.workflow", move |_ctx, _args| {
22567                calls.fetch_add(1, Ordering::SeqCst);
22568                async move { Ok(Value::Null) }
22569            });
22570            let calls = Arc::clone(&handler_calls);
22571            worker.register_activity("codec.activity", move |_ctx, _args| {
22572                calls.fetch_add(1, Ordering::SeqCst);
22573                async move { Ok(Value::Null) }
22574            });
22575            let calls = Arc::clone(&handler_calls);
22576            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22577                calls.fetch_add(1, Ordering::SeqCst);
22578                async move { Ok(Value::Null) }
22579            });
22580
22581            assert_eq!(
22582                worker.run_once().await.expect("invalid tasks are settled"),
22583                3,
22584                "all {} codec tasks must be handled",
22585                codec_case.label()
22586            );
22587            assert_eq!(
22588                handler_calls.load(Ordering::SeqCst),
22589                0,
22590                "{} task codecs must fail before every handler",
22591                codec_case.label()
22592            );
22593
22594            for path in [
22595                "/api/worker/workflow-tasks/codec-workflow/fail",
22596                "/api/worker/activity-tasks/codec-activity/fail",
22597                "/api/worker/query-tasks/codec-query/fail",
22598            ] {
22599                let body = server.request_body(path);
22600                assert!(
22601                    body["failure"]["message"]
22602                        .as_str()
22603                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
22604                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
22605                    codec_case.label()
22606                );
22607            }
22608            assert_eq!(
22609                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
22610                    ["reason"],
22611                "query_payload_decode_failed"
22612            );
22613            for path in [
22614                "/api/worker/workflow-tasks/codec-workflow/complete",
22615                "/api/worker/activity-tasks/codec-activity/complete",
22616                "/api/worker/query-tasks/codec-query/complete",
22617            ] {
22618                assert_eq!(
22619                    server.request_count(path),
22620                    0,
22621                    "invalid {} codec task reached {path}",
22622                    codec_case.label()
22623                );
22624            }
22625        }
22626    }
22627
22628    #[tokio::test]
22629    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22630        let client = Client::new("http://127.0.0.1:8080").expect("client");
22631        let mut worker = Worker::new(client, "rust-workers");
22632        let handler_calls = Arc::new(AtomicUsize::new(0));
22633
22634        let calls = Arc::clone(&handler_calls);
22635        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22636            calls.fetch_add(1, Ordering::SeqCst);
22637            async move { Ok(Value::Null) }
22638        });
22639        let calls = Arc::clone(&handler_calls);
22640        worker.register_activity("codec.activity", move |_ctx, _args| {
22641            calls.fetch_add(1, Ordering::SeqCst);
22642            async move { Ok(Value::Null) }
22643        });
22644        let calls = Arc::clone(&handler_calls);
22645        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22646            calls.fetch_add(1, Ordering::SeqCst);
22647            async move { Ok(Value::Null) }
22648        });
22649        let calls = Arc::clone(&handler_calls);
22650        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22651            calls.fetch_add(1, Ordering::SeqCst);
22652            async move { Ok(Value::Null) }
22653        });
22654
22655        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22656        workflow.payload_codec = "json".to_string();
22657        workflow.arguments = None;
22658        let error = worker
22659            .execute_workflow_task(workflow)
22660            .expect_err("task codec must be checked before workflow invocation");
22661        assert!(error.to_string().contains("unsupported_payload_codec"));
22662
22663        let activity = ActivityTask {
22664            task_id: "activity-invalid-codec".to_string(),
22665            workflow_id: None,
22666            run_id: None,
22667            activity_execution_id: None,
22668            observability_context: None,
22669            dispatch_observability_context: None,
22670            observability_links: None,
22671            activity_attempt_id: None,
22672            attempt_id: None,
22673            activity_type: "codec.activity".to_string(),
22674            payload_codec: "unknown".to_string(),
22675            arguments: None,
22676            attempt_number: 1,
22677            lease_owner: None,
22678        };
22679        let error = worker
22680            .execute_activity_task(activity)
22681            .await
22682            .expect_err("task codec must be checked before activity invocation");
22683        assert!(error.to_string().contains("unsupported_payload_codec"));
22684
22685        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22686        update.workflow_update_id = Some("update-invalid-codec".to_string());
22687        update.update_name = Some("known".to_string());
22688        update.history_events.push(history_event(
22689            "UpdateAccepted",
22690            json!({
22691                "update_id": "update-invalid-codec",
22692                "update_name": "known",
22693                "arguments": {"codec": "json", "blob": null}
22694            }),
22695        ));
22696        let error = worker
22697            .execute_workflow_task(update)
22698            .expect_err("nested update codec must be checked before handler lookup");
22699        assert!(error.to_string().contains("unsupported_payload_codec"));
22700
22701        let query: QueryTask = serde_json::from_value(json!({
22702            "query_task_id": "query-invalid-codec",
22703            "workflow_type": "codec.workflow",
22704            "query_name": "known",
22705            "payload_codec": DEFAULT_CODEC,
22706            "workflow_arguments": null,
22707            "query_arguments": null,
22708            "history_export": {
22709                "payloads": {"codec": DEFAULT_CODEC},
22710                "signals": [{
22711                    "name": "empty",
22712                    "payload_codec": "json",
22713                    "arguments": null
22714                }]
22715            }
22716        }))
22717        .expect("query task");
22718        let failure = worker
22719            .execute_query_task(query)
22720            .await
22721            .expect_err("exported signal codec must be checked before query invocation");
22722        assert_eq!(failure.reason, "query_payload_decode_failed");
22723        assert!(failure.message.contains("unsupported_payload_codec"));
22724
22725        let exported_history: QueryTask = serde_json::from_value(json!({
22726            "query_task_id": "query-invalid-history-codec",
22727            "workflow_type": "codec.workflow",
22728            "query_name": "known",
22729            "payload_codec": DEFAULT_CODEC,
22730            "history_export": {
22731                "payloads": {"codec": DEFAULT_CODEC},
22732                "history_events": [{
22733                    "type": "ActivityCompleted",
22734                    "payload": {"payload_codec": "unknown", "result": null}
22735                }]
22736            }
22737        }))
22738        .expect("query task");
22739        let failure = worker
22740            .execute_query_task(exported_history)
22741            .await
22742            .expect_err("exported history codec must be checked before query invocation");
22743        assert_eq!(failure.reason, "query_payload_decode_failed");
22744        assert!(failure.message.contains("unsupported_payload_codec"));
22745        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22746
22747        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22748        unknown_workflow.arguments = None;
22749        unknown_workflow.history_events.push(history_event(
22750            "SignalReceived",
22751            json!({
22752                "signal_name": "empty",
22753                "payload_codec": "json",
22754                "arguments": null
22755            }),
22756        ));
22757        let error = worker
22758            .execute_workflow_task(unknown_workflow)
22759            .expect_err("history codec must precede unknown workflow outcome");
22760        assert!(error.to_string().contains("unsupported_payload_codec"));
22761
22762        let unknown_activity = ActivityTask {
22763            task_id: "activity-unknown".to_string(),
22764            workflow_id: None,
22765            run_id: None,
22766            activity_execution_id: None,
22767            observability_context: None,
22768            dispatch_observability_context: None,
22769            observability_links: None,
22770            activity_attempt_id: None,
22771            attempt_id: None,
22772            activity_type: "missing".to_string(),
22773            payload_codec: "json".to_string(),
22774            arguments: None,
22775            attempt_number: 1,
22776            lease_owner: None,
22777        };
22778        let error = worker
22779            .execute_activity_task(unknown_activity)
22780            .await
22781            .expect_err("codec must precede unknown activity outcome");
22782        assert!(error.to_string().contains("unsupported_payload_codec"));
22783
22784        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22785        unknown_update.payload_codec = "json".to_string();
22786        unknown_update.arguments = None;
22787        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22788        unknown_update.update_name = Some("missing".to_string());
22789        let error = worker
22790            .execute_workflow_task(unknown_update)
22791            .expect_err("codec must precede fail_update shortcut");
22792        assert!(error.to_string().contains("unsupported_payload_codec"));
22793
22794        let unknown_query: QueryTask = serde_json::from_value(json!({
22795            "query_task_id": "query-unknown",
22796            "workflow_type": "missing",
22797            "query_name": "missing",
22798            "payload_codec": "json",
22799            "workflow_arguments": null,
22800            "query_arguments": null
22801        }))
22802        .expect("query task");
22803        let failure = worker
22804            .execute_query_task(unknown_query)
22805            .await
22806            .expect_err("codec must precede unknown query outcome");
22807        assert_eq!(failure.reason, "query_payload_decode_failed");
22808        assert!(failure.message.contains("unsupported_payload_codec"));
22809    }
22810
22811    #[tokio::test]
22812    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22813        let client = Client::new("http://127.0.0.1:8080").expect("client");
22814        let worker = Worker::new(client, "rust-workers");
22815
22816        for event_type in ["SignalReceived", "SignalApplied"] {
22817            for (payload_field, codec) in [
22818                ("value", "json"),
22819                ("input", "unknown"),
22820                ("arguments", "json"),
22821            ] {
22822                let payload = json!({
22823                    "signal_name": "empty",
22824                    payload_field: {"codec": codec, "blob": null}
22825                });
22826                let workflow = workflow_task(
22827                    "missing",
22828                    vec![history_event(event_type, payload.clone())],
22829                    DEFAULT_CODEC,
22830                );
22831                let error = worker
22832                    .execute_workflow_task(workflow)
22833                    .expect_err("signal payload codec must precede unknown workflow outcome");
22834                assert!(
22835                    error.to_string().contains("unsupported_payload_codec"),
22836                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22837                );
22838
22839                let query: QueryTask = serde_json::from_value(json!({
22840                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22841                    "workflow_type": "missing",
22842                    "query_name": "missing",
22843                    "payload_codec": DEFAULT_CODEC,
22844                    "workflow_arguments": null,
22845                    "query_arguments": null,
22846                    "history_events": [{
22847                        "event_type": event_type,
22848                        "payload": payload
22849                    }]
22850                }))
22851                .expect("query task");
22852                let failure = worker
22853                    .execute_query_task(query)
22854                    .await
22855                    .expect_err("signal payload codec must precede unknown query outcome");
22856                assert_eq!(
22857                    failure.reason, "query_payload_decode_failed",
22858                    "{event_type}.{payload_field} returned an unrelated query outcome"
22859                );
22860                assert!(
22861                    failure.message.contains("unsupported_payload_codec"),
22862                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22863                    failure.message
22864                );
22865            }
22866        }
22867    }
22868
22869    #[test]
22870    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22871        let ctx = WorkflowContext {
22872            cancellation_scope_id: "root".into(),
22873            state: Arc::new(Mutex::new(
22874                WorkflowState::new_with_identity(
22875                    Vec::new(),
22876                    Some("wf-parent".to_string()),
22877                    Some("run-parent".to_string()),
22878                    "rust-workers".to_string(),
22879                    DEFAULT_CODEC.to_string(),
22880                    None,
22881                )
22882                .expect("workflow state"),
22883            )),
22884        };
22885
22886        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22887        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22888        assert!(matches!(
22889            call.as_mut().poll(&mut task_context),
22890            Poll::Pending
22891        ));
22892
22893        let commands = ctx.take_commands().expect("commands");
22894        assert_eq!(commands[0]["type"], "schedule_activity");
22895        assert_eq!(commands[0]["activity_type"], "hello.activity");
22896    }
22897
22898    #[test]
22899    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22900        let ctx = workflow_context(Vec::new());
22901        let options = ActivityOptions::new()
22902            .task_queue("payments")
22903            .retry_policy(
22904                ActivityRetryPolicy::new(4)
22905                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22906                    .non_retryable_error_type("ValidationError"),
22907            )
22908            .start_to_close_timeout(Duration::from_secs(120))
22909            .schedule_to_start_timeout(Duration::from_secs(10))
22910            .schedule_to_close_timeout(Duration::from_secs(300))
22911            .heartbeat_timeout(Duration::from_secs(15));
22912        let mut call = Box::pin(ctx.activity_with_options(
22913            "charge-card",
22914            options,
22915            json!([{"order_id": "o-1"}]),
22916        ));
22917        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22918
22919        assert!(matches!(
22920            call.as_mut().poll(&mut task_context),
22921            Poll::Pending
22922        ));
22923        assert!(matches!(
22924            call.as_mut().poll(&mut task_context),
22925            Poll::Pending
22926        ));
22927
22928        let commands = ctx.take_commands().expect("activity command");
22929        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22930        assert_eq!(commands[0]["queue"], "payments");
22931        assert_eq!(
22932            commands[0]["retry_policy"],
22933            json!({
22934                "max_attempts": 4,
22935                "backoff_seconds": [1, 3, 9],
22936                "non_retryable_error_types": ["ValidationError"],
22937            })
22938        );
22939        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22940        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22941        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22942        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22943    }
22944
22945    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22946        vec![
22947            history_event(
22948                "ActivityScheduled",
22949                json!({"sequence":1,"activity_type":"render",
22950                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22951            ),
22952            history_event(
22953                "ActivityCompleted",
22954                json!({"sequence":1,"activity_type":"render",
22955                "payload_codec":DEFAULT_CODEC,
22956                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
22957            ),
22958        ]
22959    }
22960
22961    #[test]
22962    fn worker_session_activity_routes_to_session_queue_once() {
22963        let ctx = workflow_context(Vec::new());
22964        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22965        let mut call = Box::pin(
22966            ctx.activity("render", json!([]))
22967                .in_worker_session(session.clone()),
22968        );
22969        let mut cx = TaskContext::from_waker(noop_waker_ref());
22970        assert!(call.as_mut().poll(&mut cx).is_pending());
22971        assert!(call.as_mut().poll(&mut cx).is_pending());
22972        let commands = ctx.take_commands().unwrap();
22973        assert_eq!(commands.len(), 1);
22974        assert_eq!(commands[0]["queue"], "gpu-workers");
22975        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
22976    }
22977
22978    #[tokio::test]
22979    async fn worker_session_cold_replay_uses_recorded_avro_result() {
22980        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22981        for _replacement in 0..2 {
22982            let ctx = workflow_context(completed_worker_session_history(&session));
22983            let result: i64 = ctx
22984                .activity("render", json!([]))
22985                .in_worker_session(session.clone())
22986                .typed()
22987                .await
22988                .unwrap();
22989            assert_eq!(result, 42);
22990            assert!(ctx.take_commands().unwrap().is_empty());
22991        }
22992    }
22993
22994    #[test]
22995    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
22996        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22997        for changed in [
22998            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
22999            Some(original.clone().ttl_seconds(60)),
23000            Some(original.clone().requirements(["gpu:l4"])),
23001            None,
23002        ] {
23003            let ctx = workflow_context(completed_worker_session_history(&original));
23004            let mut call = ctx.activity_with_options(
23005                "render",
23006                ActivityOptions::new().task_queue("gpu-workers"),
23007                json!([]),
23008            );
23009            if let Some(changed) = changed {
23010                call = call.in_worker_session(changed);
23011            }
23012            let mut call = Box::pin(call);
23013            let mut cx = TaskContext::from_waker(noop_waker_ref());
23014            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23015                call.as_mut().poll(&mut cx)
23016            else {
23017                panic!("changed session must fail replay");
23018            };
23019            assert_eq!(failure.reason, "activity_worker_session_mismatch");
23020            assert!(ctx.take_commands().unwrap().is_empty());
23021        }
23022    }
23023
23024    #[test]
23025    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
23026        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23027        let ctx = workflow_context(Vec::new());
23028        let mut local = Box::pin(
23029            ctx.local_activity("render", json!([]))
23030                .in_worker_session(session.clone()),
23031        );
23032        let mut cx = TaskContext::from_waker(noop_waker_ref());
23033        assert!(matches!(
23034            local.as_mut().poll(&mut cx),
23035            Poll::Ready(Err(Error::WorkerLoop(_)))
23036        ));
23037        assert!(ctx.take_commands().unwrap().is_empty());
23038        let mut remote = Box::pin(
23039            ctx.activity_with_options(
23040                "render",
23041                ActivityOptions::new().task_queue("other"),
23042                json!([]),
23043            )
23044            .in_worker_session(session),
23045        );
23046        assert!(matches!(
23047            remote.as_mut().poll(&mut cx),
23048            Poll::Ready(Err(Error::WorkerLoop(_)))
23049        ));
23050        assert!(ctx.take_commands().unwrap().is_empty());
23051    }
23052
23053    #[test]
23054    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
23055        let ctx = workflow_context(Vec::new());
23056        let options = ActivityOptions::new().retry_policy(
23057            ActivityRetryPolicy::new(3)
23058                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
23059        );
23060        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23061        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23062
23063        assert!(matches!(
23064            call.as_mut().poll(&mut task_context),
23065            Poll::Pending
23066        ));
23067        assert_eq!(
23068            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
23069            json!([1, 2])
23070        );
23071    }
23072
23073    #[test]
23074    fn activity_options_preserve_unused_explicit_backoff_entries() {
23075        for max_attempts in [1, 2, 10] {
23076            let ctx = workflow_context(Vec::new());
23077            let options =
23078                ActivityOptions::new()
23079                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
23080                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
23081                    ));
23082            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23083            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23084            assert!(matches!(
23085                call.as_mut().poll(&mut task_context),
23086                Poll::Pending
23087            ));
23088            let commands = ctx.take_commands().expect("command");
23089            assert_eq!(commands.len(), 1);
23090            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
23091            assert_eq!(
23092                commands[0]["retry_policy"]["backoff_seconds"],
23093                json!([1, 2, 5, 10, 15, 30, 60, 120])
23094            );
23095        }
23096        let default_options = ActivityOptions::new().validate().expect("default options");
23097        let default_policy = current_activity_retry_snapshot(&default_options);
23098        assert_eq!(
23099            default_policy.max_attempts,
23100            RecordedSnapshotValue::Known(Some(1))
23101        );
23102        assert_eq!(
23103            default_policy.backoff_seconds,
23104            RecordedSnapshotValue::Known(Vec::new())
23105        );
23106    }
23107
23108    #[test]
23109    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
23110        let fixture: Value = serde_json::from_str(include_str!(
23111            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
23112        ))
23113        .expect("published PHP fixture");
23114        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
23115            .expect("unchanged published history");
23116        let matching = ActivityOptions::new().task_queue("default").retry_policy(
23117            ActivityRetryPolicy::new(1)
23118                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
23119        );
23120        let mut changed_tail = matching.clone();
23121        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23122            [1, 2, 5, 10, 15, 30, 60, 121]
23123                .map(Duration::from_secs)
23124                .to_vec(),
23125        ));
23126        let mut changed_first = matching.clone();
23127        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23128            [2, 2, 5, 10, 15, 30, 60, 120]
23129                .map(Duration::from_secs)
23130                .to_vec(),
23131        ));
23132        let mut changed_attempts = matching.clone();
23133        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
23134        let mut changed_types = matching.clone();
23135        changed_types
23136            .retry_policy
23137            .as_mut()
23138            .unwrap()
23139            .non_retryable_error_types = vec!["ChangedError".into()];
23140        let mut changed_start = matching.clone();
23141        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
23142        let mut changed_schedule_start = matching.clone();
23143        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
23144        let mut changed_schedule_close = matching.clone();
23145        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
23146        let mut changed_heartbeat = matching;
23147        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
23148        let unchanged_defaults = ActivityOptions::new().task_queue("default");
23149        for options in [
23150            changed_tail,
23151            changed_first,
23152            changed_attempts,
23153            changed_types,
23154            changed_start,
23155            changed_schedule_start,
23156            changed_schedule_close,
23157            changed_heartbeat,
23158            unchanged_defaults,
23159        ] {
23160            let ctx = workflow_context(history.clone());
23161            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
23162            assert!(!ctx.patched("frozen-zero").unwrap());
23163            ctx.deprecate_patch("frozen-zero").unwrap();
23164            let mut call =
23165                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
23166            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23167            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23168                call.as_mut().poll(&mut task_context)
23169            else {
23170                panic!("changed explicit policy must fail replay")
23171            };
23172            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
23173            assert_eq!(failure.sequence, Some(2));
23174            assert!(ctx.take_commands().unwrap().is_empty());
23175        }
23176    }
23177
23178    #[test]
23179    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
23180        let cases = [
23181            (
23182                ActivityOptions::new().task_queue("  "),
23183                ActivityOptionsErrorKind::EmptyTaskQueue,
23184            ),
23185            (
23186                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
23187                ActivityOptionsErrorKind::EmptyRetryPolicy,
23188            ),
23189            (
23190                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
23191                ActivityOptionsErrorKind::InvalidMaxAttempts,
23192            ),
23193            (
23194                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
23195                    max_attempts: None,
23196                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
23197                    non_retryable_error_types: Vec::new(),
23198                }),
23199                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
23200            ),
23201            (
23202                ActivityOptions::new().retry_policy(
23203                    ActivityRetryPolicy::new(2).exponential_backoff(
23204                        Duration::from_secs(1),
23205                        0,
23206                        None,
23207                    ),
23208                ),
23209                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
23210            ),
23211            (
23212                ActivityOptions::new()
23213                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
23214                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
23215            ),
23216            (
23217                ActivityOptions::new().retry_policy(
23218                    ActivityRetryPolicy::new(10_002).exponential_backoff(
23219                        Duration::from_secs(1),
23220                        1,
23221                        None,
23222                    ),
23223                ),
23224                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
23225            ),
23226            (
23227                ActivityOptions::new().retry_policy(
23228                    ActivityRetryPolicy::new(2)
23229                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
23230                ),
23231                ActivityOptionsErrorKind::BackoffOverflow,
23232            ),
23233        ];
23234
23235        for (options, expected_kind) in cases {
23236            let ctx = workflow_context(Vec::new());
23237            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23238            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23239            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
23240                call.as_mut().poll(&mut task_context)
23241            else {
23242                panic!("expected typed activity validation error");
23243            };
23244            assert_eq!(error.kind, expected_kind);
23245            assert!(ctx.take_commands().expect("commands").is_empty());
23246        }
23247    }
23248
23249    #[test]
23250    fn activity_options_validate_positive_and_ordered_timeouts() {
23251        let zero_timeout_cases = [
23252            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
23253            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
23254            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
23255            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
23256        ];
23257        for options in zero_timeout_cases {
23258            assert_eq!(
23259                options.validate().expect_err("zero timeout").kind,
23260                ActivityOptionsErrorKind::TimeoutNotPositive
23261            );
23262        }
23263
23264        let ordering_cases = [
23265            ActivityOptions::new()
23266                .heartbeat_timeout(Duration::from_secs(11))
23267                .start_to_close_timeout(Duration::from_secs(10)),
23268            ActivityOptions::new()
23269                .start_to_close_timeout(Duration::from_secs(31))
23270                .schedule_to_close_timeout(Duration::from_secs(30)),
23271            ActivityOptions::new()
23272                .schedule_to_start_timeout(Duration::from_secs(31))
23273                .schedule_to_close_timeout(Duration::from_secs(30)),
23274        ];
23275        for options in ordering_cases {
23276            assert_eq!(
23277                options.validate().expect_err("timeout order").kind,
23278                ActivityOptionsErrorKind::TimeoutOrder
23279            );
23280        }
23281
23282        assert_eq!(
23283            ActivityOptions::new()
23284                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
23285                .validate()
23286                .expect_err("protocol integer overflow")
23287                .kind,
23288            ActivityOptionsErrorKind::TimeoutOverflow
23289        );
23290    }
23291
23292    #[test]
23293    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
23294        let ctx = workflow_context(completed_retry_activity_history());
23295        let mut call =
23296            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23297        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23298
23299        assert!(matches!(
23300            call.as_mut().poll(&mut task_context),
23301            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23302        ));
23303        assert!(ctx.take_commands().expect("commands").is_empty());
23304        ctx.ensure_history_consumed().expect("history consumed");
23305    }
23306
23307    #[test]
23308    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
23309        let mut options = retry_activity_options();
23310        options
23311            .retry_policy
23312            .as_mut()
23313            .expect("retry policy")
23314            .non_retryable_error_types
23315            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
23316
23317        let new_ctx = workflow_context(Vec::new());
23318        let mut new_call =
23319            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
23320        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23321        assert!(matches!(
23322            new_call.as_mut().poll(&mut task_context),
23323            Poll::Pending
23324        ));
23325        let commands = new_ctx.take_commands().expect("commands");
23326        assert_eq!(commands.len(), 1);
23327        assert_eq!(
23328            commands[0]["retry_policy"]["non_retryable_error_types"],
23329            json!(["PermanentError"])
23330        );
23331
23332        let replay_ctx = workflow_context(completed_retry_activity_history());
23333        let mut replay_call =
23334            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
23335        assert!(matches!(
23336            replay_call.as_mut().poll(&mut task_context),
23337            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23338        ));
23339        assert!(replay_ctx.take_commands().expect("commands").is_empty());
23340        replay_ctx
23341            .ensure_history_consumed()
23342            .expect("history consumed");
23343    }
23344
23345    #[test]
23346    fn replayed_intermediate_retry_remains_pending_across_restarts() {
23347        let history = completed_retry_activity_history()
23348            .into_iter()
23349            .take(3)
23350            .collect::<Vec<_>>();
23351
23352        for _restart in 0..2 {
23353            let ctx = workflow_context(history.clone());
23354            let mut call =
23355                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23356            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23357            assert!(matches!(
23358                call.as_mut().poll(&mut task_context),
23359                Poll::Pending
23360            ));
23361            assert!(ctx.take_commands().expect("commands").is_empty());
23362        }
23363    }
23364
23365    #[test]
23366    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
23367        let mut changed_queue = retry_activity_options();
23368        changed_queue.task_queue = Some("different-queue".to_string());
23369
23370        let mut changed_max_attempts = retry_activity_options();
23371        let retry_policy = changed_max_attempts
23372            .retry_policy
23373            .as_mut()
23374            .expect("retry policy");
23375        retry_policy.max_attempts = Some(4);
23376
23377        let mut changed_backoff = retry_activity_options();
23378        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
23379        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
23380            Duration::from_secs(3),
23381            Duration::from_secs(4),
23382        ]));
23383
23384        let mut changed_non_retryable_types = retry_activity_options();
23385        let retry_policy = changed_non_retryable_types
23386            .retry_policy
23387            .as_mut()
23388            .expect("retry policy");
23389        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
23390
23391        let mut changed_start_to_close = retry_activity_options();
23392        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
23393        let mut changed_schedule_to_start = retry_activity_options();
23394        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
23395        let mut changed_schedule_to_close = retry_activity_options();
23396        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
23397        let mut changed_heartbeat = retry_activity_options();
23398        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
23399
23400        let cases = [
23401            (changed_queue, "activity_task_queue_mismatch"),
23402            (changed_max_attempts, "activity_retry_policy_mismatch"),
23403            (changed_backoff, "activity_retry_policy_mismatch"),
23404            (
23405                changed_non_retryable_types,
23406                "activity_retry_policy_mismatch",
23407            ),
23408            (changed_start_to_close, "activity_retry_policy_mismatch"),
23409            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
23410            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
23411            (changed_heartbeat, "activity_retry_policy_mismatch"),
23412        ];
23413
23414        for (options, expected_reason) in cases {
23415            let ctx = workflow_context(completed_retry_activity_history());
23416            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
23417            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23418            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23419                call.as_mut().poll(&mut task_context)
23420            else {
23421                panic!("changed activity options must fail replay");
23422            };
23423            assert_eq!(failure.reason, expected_reason);
23424            assert_eq!(failure.sequence, Some(1));
23425            assert!(ctx.take_commands().expect("commands").is_empty());
23426        }
23427    }
23428
23429    #[test]
23430    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
23431        let cases = [
23432            (
23433                "execution_mode",
23434                json!("local"),
23435                "activity_execution_mode_mismatch",
23436            ),
23437            (
23438                "snapshot_version",
23439                json!(2),
23440                "activity_retry_policy_mismatch",
23441            ),
23442        ];
23443
23444        for (field, value, expected_reason) in cases {
23445            let mut history = completed_retry_activity_history();
23446            let activity = history[0].payload["activity"]
23447                .as_object_mut()
23448                .expect("activity snapshot");
23449            if field == "execution_mode" {
23450                activity.insert(field.to_string(), value);
23451            } else {
23452                activity["retry_policy"]
23453                    .as_object_mut()
23454                    .expect("retry snapshot")
23455                    .insert(field.to_string(), value);
23456            }
23457
23458            let ctx = workflow_context(history);
23459            let mut call =
23460                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23461            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23462            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23463                call.as_mut().poll(&mut task_context)
23464            else {
23465                panic!("changed {field} must fail replay");
23466            };
23467            assert_eq!(failure.reason, expected_reason);
23468            assert_eq!(failure.sequence, Some(1));
23469            assert!(ctx.take_commands().expect("commands").is_empty());
23470        }
23471    }
23472
23473    #[test]
23474    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
23475        for (nested, field, value, terminal_only) in [
23476            (false, "execution_mode", json!("local"), false),
23477            (false, "local_activity", json!(true), false),
23478            (true, "local_activity", json!(true), false),
23479            (false, "local_activity", json!(true), true),
23480        ] {
23481            let mut history = completed_retry_activity_history();
23482            history[0]
23483                .payload
23484                .as_object_mut()
23485                .unwrap()
23486                .remove("activity");
23487            let event = if terminal_only {
23488                history.last_mut().unwrap()
23489            } else {
23490                &mut history[0]
23491            };
23492            if nested {
23493                event.payload["activity"] = json!({(field): value});
23494            } else {
23495                event.payload[field] = value;
23496            }
23497            let ctx = workflow_context(history);
23498            let mut call =
23499                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23500            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23501            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23502                call.as_mut().poll(&mut task_context)
23503            else {
23504                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
23505            };
23506            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
23507            assert_eq!(failure.sequence, Some(1));
23508            assert!(ctx.take_commands().expect("commands").is_empty());
23509        }
23510    }
23511
23512    #[test]
23513    fn activity_history_rejects_conflicting_local_execution_markers() {
23514        let mut history = completed_retry_activity_history();
23515        history.last_mut().unwrap().payload["local_activity"] = json!(true);
23516        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
23517            .expect_err("remote schedule cannot become a local completion");
23518        assert!(
23519            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
23520            if reason == "activity_execution_mode_conflict")
23521        );
23522    }
23523
23524    #[test]
23525    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
23526        let mut history = completed_retry_activity_history();
23527        let activity = history[0].payload["activity"]
23528            .as_object_mut()
23529            .expect("activity snapshot");
23530        activity.remove("execution_mode");
23531        activity.remove("retry_policy");
23532
23533        let mut current = retry_activity_options();
23534        current.start_to_close_timeout = Some(Duration::from_secs(45));
23535        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
23536        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
23537        current.heartbeat_timeout = Some(Duration::from_secs(12));
23538
23539        let ctx = workflow_context(history);
23540        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
23541        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23542        assert!(matches!(
23543            call.as_mut().poll(&mut task_context),
23544            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23545        ));
23546        assert!(ctx.take_commands().expect("commands").is_empty());
23547        ctx.ensure_history_consumed().expect("history consumed");
23548    }
23549
23550    #[test]
23551    fn terminal_activity_failed_after_start_returns_typed_failure() {
23552        let history = vec![
23553            history_event(
23554                "ActivityScheduled",
23555                json!({
23556                    "sequence": 1,
23557                    "activity_type": "flaky",
23558                    "activity_execution_id": "act-terminal",
23559                    "activity": {
23560                        "id": "act-terminal",
23561                        "sequence": 1,
23562                        "type": "flaky",
23563                        "queue": "critical-activities",
23564                        "retry_policy": {
23565                            "snapshot_version": 1,
23566                            "max_attempts": 3,
23567                            "backoff_seconds": [2, 4],
23568                            "non_retryable_error_types": ["PermanentError"]
23569                        }
23570                    }
23571                }),
23572            ),
23573            history_event(
23574                "ActivityStarted",
23575                json!({
23576                    "sequence": 1,
23577                    "activity_type": "flaky",
23578                    "activity_execution_id": "act-terminal",
23579                    "activity_attempt_id": "attempt-1",
23580                    "attempt_number": 1
23581                }),
23582            ),
23583            history_event(
23584                "ActivityFailed",
23585                json!({
23586                    "sequence": 1,
23587                    "activity_type": "flaky",
23588                    "activity_execution_id": "act-terminal",
23589                    "activity_attempt_id": "attempt-1",
23590                    "attempt_number": 1,
23591                    "failure_id": "failure-terminal",
23592                    "failure_category": "activity",
23593                    "exception_type": "PermanentError",
23594                    "message": "cannot retry",
23595                    "non_retryable": true
23596                }),
23597            ),
23598        ];
23599        let ctx = workflow_context(history);
23600        let mut call =
23601            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23602        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23603
23604        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23605            call.as_mut().poll(&mut task_context)
23606        else {
23607            panic!("terminal ActivityFailed must settle the activity future");
23608        };
23609        assert_eq!(failure.kind, ActivityFailureKind::Failed);
23610        assert_eq!(
23611            failure.activity_execution_id.as_deref(),
23612            Some("act-terminal")
23613        );
23614        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
23615        assert!(failure.non_retryable);
23616        assert!(ctx.take_commands().expect("commands").is_empty());
23617        ctx.ensure_history_consumed().expect("history consumed");
23618    }
23619
23620    #[test]
23621    fn activity_terminal_events_return_machine_readable_failures() {
23622        let cases = [
23623            (
23624                "ActivityFailed",
23625                json!({
23626                    "sequence": 1,
23627                    "activity_type": "charge-card",
23628                    "activity_execution_id": "act-1",
23629                    "activity_attempt_id": "attempt-2",
23630                    "attempt_number": 2,
23631                    "failure_id": "failure-1",
23632                    "failure_category": "activity",
23633                    "exception_type": "PaymentDeclined",
23634                    "exception_class": "payments.PaymentDeclined",
23635                    "message": "card declined",
23636                    "non_retryable": true
23637                }),
23638                ActivityFailureKind::Failed,
23639                "activity",
23640            ),
23641            (
23642                "ActivityCancelled",
23643                json!({
23644                    "sequence": 1,
23645                    "activity_type": "charge-card",
23646                    "activity_execution_id": "act-1",
23647                    "activity_attempt_id": "attempt-1"
23648                }),
23649                ActivityFailureKind::Cancelled,
23650                "cancelled",
23651            ),
23652        ];
23653
23654        for (event_type, payload, expected_kind, expected_reason) in cases {
23655            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23656            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23657            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23658            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23659                call.as_mut().poll(&mut task_context)
23660            else {
23661                panic!("expected terminal activity failure");
23662            };
23663            assert_eq!(failure.kind, expected_kind);
23664            assert_eq!(failure.reason, expected_reason);
23665            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23666            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23667        }
23668    }
23669
23670    #[test]
23671    fn every_activity_timeout_class_is_typed() {
23672        for timeout_kind in [
23673            "start_to_close",
23674            "schedule_to_start",
23675            "schedule_to_close",
23676            "heartbeat",
23677        ] {
23678            let ctx = workflow_context(vec![history_event(
23679                "ActivityTimedOut",
23680                json!({
23681                    "sequence": 1,
23682                    "activity_type": "slow",
23683                    "activity_execution_id": "act-timeout",
23684                    "activity_attempt_id": "attempt-timeout",
23685                    "failure_category": "timeout",
23686                    "timeout_kind": timeout_kind,
23687                    "message": "deadline expired"
23688                }),
23689            )]);
23690            let mut call = Box::pin(ctx.activity("slow", json!([])));
23691            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23692            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23693                call.as_mut().poll(&mut task_context)
23694            else {
23695                panic!("expected timeout failure");
23696            };
23697            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23698            assert_eq!(failure.reason, timeout_kind);
23699            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23700            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23701        }
23702    }
23703
23704    #[test]
23705    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23706        let ctx = workflow_context(Vec::new());
23707        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23708        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23709
23710        assert!(matches!(
23711            sleep.as_mut().poll(&mut task_context),
23712            Poll::Pending
23713        ));
23714        assert!(matches!(
23715            sleep.as_mut().poll(&mut task_context),
23716            Poll::Pending
23717        ));
23718
23719        let commands = ctx.take_commands().expect("timer command");
23720        assert_eq!(
23721            commands,
23722            vec![json!({
23723                "type": "start_timer",
23724                "delay_seconds": 2,
23725            })]
23726        );
23727    }
23728
23729    #[test]
23730    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23731        let history = vec![
23732            history_event(
23733                "TimerScheduled",
23734                json!({
23735                    "sequence": 1,
23736                    "timer_id": "timer-1",
23737                    "delay_seconds": 5,
23738                    "fire_at": "2026-07-11T12:00:05Z",
23739                }),
23740            ),
23741            history_event(
23742                "TimerFired",
23743                json!({
23744                    "sequence": 1,
23745                    "timer_id": "timer-1",
23746                    "delay_seconds": 5,
23747                    "fire_at": "2026-07-11T12:00:05Z",
23748                    "fired_at": "2026-07-11T12:00:05Z",
23749                }),
23750            ),
23751        ];
23752
23753        for _restart in 0..2 {
23754            let ctx = workflow_context(history.clone());
23755            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23756            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23757            assert!(matches!(
23758                sleep.as_mut().poll(&mut task_context),
23759                Poll::Ready(Ok(()))
23760            ));
23761            assert!(ctx.take_commands().expect("commands").is_empty());
23762            ctx.ensure_history_consumed().expect("history consumed");
23763        }
23764    }
23765
23766    #[test]
23767    fn workflow_sleep_rejects_changed_delay_during_replay() {
23768        let ctx = workflow_context(vec![
23769            history_event(
23770                "TimerScheduled",
23771                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23772            ),
23773            history_event(
23774                "TimerFired",
23775                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23776            ),
23777        ]);
23778        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23779        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23780
23781        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23782            sleep.as_mut().poll(&mut task_context)
23783        else {
23784            panic!("changed timer delay must be rejected");
23785        };
23786        assert_eq!(failure.reason, "timer_delay_mismatch");
23787        assert_eq!(failure.sequence, Some(1));
23788    }
23789
23790    #[test]
23791    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23792        let ctx = workflow_context(Vec::new());
23793        let mut wait = Box::pin(
23794            ctx.wait_condition(
23795                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23796                    .timeout(Duration::from_millis(60_001)),
23797                || Ok(false),
23798            ),
23799        );
23800        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23801
23802        assert!(matches!(
23803            wait.as_mut().poll(&mut task_context),
23804            Poll::Pending
23805        ));
23806        assert!(matches!(
23807            wait.as_mut().poll(&mut task_context),
23808            Poll::Pending
23809        ));
23810        assert_eq!(
23811            ctx.take_commands().expect("condition command"),
23812            vec![json!({
23813                "type": "open_condition_wait",
23814                "condition_wait_occurrence_id": "rust:condition-wait:0",
23815                "condition_key": "approval.ready",
23816                "condition_definition_fingerprint": "sha256:approval-v1",
23817                "timeout_seconds": 61,
23818            })]
23819        );
23820    }
23821
23822    #[test]
23823    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23824        let ctx = workflow_context(Vec::new());
23825        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23826        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23827        assert!(matches!(
23828            satisfied.as_mut().poll(&mut task_context),
23829            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23830        ));
23831
23832        let mut timed_out = Box::pin(wait_condition!(
23833            ctx,
23834            "no-wait",
23835            timeout: Duration::ZERO,
23836            || Ok(false),
23837        ));
23838        assert!(matches!(
23839            timed_out.as_mut().poll(&mut task_context),
23840            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23841        ));
23842        assert!(ctx.take_commands().expect("commands").is_empty());
23843    }
23844
23845    #[test]
23846    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23847        let signal_history = vec![
23848            history_event(
23849                "ConditionWaitOpened",
23850                json!({
23851                    "sequence": 4,
23852                    "condition_wait_id": "condition:4",
23853                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23854                    "condition_key": "approval",
23855                    "condition_definition_fingerprint": "sha256:approval-v1",
23856                    "timeout_seconds": 30,
23857                }),
23858            ),
23859            history_event(
23860                "SignalReceived",
23861                json!({
23862                    "workflow_sequence": 4,
23863                    "signal_name": "approve",
23864                    "arguments": fixture_envelope(json!(["Ada"])),
23865                }),
23866            ),
23867        ];
23868        for _worker_before_or_after_restart in 0..2 {
23869            let ctx = workflow_context(signal_history.clone());
23870            let predicate_ctx = ctx.clone();
23871            let mut wait = Box::pin(
23872                ctx.wait_condition(
23873                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23874                        .timeout(Duration::from_secs(30)),
23875                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23876                ),
23877            );
23878            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23879            assert!(matches!(
23880                wait.as_mut().poll(&mut task_context),
23881                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23882            ));
23883            assert!(ctx.take_commands().expect("commands").is_empty());
23884            ctx.ensure_history_consumed().expect("condition consumed");
23885        }
23886
23887        let update_history = vec![
23888            history_event(
23889                "ConditionWaitOpened",
23890                json!({
23891                    "sequence": 7,
23892                    "condition_wait_id": "condition:7",
23893                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23894                    "condition_key": "update-approval",
23895                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23896                }),
23897            ),
23898            history_event(
23899                "UpdateApplied",
23900                json!({
23901                    "sequence": 7,
23902                    "update_id": "update-1",
23903                    "update_name": "approve",
23904                    "arguments": fixture_envelope(json!([true])),
23905                }),
23906            ),
23907        ];
23908        let ctx = workflow_context(update_history);
23909        let predicate_ctx = ctx.clone();
23910        let mut wait = Box::pin(ctx.wait_condition(
23911            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23912            move || {
23913                Ok(predicate_ctx
23914                    .updates("approve")?
23915                    .first()
23916                    .and_then(|arguments| arguments.first())
23917                    .and_then(Value::as_bool)
23918                    == Some(true))
23919            },
23920        ));
23921        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23922        assert!(matches!(
23923            wait.as_mut().poll(&mut task_context),
23924            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23925        ));
23926        assert!(ctx.take_commands().expect("commands").is_empty());
23927        ctx.ensure_history_consumed().expect("condition consumed");
23928    }
23929
23930    #[test]
23931    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23932        let open_history = vec![
23933            history_event(
23934                "ConditionWaitOpened",
23935                json!({
23936                    "sequence": 3,
23937                    "condition_wait_id": "condition:3",
23938                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23939                    "condition_key": "two-votes",
23940                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23941                    "timeout_seconds": 120,
23942                }),
23943            ),
23944            history_event(
23945                "SignalReceived",
23946                json!({
23947                    "workflow_sequence": 3,
23948                    "signal_name": "vote",
23949                    "arguments": fixture_envelope(json!(["first"])),
23950                }),
23951            ),
23952        ];
23953        for _worker_before_or_after_restart in 0..2 {
23954            let ctx = workflow_context(open_history.clone());
23955            let predicate_ctx = ctx.clone();
23956            let mut wait = Box::pin(
23957                ctx.wait_condition(
23958                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23959                        .timeout(Duration::from_secs(120)),
23960                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23961                ),
23962            );
23963            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23964            assert!(matches!(
23965                wait.as_mut().poll(&mut task_context),
23966                Poll::Pending
23967            ));
23968            assert_eq!(
23969                ctx.take_commands().expect("reopened condition"),
23970                vec![json!({
23971                    "type": "open_condition_wait",
23972                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23973                    "condition_key": "two-votes",
23974                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23975                    "timeout_seconds": 120,
23976                })]
23977            );
23978        }
23979
23980        let satisfied_ctx = workflow_context(vec![
23981            history_event(
23982                "ConditionWaitOpened",
23983                json!({
23984                    "sequence": 5,
23985                    "condition_wait_id": "condition:5",
23986                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23987                    "condition_key": "approval",
23988                    "condition_definition_fingerprint": "sha256:approval-v1",
23989                }),
23990            ),
23991            history_event(
23992                "ConditionWaitSatisfied",
23993                json!({
23994                    "sequence": 5,
23995                    "condition_wait_id": "condition:5",
23996                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23997                    "condition_key": "approval",
23998                    "condition_definition_fingerprint": "sha256:approval-v1",
23999                }),
24000            ),
24001        ]);
24002        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
24003            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
24004            || Ok(false),
24005        ));
24006        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24007        assert!(matches!(
24008            satisfied.as_mut().poll(&mut task_context),
24009            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24010        ));
24011
24012        let timed_out_ctx = workflow_context(vec![
24013            history_event(
24014                "ConditionWaitOpened",
24015                json!({
24016                    "sequence": 8,
24017                    "condition_wait_id": "condition:8",
24018                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24019                    "condition_key": "approval-timeout",
24020                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
24021                    "timeout_seconds": 5,
24022                }),
24023            ),
24024            history_event(
24025                "TimerScheduled",
24026                json!({
24027                    "sequence": 9,
24028                    "timer_id": "condition-timer:9",
24029                    "timer_kind": "condition_timeout",
24030                    "condition_wait_id": "condition:8",
24031                    "delay_seconds": 5,
24032                }),
24033            ),
24034            history_event(
24035                "TimerFired",
24036                json!({
24037                    "sequence": 9,
24038                    "timer_id": "condition-timer:9",
24039                    "timer_kind": "condition_timeout",
24040                    "condition_wait_id": "condition:8",
24041                    "delay_seconds": 5,
24042                }),
24043            ),
24044        ]);
24045        let mut timed_out = Box::pin(
24046            timed_out_ctx.wait_condition(
24047                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
24048                    .timeout(Duration::from_secs(5)),
24049                || Ok(true),
24050            ),
24051        );
24052        assert!(matches!(
24053            timed_out.as_mut().poll(&mut task_context),
24054            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24055        ));
24056    }
24057
24058    #[test]
24059    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
24060        let ctx = workflow_context(reopened_selection_condition_history());
24061        {
24062            let state = ctx.state.lock().unwrap();
24063            assert!(matches!(
24064                selection_member_recorded_command(&state, 2),
24065                Some(RecordedCommand::ConditionWait {
24066                    sequence: 3,
24067                    result: None,
24068                    ..
24069                })
24070            ));
24071        }
24072        let mut selected = Box::pin(ctx.select_keyed(vec![
24073            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24074            (
24075                "votes",
24076                ParallelOperation::condition(
24077                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24078                    || Ok(true),
24079                ),
24080            ),
24081        ]));
24082        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24083        assert!(selected.as_mut().poll(&mut task_context).is_pending());
24084        assert!(
24085            ctx.take_commands().unwrap().is_empty(),
24086            "true predicate must not reopen the recorded wait"
24087        );
24088        ctx.ensure_history_consumed()
24089            .expect("physical reopens are consumed while canonical selection is pending");
24090    }
24091
24092    #[test]
24093    fn reopened_selection_condition_replays_its_latest_physical_winner() {
24094        for (terminal_type, acknowledge_timeout) in [
24095            ("ConditionWaitSatisfied", false),
24096            ("ConditionWaitTimedOut", false),
24097            ("TimerFired", false),
24098            ("TimerFired", true),
24099        ] {
24100            let mut history = reopened_selection_condition_history();
24101            let original_identity = history[1].payload["condition_wait_id"].clone();
24102            let uses_timer = terminal_type == "TimerFired";
24103            let mut resolution_payload = history[3].payload.clone();
24104            if uses_timer {
24105                for event in &mut history[1..] {
24106                    event.payload["timeout_seconds"] = json!(3);
24107                }
24108                resolution_payload = history[3].payload.clone();
24109                resolution_payload["timer_kind"] = json!("condition_timeout");
24110                resolution_payload["timer_id"] = json!("condition-timeout-3");
24111                resolution_payload["delay_seconds"] = json!(3);
24112                history.push(history_event("TimerScheduled", resolution_payload.clone()));
24113            }
24114            let mut resolution = history_event(terminal_type, resolution_payload.clone());
24115            resolution
24116                .raw
24117                .insert("id".into(), json!("latest-condition-resolution"));
24118            history.push(resolution);
24119            history.push(history_event(
24120                "SelectionResolved",
24121                json!({
24122                    "selection_group_id": "select-calls:1:2",
24123                    "selection_group_base_sequence": 1,
24124                    "selection_group_size": 2,
24125                    "member_key": "votes",
24126                    "member_index": 1,
24127                    "member_base_sequence": 2,
24128                    "member_size": 1,
24129                    "operation_kind": "condition",
24130                    "operation_identity": original_identity,
24131                    "outcome": "completed",
24132                    "resolution_event_id": "latest-condition-resolution",
24133                    "resolution_event_type": terminal_type,
24134                }),
24135            ));
24136            if acknowledge_timeout {
24137                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
24138            }
24139            let ctx = workflow_context(history);
24140            let mut selected = Box::pin(ctx.select_keyed(vec![
24141                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24142                (
24143                    "votes",
24144                    ParallelOperation::condition(
24145                        if uses_timer {
24146                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24147                                .timeout(Duration::from_secs(3))
24148                        } else {
24149                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24150                        },
24151                        || Ok(true),
24152                    ),
24153                ),
24154            ]));
24155            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24156            match selected.as_mut().poll(&mut task_context) {
24157                Poll::Ready(Ok(result)) => {
24158                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
24159                    let expected = if terminal_type == "ConditionWaitSatisfied" {
24160                        ConditionWaitResult::Satisfied
24161                    } else {
24162                        ConditionWaitResult::TimedOut
24163                    };
24164                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
24165                }
24166                other => panic!("latest physical winner must replay: {other:?}"),
24167            }
24168            assert!(ctx.take_commands().unwrap().is_empty());
24169            ctx.ensure_history_consumed()
24170                .expect("winner history consumed");
24171        }
24172    }
24173
24174    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
24175        let fixture: Value = serde_json::from_str(include_str!(
24176            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24177        ))
24178        .expect("grouped condition fixture");
24179        fixture["history"]
24180            .as_array()
24181            .unwrap()
24182            .iter()
24183            .map(|event| {
24184                let mut payload = event["payload"].clone();
24185                let index = payload["parallel_group_index"].as_u64().unwrap();
24186                payload["parallel_group_id"] = json!("select-calls:1:2");
24187                payload["parallel_group_mode"] = json!("select");
24188                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
24189                payload["selection_member_index"] = json!(index);
24190                payload["selection_member_base_sequence"] = json!(index + 1);
24191                payload["selection_member_size"] = json!(1);
24192                payload["selection_member_kind"] =
24193                    json!(if index == 0 { "timer" } else { "condition" });
24194                history_event(event["event_type"].as_str().unwrap(), payload)
24195            })
24196            .collect()
24197    }
24198
24199    #[test]
24200    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
24201        let fixture: Value = serde_json::from_str(include_str!(
24202            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24203        ))
24204        .expect("grouped condition fixture");
24205        let original = fixture["history"].as_array().expect("fixture history");
24206        let decode = |events: &[Value]| {
24207            let history = events
24208                .iter()
24209                .map(|event| {
24210                    history_event(
24211                        event["event_type"].as_str().unwrap(),
24212                        event["payload"].clone(),
24213                    )
24214                })
24215                .collect::<Vec<_>>();
24216            recorded_commands(
24217                &history,
24218                DEFAULT_CODEC,
24219                WorkflowIdentity {
24220                    workflow_id: None,
24221                    run_id: None,
24222                },
24223            )
24224        };
24225        assert!(decode(original).is_ok());
24226        for field in [
24227            "condition_wait_occurrence_id",
24228            "condition_key",
24229            "condition_definition_fingerprint",
24230            "timeout_seconds",
24231            "parallel_group_id",
24232            "parallel_group_size",
24233            "parallel_group_index",
24234        ] {
24235            let mut changed = original.clone();
24236            changed[3]["payload"][field] = match field {
24237                "timeout_seconds" | "parallel_group_size" => json!(30),
24238                "parallel_group_index" => json!(0),
24239                _ => json!("changed"),
24240            };
24241            assert!(
24242                decode(&changed).is_err(),
24243                "reopen must reject changed {field}"
24244            );
24245        }
24246        let mut unsettled = original.clone();
24247        unsettled.remove(2);
24248        assert!(
24249            decode(&unsettled).is_err(),
24250            "physical predecessor must be resolved"
24251        );
24252        let mut timed_out = original.clone();
24253        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
24254        assert!(decode(&timed_out).is_err(), "timeout is terminal");
24255        let mut late_resolution = original.clone();
24256        late_resolution.swap(2, 3);
24257        assert!(
24258            decode(&late_resolution).is_err(),
24259            "later history cannot authorize a reopen"
24260        );
24261    }
24262
24263    #[test]
24264    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
24265        let history = vec![
24266            history_event(
24267                "ConditionWaitOpened",
24268                json!({
24269                    "sequence": 3,
24270                    "condition_wait_id": "condition:3",
24271                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24272                    "condition_key": "two-votes",
24273                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24274                }),
24275            ),
24276            history_event(
24277                "SignalReceived",
24278                json!({
24279                    "workflow_sequence": 3,
24280                    "signal_name": "vote",
24281                    "arguments": fixture_envelope(json!(["first"])),
24282                }),
24283            ),
24284            history_event(
24285                "ConditionWaitSatisfied",
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                "ConditionWaitOpened",
24296                json!({
24297                    "sequence": 5,
24298                    "condition_wait_id": "condition:5",
24299                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24300                    "condition_key": "two-votes",
24301                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24302                }),
24303            ),
24304            history_event(
24305                "SignalReceived",
24306                json!({
24307                    "workflow_sequence": 5,
24308                    "signal_name": "vote",
24309                    "arguments": fixture_envelope(json!(["second"])),
24310                }),
24311            ),
24312            history_event(
24313                "ConditionWaitSatisfied",
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        ];
24323        for _cold_worker_or_restart in 0..2 {
24324            let ctx = workflow_context(history.clone());
24325            let predicate_ctx = ctx.clone();
24326            let mut wait = Box::pin(ctx.wait_condition(
24327                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24328                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24329            ));
24330            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24331
24332            assert!(matches!(
24333                wait.as_mut().poll(&mut task_context),
24334                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24335            ));
24336            assert!(ctx.take_commands().expect("commands").is_empty());
24337            ctx.ensure_history_consumed()
24338                .expect("every physical wait-open is consumed");
24339        }
24340    }
24341
24342    #[test]
24343    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
24344        let history = vec![
24345            history_event(
24346                "ConditionWaitOpened",
24347                json!({
24348                    "sequence": 3,
24349                    "condition_wait_id": "condition:3",
24350                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24351                    "condition_key": "approved",
24352                    "condition_definition_fingerprint": "sha256:approved-v1",
24353                }),
24354            ),
24355            history_event(
24356                "UpdateApplied",
24357                json!({
24358                    "sequence": 3,
24359                    "update_id": "update-1",
24360                    "update_name": "approve",
24361                    "arguments": fixture_envelope(json!([false])),
24362                }),
24363            ),
24364            history_event(
24365                "ConditionWaitOpened",
24366                json!({
24367                    "sequence": 5,
24368                    "condition_wait_id": "condition:5",
24369                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24370                    "condition_key": "approved",
24371                    "condition_definition_fingerprint": "sha256:approved-v1",
24372                }),
24373            ),
24374            history_event(
24375                "UpdateApplied",
24376                json!({
24377                    "sequence": 5,
24378                    "update_id": "update-2",
24379                    "update_name": "approve",
24380                    "arguments": fixture_envelope(json!([true])),
24381                }),
24382            ),
24383        ];
24384
24385        for _cold_worker_or_restart in 0..2 {
24386            let ctx = workflow_context(history.clone());
24387            let predicate_ctx = ctx.clone();
24388            let mut wait = Box::pin(ctx.wait_condition(
24389                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
24390                move || {
24391                    Ok(predicate_ctx
24392                        .updates("approve")?
24393                        .last()
24394                        .and_then(|arguments| arguments.first())
24395                        .and_then(Value::as_bool)
24396                        == Some(true))
24397                },
24398            ));
24399            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24400
24401            assert!(matches!(
24402                wait.as_mut().poll(&mut task_context),
24403                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24404            ));
24405            assert!(ctx.take_commands().expect("commands").is_empty());
24406            ctx.ensure_history_consumed()
24407                .expect("every update-driven reopen is consumed");
24408        }
24409    }
24410
24411    #[test]
24412    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
24413        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
24414            ("shared", "sha256:first", "shared", "sha256:second"),
24415            ("first", "sha256:shared", "second", "sha256:shared"),
24416            ("shared", "sha256:shared", "shared", "sha256:shared"),
24417            ("first", "sha256:first", "second", "sha256:second"),
24418        ] {
24419            let history = vec![
24420                history_event(
24421                    "ConditionWaitOpened",
24422                    json!({
24423                        "sequence": 3,
24424                        "condition_wait_id": "condition:3",
24425                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24426                        "condition_key": first_key,
24427                        "condition_definition_fingerprint": first_fingerprint,
24428                    }),
24429                ),
24430                history_event(
24431                    "ConditionWaitSatisfied",
24432                    json!({
24433                        "sequence": 3,
24434                        "condition_wait_id": "condition:3",
24435                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24436                        "condition_key": first_key,
24437                        "condition_definition_fingerprint": first_fingerprint,
24438                    }),
24439                ),
24440                history_event(
24441                    "ConditionWaitOpened",
24442                    json!({
24443                        "sequence": 4,
24444                        "condition_wait_id": "condition:4",
24445                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24446                        "condition_key": second_key,
24447                        "condition_definition_fingerprint": second_fingerprint,
24448                    }),
24449                ),
24450                history_event(
24451                    "ConditionWaitSatisfied",
24452                    json!({
24453                        "sequence": 4,
24454                        "condition_wait_id": "condition:4",
24455                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24456                        "condition_key": second_key,
24457                        "condition_definition_fingerprint": second_fingerprint,
24458                    }),
24459                ),
24460            ];
24461            for _cold_worker_or_restart in 0..2 {
24462                let ctx = workflow_context(history.clone());
24463                let mut task_context = TaskContext::from_waker(noop_waker_ref());
24464                let mut first = Box::pin(ctx.wait_condition(
24465                    ConditionWaitOptions::new(first_key, first_fingerprint),
24466                    || Ok(false),
24467                ));
24468                assert!(matches!(
24469                    first.as_mut().poll(&mut task_context),
24470                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24471                ));
24472
24473                let mut second = Box::pin(ctx.wait_condition(
24474                    ConditionWaitOptions::new(second_key, second_fingerprint),
24475                    || Ok(false),
24476                ));
24477                assert!(matches!(
24478                    second.as_mut().poll(&mut task_context),
24479                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24480                ));
24481                assert!(ctx.take_commands().expect("commands").is_empty());
24482                ctx.ensure_history_consumed()
24483                    .expect("each authored wait consumes one occurrence");
24484            }
24485        }
24486    }
24487
24488    #[test]
24489    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
24490        fn worker() -> Worker {
24491            let client = Client::new("http://127.0.0.1:8080").expect("client");
24492            let mut worker = Worker::new(client, "rust-workers");
24493            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
24494                let mut outcomes = Vec::new();
24495                for _ in 0..2 {
24496                    outcomes.push(
24497                        ctx.wait_condition(
24498                            ConditionWaitOptions::new("shared", "sha256:shared"),
24499                            || Ok(false),
24500                        )
24501                        .await?,
24502                    );
24503                }
24504                Ok(json!(outcomes))
24505            });
24506            worker
24507        }
24508
24509        let task = workflow_task(
24510            "rust.condition-loop",
24511            vec![
24512                history_event(
24513                    "ConditionWaitOpened",
24514                    json!({
24515                        "sequence": 1,
24516                        "condition_wait_id": "condition:1",
24517                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24518                        "condition_key": "shared",
24519                        "condition_definition_fingerprint": "sha256:shared",
24520                    }),
24521                ),
24522                history_event(
24523                    "ConditionWaitSatisfied",
24524                    json!({
24525                        "sequence": 1,
24526                        "condition_wait_id": "condition:1",
24527                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24528                        "condition_key": "shared",
24529                        "condition_definition_fingerprint": "sha256:shared",
24530                    }),
24531                ),
24532                history_event(
24533                    "ConditionWaitOpened",
24534                    json!({
24535                        "sequence": 2,
24536                        "condition_wait_id": "condition:2",
24537                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24538                        "condition_key": "shared",
24539                        "condition_definition_fingerprint": "sha256:shared",
24540                    }),
24541                ),
24542                history_event(
24543                    "ConditionWaitSatisfied",
24544                    json!({
24545                        "sequence": 2,
24546                        "condition_wait_id": "condition:2",
24547                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24548                        "condition_key": "shared",
24549                        "condition_definition_fingerprint": "sha256:shared",
24550                    }),
24551                ),
24552            ],
24553            DEFAULT_CODEC,
24554        );
24555
24556        for _cold_worker_or_restart in 0..2 {
24557            let commands = worker()
24558                .execute_workflow_task(task.clone())
24559                .expect("adjacent loop waits replay deterministically");
24560            assert_eq!(commands.len(), 1);
24561            assert_eq!(commands[0]["type"], "complete_workflow");
24562            assert_eq!(
24563                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24564                json!(["satisfied", "satisfied"])
24565            );
24566        }
24567    }
24568
24569    #[test]
24570    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
24571        let history = vec![history_event(
24572            "ConditionWaitOpened",
24573            json!({
24574                "sequence": 12,
24575                "condition_wait_id": "condition:12",
24576                "condition_wait_occurrence_id": "rust:condition-wait:0",
24577                "condition_key": "approval",
24578                "condition_definition_fingerprint": "sha256:approval-v1",
24579                "timeout_seconds": 30,
24580            }),
24581        )];
24582        for (options, expected_reason) in [
24583            (
24584                ConditionWaitOptions::new("changed", "sha256:approval-v1")
24585                    .timeout(Duration::from_secs(30)),
24586                "condition_wait_key_mismatch",
24587            ),
24588            (
24589                ConditionWaitOptions::new("approval", "sha256:approval-v2")
24590                    .timeout(Duration::from_secs(30)),
24591                "condition_wait_predicate_mismatch",
24592            ),
24593            (
24594                ConditionWaitOptions::new("approval", "sha256:approval-v1")
24595                    .timeout(Duration::from_secs(29)),
24596                "condition_wait_timeout_mismatch",
24597            ),
24598        ] {
24599            let ctx = workflow_context(history.clone());
24600            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
24601            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24602            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24603                wait.as_mut().poll(&mut task_context)
24604            else {
24605                panic!("changed condition definition must fail replay");
24606            };
24607            assert_eq!(failure.reason, expected_reason);
24608            assert_eq!(failure.sequence, Some(12));
24609        }
24610    }
24611
24612    #[test]
24613    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
24614        let error = WorkflowState::new(
24615            vec![history_event(
24616                "ConditionWaitOpened",
24617                json!({
24618                    "sequence": 12,
24619                    "condition_wait_id": "condition:12",
24620                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24621                    "condition_key": "approval",
24622                }),
24623            )],
24624            "rust-workers".to_string(),
24625            DEFAULT_CODEC.to_string(),
24626            None,
24627        )
24628        .expect_err("condition history without a predicate fingerprint must fail");
24629
24630        assert!(matches!(
24631            error,
24632            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24633                if reason == "condition_wait_predicate_fingerprint_missing"
24634        ));
24635    }
24636
24637    #[test]
24638    fn condition_wait_history_requires_authored_occurrence_identity() {
24639        let error = WorkflowState::new(
24640            vec![history_event(
24641                "ConditionWaitOpened",
24642                json!({
24643                    "sequence": 12,
24644                    "condition_wait_id": "condition:12",
24645                    "condition_key": "approval",
24646                    "condition_definition_fingerprint": "sha256:approval-v1",
24647                }),
24648            )],
24649            "rust-workers".to_string(),
24650            DEFAULT_CODEC.to_string(),
24651            None,
24652        )
24653        .expect_err("condition history without occurrence identity must fail");
24654
24655        assert!(matches!(
24656            error,
24657            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24658                if reason == "condition_wait_occurrence_id_missing"
24659        ));
24660    }
24661
24662    #[test]
24663    fn typed_search_attribute_updates_validate_emit_and_replay() {
24664        let update = SearchAttributeUpdate::new()
24665            .keyword("OrderStatus", " waiting ")
24666            .expect("keyword")
24667            .int("Attempt", 3)
24668            .expect("int")
24669            .bool("Escalated", false)
24670            .expect("bool")
24671            .keyword_list("Regions", ["us-east", "eu-west"])
24672            .expect("list")
24673            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24674            .expect("datetime")
24675            .delete("LegacyStatus")
24676            .expect("delete");
24677        let ctx = workflow_context(Vec::new());
24678        ctx.upsert_search_attributes(update.clone())
24679            .expect("typed update");
24680        assert_eq!(
24681            ctx.take_commands().expect("search-attribute command"),
24682            vec![json!({
24683                "type": "upsert_search_attributes",
24684                "attributes": {
24685                    "Attempt": 3,
24686                    "Escalated": false,
24687                    "LegacyStatus": null,
24688                    "OrderStatus": "waiting",
24689                    "Regions": ["us-east", "eu-west"],
24690                    "UpdatedAt": "2026-08-22T04:00:00Z",
24691                },
24692                "attribute_types": {
24693                    "Attempt": "int",
24694                    "Escalated": "bool",
24695                    "OrderStatus": "keyword",
24696                    "Regions": "keyword_list",
24697                    "UpdatedAt": "datetime",
24698                },
24699            })]
24700        );
24701
24702        let replay = workflow_context(vec![history_event(
24703            "SearchAttributesUpserted",
24704            json!({
24705                "sequence": 6,
24706                "attributes": {
24707                    "Attempt": 3,
24708                    "Escalated": false,
24709                    "LegacyStatus": null,
24710                    "OrderStatus": "waiting",
24711                    "Regions": ["us-east", "eu-west"],
24712                    "UpdatedAt": "2026-08-22T04:00:00Z",
24713                },
24714                "attribute_types": {
24715                    "Attempt": "int",
24716                    "Escalated": "bool",
24717                    "OrderStatus": "keyword",
24718                    "Regions": "keyword_list",
24719                    "UpdatedAt": "datetime",
24720                },
24721                "merged": {},
24722            }),
24723        )]);
24724        replay
24725            .upsert_search_attributes(update)
24726            .expect("matching update replays");
24727        assert!(replay.take_commands().expect("commands").is_empty());
24728        replay.ensure_history_consumed().expect("history consumed");
24729
24730        let type_drift = workflow_context(vec![history_event(
24731            "SearchAttributesUpserted",
24732            json!({
24733                "sequence": 7,
24734                "attributes": {"OrderStatus": "waiting"},
24735                "attribute_types": {"OrderStatus": "keyword"},
24736                "merged": {"OrderStatus": "waiting"},
24737            }),
24738        )]);
24739        let error = type_drift
24740            .upsert_search_attributes(
24741                SearchAttributeUpdate::new()
24742                    .string("OrderStatus", "waiting")
24743                    .expect("string update"),
24744            )
24745            .expect_err("same JSON value with a changed type must fail replay");
24746        assert!(matches!(
24747            error,
24748            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24749                if reason == "search_attribute_type_mismatch"
24750        ));
24751
24752        let malformed_types = WorkflowState::new(
24753            vec![history_event(
24754                "SearchAttributesUpserted",
24755                json!({
24756                    "sequence": 8,
24757                    "attributes": {"OrderStatus": "waiting"},
24758                    "attribute_types": {"OrderStatus": "unsupported"},
24759                    "merged": {"OrderStatus": "waiting"},
24760                }),
24761            )],
24762            "rust-workers".to_string(),
24763            DEFAULT_CODEC.to_string(),
24764            None,
24765        )
24766        .expect_err("unsupported search-attribute type metadata must fail");
24767        assert!(matches!(
24768            malformed_types,
24769            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24770                if reason == "search_attribute_types_malformed"
24771        ));
24772
24773        assert!(matches!(
24774            SearchAttributeUpdate::new().keyword("bad key", "value"),
24775            Err(SearchAttributeUpdateError::InvalidKey(_))
24776        ));
24777        assert!(matches!(
24778            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24779            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24780        ));
24781        assert!(matches!(
24782            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24783            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24784        ));
24785        assert!(matches!(
24786            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24787            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24788        ));
24789        assert!(matches!(
24790            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24791            Err(Error::InvalidSearchAttributeUpdate(
24792                SearchAttributeUpdateError::Empty
24793            ))
24794        ));
24795    }
24796
24797    #[test]
24798    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24799        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24800        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24801
24802        assert!(SearchAttributeUpdate::new()
24803            .string("AsciiDescription", ascii)
24804            .is_ok());
24805        assert!(SearchAttributeUpdate::new()
24806            .string("Utf8Description", utf8)
24807            .is_ok());
24808        assert!(matches!(
24809            SearchAttributeUpdate::new().string(
24810                "TooLongDescription",
24811                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24812            ),
24813            Err(SearchAttributeUpdateError::ValueTooLong {
24814                kind: "string",
24815                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24816                ..
24817            })
24818        ));
24819    }
24820
24821    #[test]
24822    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24823        let lone_fire = WorkflowState::new(
24824            vec![history_event(
24825                "TimerFired",
24826                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24827            )],
24828            "rust-workers".to_string(),
24829            DEFAULT_CODEC.to_string(),
24830            None,
24831        )
24832        .expect_err("TimerFired requires TimerScheduled");
24833        assert!(matches!(
24834            lone_fire,
24835            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24836                if reason == "timer_schedule_missing_or_duplicate"
24837        ));
24838
24839        let wrong_identity = WorkflowState::new(
24840            vec![
24841                history_event(
24842                    "TimerScheduled",
24843                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24844                ),
24845                history_event(
24846                    "TimerFired",
24847                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24848                ),
24849            ],
24850            "rust-workers".to_string(),
24851            DEFAULT_CODEC.to_string(),
24852            None,
24853        )
24854        .expect_err("fire must match scheduled timer identity");
24855        assert!(matches!(
24856            wrong_identity,
24857            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24858                if reason == "timer_identity_mismatch"
24859        ));
24860
24861        let duplicate_fire = WorkflowState::new(
24862            vec![
24863                history_event(
24864                    "TimerScheduled",
24865                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24866                ),
24867                history_event(
24868                    "TimerFired",
24869                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24870                ),
24871                history_event(
24872                    "TimerFired",
24873                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24874                ),
24875            ],
24876            "rust-workers".to_string(),
24877            DEFAULT_CODEC.to_string(),
24878            None,
24879        )
24880        .expect_err("a durable timer cannot fire twice");
24881        assert!(matches!(
24882            duplicate_fire,
24883            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24884                if reason == "duplicate_timer_fire"
24885        ));
24886
24887        let wrong_fired_delay = WorkflowState::new(
24888            vec![
24889                history_event(
24890                    "TimerScheduled",
24891                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24892                ),
24893                history_event(
24894                    "TimerFired",
24895                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24896                ),
24897            ],
24898            "rust-workers".to_string(),
24899            DEFAULT_CODEC.to_string(),
24900            None,
24901        )
24902        .expect_err("timer schedule and fire delays must agree");
24903        assert!(matches!(
24904            wrong_fired_delay,
24905            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24906                if reason == "timer_history_delay_mismatch"
24907        ));
24908    }
24909
24910    #[test]
24911    fn replay_rejects_activity_moved_before_recorded_timer() {
24912        let ctx = workflow_context(vec![
24913            history_event(
24914                "TimerScheduled",
24915                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24916            ),
24917            history_event(
24918                "TimerFired",
24919                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24920            ),
24921            history_event(
24922                "ActivityCompleted",
24923                json!({
24924                    "sequence": 2,
24925                    "activity_type": "after-timer",
24926                    "payload_codec": DEFAULT_CODEC,
24927                    "result": fixture_envelope(json!("done")),
24928                }),
24929            ),
24930        ]);
24931        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24932        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24933
24934        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24935            activity.as_mut().poll(&mut task_context)
24936        else {
24937            panic!("reordered durable command must be rejected");
24938        };
24939        assert_eq!(failure.reason, "recorded_command_mismatch");
24940        assert_eq!(failure.sequence, Some(1));
24941        assert_eq!(failure.expected.as_deref(), Some("timer"));
24942        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24943    }
24944
24945    #[test]
24946    fn workflow_context_emits_a_typed_named_signal_wait() {
24947        let ctx = workflow_context(Vec::new());
24948        let mut signal = Box::pin(ctx.wait_signal("finish"));
24949        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24950
24951        assert!(matches!(
24952            signal.as_mut().poll(&mut task_context),
24953            Poll::Pending
24954        ));
24955        assert_eq!(
24956            ctx.take_commands().expect("signal-wait command"),
24957            vec![json!({
24958                "type": "open_signal_wait",
24959                "signal_name": "finish",
24960            })]
24961        );
24962    }
24963
24964    #[test]
24965    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
24966        let ctx = workflow_context(Vec::new());
24967        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
24968        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24969
24970        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
24971        else {
24972            panic!("runtime-reserved signal should be rejected");
24973        };
24974        assert!(message.contains("reserved by the workflow runtime"));
24975        assert!(ctx.take_commands().expect("commands").is_empty());
24976    }
24977
24978    #[tokio::test]
24979    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
24980        let client = Client::builder("http://127.0.0.1:9")
24981            .build()
24982            .expect("client");
24983        let error = client
24984            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
24985            .await
24986            .expect_err("runtime-reserved signal should be rejected before transport");
24987
24988        assert!(
24989            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
24990        );
24991    }
24992
24993    #[test]
24994    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
24995        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24996            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24997                value.to_string(),
24998            )]))
24999            .expect("message payload");
25000            json!({
25001                "schema": MESSAGE_STREAM_SCHEMA,
25002                "stream_name": "orders",
25003                "message_id": message_id,
25004                "position": position,
25005                "payload_envelope": payload,
25006            })
25007        }
25008
25009        fn opened(sequence: u64) -> HistoryEvent {
25010            history_event(
25011                "SignalWaitOpened",
25012                json!({
25013                    "sequence": sequence,
25014                    "signal_name": MESSAGE_STREAM_SIGNAL,
25015                }),
25016            )
25017        }
25018
25019        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25020            history_event(
25021                "SignalApplied",
25022                json!({
25023                    "sequence": sequence,
25024                    "signal_name": MESSAGE_STREAM_SIGNAL,
25025                    "value": fixture_envelope(json!([delivery])),
25026                }),
25027            )
25028        }
25029
25030        fn received(delivery: Value) -> HistoryEvent {
25031            history_event(
25032                "SignalReceived",
25033                json!({
25034                    "signal_name": MESSAGE_STREAM_SIGNAL,
25035                    "arguments": fixture_envelope(json!([delivery])),
25036                    "payload_codec": DEFAULT_CODEC,
25037                }),
25038            )
25039        }
25040
25041        let client = Client::new("http://127.0.0.1:8080").expect("client");
25042        let mut worker = Worker::new(client, "rust-workers");
25043        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
25044            let messages = ctx.message_stream("orders")?.receive(2).await?;
25045            Ok(json!(messages
25046                .into_iter()
25047                .map(|message| message.message_id)
25048                .collect::<Vec<_>>()))
25049        });
25050
25051        let first = delivery("message-1", 1, "one");
25052        let second = delivery("message-2", 2, "two");
25053        let batch = worker
25054            .execute_workflow_task_decision(workflow_task(
25055                "rust.message-stream-batch",
25056                vec![
25057                    opened(1),
25058                    received(first.clone()),
25059                    applied(1, first.clone()),
25060                    received(first.clone()),
25061                    received(second),
25062                ],
25063                DEFAULT_CODEC,
25064            ))
25065            .expect("worker task consumes the available batch");
25066
25067        assert_eq!(batch.commands.len(), 1);
25068        assert_eq!(batch.commands[0]["type"], "complete_workflow");
25069        assert_eq!(
25070            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
25071                .expect("workflow result"),
25072            json!(["message-1", "message-2"])
25073        );
25074        assert_eq!(
25075            batch.message_stream_cursors,
25076            vec![json!({"stream_name": "orders", "through_position": 2})]
25077        );
25078        assert!(batch.message_stream_waits.is_empty());
25079
25080        let partial = worker
25081            .execute_workflow_task_decision(workflow_task(
25082                "rust.message-stream-batch",
25083                vec![opened(1), received(first.clone()), applied(1, first)],
25084                DEFAULT_CODEC,
25085            ))
25086            .expect("worker task returns without waiting for a missing second item");
25087        assert_eq!(partial.commands.len(), 1);
25088        assert_eq!(partial.commands[0]["type"], "complete_workflow");
25089        assert_eq!(
25090            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
25091                .expect("workflow result"),
25092            json!(["message-1"])
25093        );
25094        assert_eq!(
25095            partial.message_stream_cursors,
25096            vec![json!({"stream_name": "orders", "through_position": 1})]
25097        );
25098        assert!(partial.message_stream_waits.is_empty());
25099    }
25100
25101    #[test]
25102    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
25103        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25104            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25105                value.to_string(),
25106            )]))
25107            .expect("message payload");
25108            json!({
25109                "schema": MESSAGE_STREAM_SCHEMA,
25110                "stream_name": "orders",
25111                "message_id": message_id,
25112                "position": position,
25113                "payload_envelope": payload,
25114            })
25115        }
25116
25117        fn opened(sequence: u64) -> HistoryEvent {
25118            history_event(
25119                "SignalWaitOpened",
25120                json!({
25121                    "sequence": sequence,
25122                    "signal_name": MESSAGE_STREAM_SIGNAL,
25123                }),
25124            )
25125        }
25126
25127        fn received(delivery: Value) -> HistoryEvent {
25128            history_event(
25129                "SignalReceived",
25130                json!({
25131                    "signal_name": MESSAGE_STREAM_SIGNAL,
25132                    "arguments": fixture_envelope(json!([delivery])),
25133                    "payload_codec": DEFAULT_CODEC,
25134                }),
25135            )
25136        }
25137
25138        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25139            history_event(
25140                "SignalApplied",
25141                json!({
25142                    "sequence": sequence,
25143                    "signal_name": MESSAGE_STREAM_SIGNAL,
25144                    "value": fixture_envelope(json!([delivery])),
25145                }),
25146            )
25147        }
25148
25149        let client = Client::new("http://127.0.0.1:8080").expect("client");
25150        let mut worker = Worker::new(client, "rust-workers");
25151        worker.register_workflow(
25152            "rust.message-stream-partial-batches",
25153            |ctx, _input| async move {
25154                let stream = ctx.message_stream("orders")?;
25155                let first = stream.receive(10).await?;
25156                let second = stream.receive(10).await?;
25157                Ok(json!([
25158                    first
25159                        .into_iter()
25160                        .map(|message| message.message_id)
25161                        .collect::<Vec<_>>(),
25162                    second
25163                        .into_iter()
25164                        .map(|message| message.message_id)
25165                        .collect::<Vec<_>>(),
25166                ]))
25167            },
25168        );
25169
25170        let first = delivery("message-1", 1, "one");
25171        let second = delivery("message-2", 2, "two");
25172        let decision = worker
25173            .execute_workflow_task_decision(workflow_task(
25174                "rust.message-stream-partial-batches",
25175                vec![
25176                    opened(1),
25177                    received(first.clone()),
25178                    applied(1, first),
25179                    opened(2),
25180                    received(second.clone()),
25181                    applied(2, second),
25182                ],
25183                DEFAULT_CODEC,
25184            ))
25185            .expect("cold replay preserves both authored receive boundaries");
25186
25187        assert_eq!(decision.commands.len(), 1);
25188        assert_eq!(decision.commands[0]["type"], "complete_workflow");
25189        assert_eq!(
25190            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
25191                .expect("workflow result"),
25192            json!([["message-1"], ["message-2"]])
25193        );
25194        assert_eq!(
25195            decision.message_stream_cursors,
25196            vec![json!({"stream_name": "orders", "through_position": 2})]
25197        );
25198        assert!(decision.message_stream_waits.is_empty());
25199    }
25200
25201    #[test]
25202    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
25203        let ctx = workflow_context(Vec::new());
25204        let stream = ctx.message_stream("orders").expect("message stream");
25205        let mut receive = Box::pin(stream.receive(10));
25206        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25207
25208        assert!(matches!(
25209            receive.as_mut().poll(&mut task_context),
25210            Poll::Pending
25211        ));
25212        assert_eq!(
25213            ctx.take_commands().expect("message-stream wait command"),
25214            vec![json!({
25215                "type": "open_signal_wait",
25216                "signal_name": MESSAGE_STREAM_SIGNAL,
25217            })]
25218        );
25219        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25220        assert!(cursors.is_empty());
25221        assert_eq!(
25222            waits,
25223            vec![json!({"stream_name": "orders", "after_position": 0})]
25224        );
25225    }
25226
25227    #[test]
25228    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
25229        let ctx = workflow_context(vec![history_event(
25230            "SignalReceived",
25231            json!({
25232                "signal_name": MESSAGE_STREAM_SIGNAL,
25233                "arguments": fixture_envelope(json!([{
25234                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
25235                    "stream_name": "orders",
25236                    "through_position": 2,
25237                }])),
25238                "payload_codec": DEFAULT_CODEC,
25239            }),
25240        )]);
25241        let stream = ctx.message_stream("orders").expect("message stream");
25242        let mut receive = Box::pin(stream.receive(10));
25243        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25244
25245        assert!(matches!(
25246            receive.as_mut().poll(&mut task_context),
25247            Poll::Pending
25248        ));
25249        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25250        assert_eq!(
25251            cursors,
25252            vec![json!({"stream_name": "orders", "through_position": 2})]
25253        );
25254        assert_eq!(
25255            waits,
25256            vec![json!({"stream_name": "orders", "after_position": 2})]
25257        );
25258    }
25259
25260    #[test]
25261    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
25262        let mut empty_map = BTreeMap::new();
25263        let mut nested = BTreeMap::new();
25264        nested.insert(
25265            "value".to_string(),
25266            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
25267        );
25268        let values = vec![
25269            AvroValue::Bytes(vec![0, 255]),
25270            AvroValue::Long(1),
25271            AvroValue::Double(1.0),
25272            AvroValue::Array(Vec::new()),
25273            AvroValue::Map(std::mem::take(&mut empty_map)),
25274            AvroValue::Map(nested),
25275        ];
25276        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
25277        let transport = vec![json!({
25278            "schema": MESSAGE_STREAM_SCHEMA,
25279            "stream_name": "orders",
25280            "message_id": "message-1",
25281            "position": 1,
25282            "payload_envelope": payload,
25283        })];
25284
25285        for _ in 0..2 {
25286            let Some(MessageStreamDelivery::Message(message)) =
25287                decode_message_stream_delivery(transport.clone()).expect("delivery")
25288            else {
25289                panic!("message delivery expected");
25290            };
25291            assert_eq!(message.arguments, values);
25292            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
25293            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
25294        }
25295    }
25296
25297    #[test]
25298    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
25299        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25300            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25301                value.to_string(),
25302            )]))
25303            .expect("message payload");
25304            json!({
25305                "schema": MESSAGE_STREAM_SCHEMA,
25306                "stream_name": "orders",
25307                "message_id": message_id,
25308                "position": position,
25309                "payload_envelope": payload,
25310            })
25311        }
25312
25313        fn opened(sequence: u64) -> HistoryEvent {
25314            history_event(
25315                "SignalWaitOpened",
25316                json!({
25317                    "sequence": sequence,
25318                    "signal_name": MESSAGE_STREAM_SIGNAL,
25319                }),
25320            )
25321        }
25322
25323        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25324            history_event(
25325                "SignalApplied",
25326                json!({
25327                    "sequence": sequence,
25328                    "signal_name": MESSAGE_STREAM_SIGNAL,
25329                    "value": fixture_envelope(json!([delivery])),
25330                }),
25331            )
25332        }
25333
25334        fn worker() -> Worker {
25335            let client = Client::new("http://127.0.0.1:8080").expect("client");
25336            let mut worker = Worker::new(client, "rust-workers");
25337            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
25338                let stream = ctx.message_stream("orders")?;
25339                let first = stream.receive_one().await?;
25340                let second = stream.receive_one().await?;
25341                Ok(json!([first.message_id, second.message_id]))
25342            });
25343            worker
25344        }
25345
25346        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
25347            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
25348            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
25349            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
25350            task
25351        }
25352
25353        let waiting = worker()
25354            .execute_workflow_task_decision(workflow_task(
25355                "rust.message-stream",
25356                Vec::new(),
25357                DEFAULT_CODEC,
25358            ))
25359            .expect("first worker opens the stream wait");
25360        assert_eq!(
25361            waiting.commands,
25362            vec![json!({
25363                "type": "open_signal_wait",
25364                "signal_name": MESSAGE_STREAM_SIGNAL,
25365            })]
25366        );
25367        assert!(waiting.message_stream_cursors.is_empty());
25368        assert_eq!(
25369            waiting.message_stream_waits,
25370            vec![json!({"stream_name": "orders", "after_position": 0})]
25371        );
25372
25373        let first_delivery = delivery("message-1", 1, "one");
25374        let first_arrival = worker()
25375            .execute_workflow_task_decision(task_with_resume(
25376                vec![opened(1)],
25377                first_delivery.clone(),
25378            ))
25379            .expect("replacement worker consumes the first arrival");
25380        assert_eq!(
25381            first_arrival.commands,
25382            vec![json!({
25383                "type": "open_signal_wait",
25384                "signal_name": MESSAGE_STREAM_SIGNAL,
25385            })]
25386        );
25387        assert_eq!(
25388            first_arrival.message_stream_cursors,
25389            vec![json!({"stream_name": "orders", "through_position": 1})]
25390        );
25391        assert_eq!(
25392            first_arrival.message_stream_waits,
25393            vec![json!({"stream_name": "orders", "after_position": 1})]
25394        );
25395
25396        let second_delivery = delivery("message-2", 2, "two");
25397        let first_applied = applied(1, first_delivery);
25398        let completed = worker()
25399            .execute_workflow_task_decision(task_with_resume(
25400                vec![opened(1), first_applied.clone(), opened(2)],
25401                second_delivery.clone(),
25402            ))
25403            .expect("next replacement worker consumes the second arrival");
25404        assert_eq!(completed.commands.len(), 1);
25405        assert_eq!(completed.commands[0]["type"], "complete_workflow");
25406        assert_eq!(
25407            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
25408                .expect("workflow result"),
25409            json!(["message-1", "message-2"])
25410        );
25411        assert_eq!(
25412            completed.message_stream_cursors,
25413            vec![json!({"stream_name": "orders", "through_position": 2})]
25414        );
25415        assert!(completed.message_stream_waits.is_empty());
25416
25417        let replay_history = vec![
25418            opened(1),
25419            first_applied,
25420            opened(2),
25421            applied(2, second_delivery),
25422        ];
25423        for _cold_worker_or_restart in 0..2 {
25424            let replayed = worker()
25425                .execute_workflow_task_decision(workflow_task(
25426                    "rust.message-stream",
25427                    replay_history.clone(),
25428                    DEFAULT_CODEC,
25429                ))
25430                .expect("cold worker replays each logical message exactly once");
25431            assert_eq!(replayed.commands.len(), 1);
25432            assert_eq!(
25433                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
25434                    .expect("replayed workflow result"),
25435                json!(["message-1", "message-2"])
25436            );
25437            assert_eq!(
25438                replayed.message_stream_cursors,
25439                vec![json!({"stream_name": "orders", "through_position": 2})]
25440            );
25441            assert!(replayed.message_stream_waits.is_empty());
25442        }
25443    }
25444
25445    #[test]
25446    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
25447        assert!(!worker_protocol_supports_message_streams("1.14"));
25448        assert!(worker_protocol_supports_message_streams("1.15"));
25449        assert!(worker_protocol_supports_message_streams("1.16"));
25450        assert!(worker_protocol_supports_message_streams(
25451            WORKER_PROTOCOL_VERSION
25452        ));
25453        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
25454    }
25455
25456    #[test]
25457    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
25458        let ctx = workflow_context(vec![
25459            history_event(
25460                "ConditionWaitOpened",
25461                json!({
25462                    "sequence": 1,
25463                    "condition_wait_id": "condition:1",
25464                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25465                    "condition_key": "signal:finish",
25466                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25467                }),
25468            ),
25469            history_event(
25470                "ConditionWaitSatisfied",
25471                json!({
25472                    "sequence": 1,
25473                    "condition_wait_id": "condition:1",
25474                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25475                    "condition_key": "signal:finish",
25476                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25477                }),
25478            ),
25479            history_event(
25480                "SignalReceived",
25481                json!({"signal_name": "finish", "arguments": []}),
25482            ),
25483        ]);
25484        let mut signal = Box::pin(ctx.wait_signal("finish"));
25485        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25486
25487        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25488            signal.as_mut().poll(&mut task_context)
25489        else {
25490            panic!("condition history must not resolve as a typed signal wait");
25491        };
25492        assert_eq!(failure.reason, "recorded_command_mismatch");
25493        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
25494    }
25495
25496    #[test]
25497    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
25498        let signal_then_timer = vec![
25499            history_event(
25500                "SignalWaitOpened",
25501                json!({"sequence": 1, "signal_name": "go"}),
25502            ),
25503            history_event(
25504                "SignalApplied",
25505                json!({
25506                    "sequence": 1,
25507                    "signal_name": "go",
25508                    "value": fixture_envelope(json!(["now"])),
25509                }),
25510            ),
25511            history_event(
25512                "TimerScheduled",
25513                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25514            ),
25515            history_event(
25516                "TimerFired",
25517                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25518            ),
25519        ];
25520
25521        let ctx = workflow_context(signal_then_timer.clone());
25522        let mut signal = Box::pin(ctx.wait_signal("go"));
25523        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25524        assert!(matches!(
25525            signal.as_mut().poll(&mut task_context),
25526            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
25527        ));
25528        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
25529        assert!(matches!(
25530            timer.as_mut().poll(&mut task_context),
25531            Poll::Ready(Ok(()))
25532        ));
25533        ctx.ensure_history_consumed()
25534            .expect("signal and timer history consumed in order");
25535
25536        let reordered = workflow_context(signal_then_timer);
25537        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
25538        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25539            timer_first.as_mut().poll(&mut task_context)
25540        else {
25541            panic!("timer cannot consume signal-wait-first history");
25542        };
25543        assert_eq!(failure.reason, "recorded_command_mismatch");
25544        assert_eq!(failure.sequence, Some(1));
25545        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
25546
25547        let timer_then_signal = vec![
25548            history_event(
25549                "TimerScheduled",
25550                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25551            ),
25552            history_event(
25553                "TimerFired",
25554                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25555            ),
25556            history_event(
25557                "SignalWaitOpened",
25558                json!({"sequence": 2, "signal_name": "go"}),
25559            ),
25560            history_event(
25561                "SignalApplied",
25562                json!({
25563                    "sequence": 2,
25564                    "signal_name": "go",
25565                    "value": fixture_envelope(json!([])),
25566                }),
25567            ),
25568        ];
25569        let reordered = workflow_context(timer_then_signal);
25570        let mut signal_first = Box::pin(reordered.wait_signal("go"));
25571        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25572            signal_first.as_mut().poll(&mut task_context)
25573        else {
25574            panic!("signal wait cannot consume timer-first history");
25575        };
25576        assert_eq!(failure.reason, "recorded_command_mismatch");
25577        assert_eq!(failure.sequence, Some(1));
25578        assert_eq!(failure.expected.as_deref(), Some("timer"));
25579    }
25580
25581    #[test]
25582    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
25583        let duplicate_timer = WorkflowState::new(
25584            vec![
25585                history_event(
25586                    "TimerScheduled",
25587                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25588                ),
25589                history_event(
25590                    "TimerScheduled",
25591                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
25592                ),
25593            ],
25594            "rust-workers".to_string(),
25595            DEFAULT_CODEC.to_string(),
25596            None,
25597        )
25598        .expect_err("one workflow sequence cannot schedule two timers");
25599        assert!(matches!(
25600            duplicate_timer,
25601            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25602                if reason == "timer_schedule_missing_or_duplicate"
25603        ));
25604
25605        let colliding_kinds = WorkflowState::new(
25606            vec![
25607                history_event(
25608                    "TimerScheduled",
25609                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25610                ),
25611                history_event(
25612                    "ActivityCompleted",
25613                    json!({"sequence": 1, "activity_type": "same-sequence"}),
25614                ),
25615            ],
25616            "rust-workers".to_string(),
25617            DEFAULT_CODEC.to_string(),
25618            None,
25619        )
25620        .expect_err("one workflow sequence cannot identify two command kinds");
25621        assert!(matches!(
25622            colliding_kinds,
25623            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25624                if reason == "durable_command_sequence_collision"
25625        ));
25626
25627        let duplicate_signal_wait = WorkflowState::new(
25628            vec![
25629                history_event(
25630                    "SignalWaitOpened",
25631                    json!({"sequence": 1, "signal_name": "go"}),
25632                ),
25633                history_event(
25634                    "SignalWaitOpened",
25635                    json!({"sequence": 1, "signal_name": "go"}),
25636                ),
25637            ],
25638            "rust-workers".to_string(),
25639            DEFAULT_CODEC.to_string(),
25640            None,
25641        )
25642        .expect_err("one workflow sequence cannot open two signal waits");
25643        assert!(matches!(
25644            duplicate_signal_wait,
25645            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25646                if reason == "signal_wait_open_missing_or_duplicate"
25647        ));
25648    }
25649
25650    #[test]
25651    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25652        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25653            .expect("side-effect result");
25654        let ctx = workflow_context(vec![history_event(
25655            "SideEffectRecorded",
25656            json!({"sequence": 99, "result": result}),
25657        )]);
25658
25659        let replayed: Value = ctx
25660            .side_effect(|| panic!("recorded side effect must not run"))
25661            .expect("positive global workflow sequence is valid");
25662        assert_eq!(replayed, json!({"captured": true}));
25663        ctx.ensure_history_consumed().expect("history consumed");
25664    }
25665
25666    #[test]
25667    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25668        let result =
25669            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25670        let zero = WorkflowState::new(
25671            vec![history_event(
25672                "SideEffectRecorded",
25673                json!({"sequence": 0, "result": result.clone()}),
25674            )],
25675            "rust-workers".to_string(),
25676            DEFAULT_CODEC.to_string(),
25677            None,
25678        )
25679        .expect_err("durable command sequences must be positive");
25680        assert!(matches!(
25681            zero,
25682            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25683                if reason == "durable_command_sequence_invalid"
25684        ));
25685
25686        let descending = WorkflowState::new(
25687            vec![
25688                history_event(
25689                    "SideEffectRecorded",
25690                    json!({"sequence": 3, "result": result}),
25691                ),
25692                history_event(
25693                    "VersionMarkerRecorded",
25694                    json!({
25695                        "sequence": 2,
25696                        "change_id": "descending-marker",
25697                        "version": 1,
25698                        "min_supported": 1,
25699                        "max_supported": 1,
25700                    }),
25701                ),
25702            ],
25703            "rust-workers".to_string(),
25704            DEFAULT_CODEC.to_string(),
25705            None,
25706        )
25707        .expect_err("new durable commands must remain strictly ordered");
25708        let Error::NonDeterministicReplay(failure) = descending else {
25709            panic!("expected typed replay failure");
25710        };
25711        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25712        assert_eq!(failure.sequence, Some(2));
25713        assert_eq!(
25714            failure.expected.as_deref(),
25715            Some("workflow sequence greater than 3")
25716        );
25717        assert_eq!(failure.actual.as_deref(), Some("2"));
25718    }
25719
25720    #[test]
25721    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25722        fn worker() -> Worker {
25723            let client = Client::new("http://127.0.0.1:8080").expect("client");
25724            let mut worker = Worker::new(client, "rust-workers");
25725            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25726                ctx.wait_signal("finish").await?;
25727                let marker: String =
25728                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25729                assert_eq!(marker, "after-finish");
25730                Ok(json!("finished"))
25731            });
25732            worker
25733        }
25734
25735        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25736            .expect("side-effect result");
25737        let task = workflow_task(
25738            "rust.finish-after-gaps",
25739            vec![
25740                history_event(
25741                    "SignalWaitOpened",
25742                    json!({"sequence": 1, "signal_name": "finish"}),
25743                ),
25744                history_event(
25745                    "SignalReceived",
25746                    json!({
25747                        "signal_id": "increment-3",
25748                        "signal_name": "increment",
25749                        "workflow_sequence": 2,
25750                        "payload_codec": DEFAULT_CODEC,
25751                        "arguments": fixture_envelope(json!([3])),
25752                    }),
25753                ),
25754                history_event(
25755                    "SignalReceived",
25756                    json!({
25757                        "signal_id": "increment-5",
25758                        "signal_name": "increment",
25759                        "workflow_sequence": 3,
25760                        "payload_codec": DEFAULT_CODEC,
25761                        "arguments": fixture_envelope(json!([5])),
25762                    }),
25763                ),
25764                history_event(
25765                    "SignalReceived",
25766                    json!({
25767                        "signal_id": "finish",
25768                        "signal_name": "finish",
25769                        "workflow_sequence": 4,
25770                        "payload_codec": DEFAULT_CODEC,
25771                        "arguments": fixture_envelope(json!([])),
25772                    }),
25773                ),
25774                history_event(
25775                    "SignalApplied",
25776                    json!({
25777                        "sequence": 1,
25778                        "signal_id": "finish",
25779                        "signal_name": "finish",
25780                        "payload_codec": DEFAULT_CODEC,
25781                        "value": fixture_envelope(json!([])),
25782                    }),
25783                ),
25784                history_event(
25785                    "SideEffectRecorded",
25786                    json!({"sequence": 5, "result": marker}),
25787                ),
25788            ],
25789            DEFAULT_CODEC,
25790        );
25791
25792        for _original_or_cold_worker in 0..2 {
25793            let commands = worker()
25794                .execute_workflow_task(task.clone())
25795                .expect("signal gaps preserve deterministic replay");
25796            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25797            assert_eq!(commands[0]["type"], "complete_workflow");
25798            assert_eq!(
25799                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25800                json!("finished")
25801            );
25802        }
25803    }
25804
25805    #[test]
25806    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25807        let ctx = workflow_context(Vec::new());
25808        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25809        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25810        assert!(matches!(
25811            sleep.as_mut().poll(&mut task_context),
25812            Poll::Ready(Err(Error::TimerDurationOverflow))
25813        ));
25814        assert!(ctx.take_commands().expect("commands").is_empty());
25815    }
25816
25817    #[test]
25818    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25819        let entries = AvroValue::Map(BTreeMap::from([
25820            ("text".to_string(), AvroValue::String("same".to_string())),
25821            (
25822                "nested".to_string(),
25823                AvroValue::Map(BTreeMap::from([
25824                    ("beta".to_string(), AvroValue::Long(2)),
25825                    ("alpha".to_string(), AvroValue::Long(1)),
25826                ])),
25827            ),
25828            ("long".to_string(), AvroValue::Long(7)),
25829            ("double".to_string(), AvroValue::Double(7.0)),
25830            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25831        ]));
25832        let ctx = workflow_context(Vec::new());
25833        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25834        let commands = ctx.take_commands().expect("commands");
25835
25836        assert_eq!(commands.len(), 1);
25837        assert_eq!(commands[0]["type"], "upsert_memo");
25838        let server_entries = json!({
25839            "codec": "avro",
25840            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25841        });
25842        assert_eq!(
25843            commands[0]["entries"]
25844                .as_object()
25845                .expect("entries envelope")
25846                .keys()
25847                .collect::<Vec<_>>(),
25848            vec!["blob", "codec"]
25849        );
25850        assert_eq!(commands[0]["entries"], server_entries);
25851        let wire_entries =
25852            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25853        assert_eq!(wire_entries, entries);
25854
25855        let history = vec![history_event(
25856            "MemoUpserted",
25857            json!({
25858                "sequence": 1,
25859                "entries": server_entries.clone(),
25860                "merged": server_entries,
25861            }),
25862        )];
25863        let replay = workflow_context(history.clone());
25864        replay
25865            .upsert_memo(entries.clone())
25866            .expect("matching replay identity");
25867        assert!(replay.take_commands().expect("replay commands").is_empty());
25868
25869        let changed_types = AvroValue::Map(BTreeMap::from([
25870            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25871            (
25872                "nested".to_string(),
25873                AvroValue::Map(BTreeMap::from([
25874                    ("alpha".to_string(), AvroValue::Long(1)),
25875                    ("beta".to_string(), AvroValue::Long(2)),
25876                ])),
25877            ),
25878            ("long".to_string(), AvroValue::Double(7.0)),
25879            ("double".to_string(), AvroValue::Long(7)),
25880            ("binary".to_string(), AvroValue::String("same".to_string())),
25881        ]));
25882        let error = workflow_context(history)
25883            .upsert_memo(changed_types)
25884            .expect_err("memo replay identity must preserve Avro value types");
25885        assert!(matches!(
25886            error,
25887            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25888        ));
25889    }
25890
25891    #[test]
25892    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25893        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25894            .expect("memo envelope");
25895        let replay = workflow_context(vec![history_event(
25896            "MemoUpserted",
25897            json!({
25898                "sequence": 1,
25899                "entries": original.clone(),
25900                "merged": original
25901            }),
25902        )]);
25903        let error = replay
25904            .upsert_memo(json!({"stage": "changed"}))
25905            .expect_err("changed memo update must fail replay");
25906        assert!(matches!(
25907            error,
25908            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25909        ));
25910
25911        let invalid = workflow_context(Vec::new())
25912            .upsert_memo(
25913                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25914            )
25915            .expect_err("oversized key");
25916        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25917    }
25918
25919    #[test]
25920    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25921        let negative_zero = AvroValue::Map(BTreeMap::from([(
25922            "reading".to_string(),
25923            AvroValue::Double(-0.0),
25924        )]));
25925        let negative_zero_envelope =
25926            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25927        let history = vec![history_event(
25928            "MemoUpserted",
25929            json!({
25930                "sequence": 1,
25931                "entries": negative_zero_envelope.clone(),
25932                "merged": negative_zero_envelope,
25933            }),
25934        )];
25935
25936        workflow_context(history.clone())
25937            .upsert_memo(negative_zero)
25938            .expect("matching negative-zero history identity");
25939
25940        let error = workflow_context(history)
25941            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25942                "reading".to_string(),
25943                AvroValue::Double(0.0),
25944            )])))
25945            .expect_err("positive zero must not consume negative-zero memo history");
25946        assert!(matches!(
25947            error,
25948            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25949        ));
25950    }
25951
25952    #[test]
25953    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
25954        let supported = json!({
25955            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
25956            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
25957        });
25958        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
25959        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
25960            "workflow_memo_updates": {"supported": false},
25961            "supported_workflow_task_commands": ["upsert_memo"]
25962        }))));
25963        assert!(commands_use_workflow_memo_updates(&[json!({
25964            "type": "upsert_memo",
25965            "entries": {"stage": "processing"}
25966        })]));
25967    }
25968
25969    #[test]
25970    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
25971        let client = Client::new("http://127.0.0.1:8080").expect("client");
25972        let mut worker = Worker::new(client, "rust-workers");
25973        worker.register_workflow("rust.timer", |ctx, _input| async move {
25974            ctx.sleep(Duration::from_secs(5)).await?;
25975            ctx.activity("after-timer", json!([])).await
25976        });
25977
25978        let task = |history_events| WorkflowTask {
25979            task_id: "wft-rust-timer-1".to_string(),
25980            observability_context: None,
25981            dispatch_observability_context: None,
25982            observability_links: None,
25983            workflow_command_id: None,
25984            workflow_id: Some("wf-rust-timer".to_string()),
25985            run_id: Some("run-rust-timer".to_string()),
25986            workflow_type: "rust.timer".to_string(),
25987            cancel_requested: false,
25988            payload_codec: DEFAULT_CODEC.to_string(),
25989            arguments: Some(
25990                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25991            ),
25992            history_events,
25993            total_history_events: None,
25994            history_size_bytes: None,
25995            continue_as_new_recommended: None,
25996            history_budget_pressure: None,
25997            next_history_page_token: None,
25998            workflow_task_attempt: 1,
25999            workflow_signal_id: None,
26000            signal_name: None,
26001            signal_arguments: None,
26002            workflow_update_id: None,
26003            update_name: None,
26004            lease_owner: Some("rust-worker".to_string()),
26005        };
26006
26007        let initial = worker
26008            .execute_workflow_task(task(Vec::new()))
26009            .expect("initial timer task");
26010        assert_eq!(
26011            initial,
26012            vec![json!({"type": "start_timer", "delay_seconds": 5})]
26013        );
26014
26015        let activity_result =
26016            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
26017        let replayed = worker
26018            .execute_workflow_task(task(vec![
26019                history_event(
26020                    "TimerScheduled",
26021                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26022                ),
26023                history_event(
26024                    "TimerFired",
26025                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26026                ),
26027                history_event(
26028                    "ActivityCompleted",
26029                    json!({
26030                        "sequence": 2,
26031                        "activity_type": "after-timer",
26032                        "payload_codec": DEFAULT_CODEC,
26033                        "result": activity_result,
26034                    }),
26035                ),
26036            ]))
26037            .expect("replayed workflow task");
26038        assert_eq!(replayed.len(), 1);
26039        assert_eq!(replayed[0]["type"], "complete_workflow");
26040        assert_eq!(
26041            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
26042            json!("done")
26043        );
26044    }
26045
26046    #[test]
26047    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
26048        let client = Client::new("http://127.0.0.1:8080").expect("client");
26049        let mut worker = Worker::new(client, "rust-workers");
26050        worker.register_workflow("rust.continue", |ctx, _input| async move {
26051            ctx.continue_as_new_with_options(
26052                ContinueAsNewOptions::new()
26053                    .workflow_type("rust.next")
26054                    .task_queue("next-workers"),
26055                json!([2, {"cursor": "next"}]),
26056            )
26057        });
26058
26059        let commands = worker
26060            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
26061            .expect("continue-as-new command");
26062
26063        assert_eq!(commands.len(), 1);
26064        assert_eq!(commands[0]["type"], "continue_as_new");
26065        assert_eq!(commands[0]["workflow_type"], "rust.next");
26066        assert_eq!(commands[0]["queue"], "next-workers");
26067        assert_eq!(
26068            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
26069                .expect("continue-as-new arguments"),
26070            json!([2, {"cursor": "next"}])
26071        );
26072    }
26073
26074    #[test]
26075    fn continue_as_new_preserves_typed_arguments() {
26076        let client = Client::new("http://127.0.0.1:8080").expect("client");
26077        let mut worker = Worker::new(client, "rust-workers");
26078        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
26079            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
26080            unreachable!("continue-as-new returns a control-flow error")
26081        });
26082
26083        let commands = worker
26084            .execute_workflow_task(workflow_task(
26085                "rust.typed-continue",
26086                Vec::new(),
26087                DEFAULT_CODEC,
26088            ))
26089            .expect("typed continue-as-new command");
26090
26091        assert_eq!(commands[0]["type"], "continue_as_new");
26092        assert_eq!(
26093            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
26094                .expect("typed continue arguments"),
26095            AvroValue::Array(vec![typed_fidelity_probe()])
26096        );
26097    }
26098
26099    #[test]
26100    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
26101        let client = Client::new("http://127.0.0.1:8080").expect("client");
26102        let mut worker = Worker::new(client, "rust-workers");
26103        worker.register_workflow("rust.continue", |ctx, _input| async move {
26104            ctx.continue_as_new(json!([2]))
26105        });
26106        let task = workflow_task(
26107            "rust.continue",
26108            vec![history_event(
26109                "WorkflowContinuedAsNew",
26110                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
26111            )],
26112            DEFAULT_CODEC,
26113        );
26114
26115        for _worker_restart_or_redelivery in 0..2 {
26116            let commands = worker
26117                .execute_workflow_task(task.clone())
26118                .expect("recorded transition replays");
26119            assert!(
26120                commands.is_empty(),
26121                "replay must not emit another successor"
26122            );
26123        }
26124    }
26125
26126    #[test]
26127    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
26128        let ctx = workflow_context(Vec::new());
26129        let error = ctx
26130            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
26131            .expect_err("blank queue must be rejected");
26132
26133        let Error::InvalidContinueAsNewOptions(error) = error else {
26134            panic!("expected typed continue-as-new validation error");
26135        };
26136        assert_eq!(error.field, "task_queue");
26137        assert!(ctx.take_commands().expect("commands").is_empty());
26138    }
26139
26140    #[test]
26141    fn workflow_context_exposes_server_history_budget() {
26142        let client = Client::new("http://127.0.0.1:8080").expect("client");
26143        let mut worker = Worker::new(client, "rust-workers");
26144        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
26145            let budget = ctx.history_budget()?;
26146            Ok(json!({
26147                "events": budget.event_count,
26148                "bytes": budget.size_bytes,
26149                "recommended": budget.continue_as_new_recommended,
26150                "pressure": budget.pressure,
26151            }))
26152        });
26153        let task: WorkflowTask = serde_json::from_value(json!({
26154            "task_id": "task-history-budget",
26155            "workflow_type": "rust.history-budget",
26156            "payload_codec": DEFAULT_CODEC,
26157            "history_events": [],
26158            "total_history_events": 480,
26159            "history_size_bytes": 1_048_576,
26160            "continue_as_new_recommended": true,
26161            "history_budget_pressure": "continue_as_new_recommended",
26162        }))
26163        .expect("published workflow task");
26164
26165        let commands = worker
26166            .execute_workflow_task(task)
26167            .expect("history-budget workflow");
26168        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
26169        assert_eq!(result["events"], 480);
26170        assert_eq!(result["bytes"], 1_048_576);
26171        assert_eq!(result["recommended"], true);
26172        assert_eq!(result["pressure"], "continue_as_new_recommended");
26173    }
26174
26175    #[test]
26176    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
26177        let client = Client::new("http://127.0.0.1:8080").expect("client");
26178        let mut worker = Worker::new(client, "rust-workers");
26179        worker.register_workflow("rust.failing", |_ctx, _input| async move {
26180            Err(Error::Codec("rust_conformance_failure".to_string()))
26181        });
26182        let task = WorkflowTask {
26183            task_id: "wft-rust-failing-1".to_string(),
26184            observability_context: None,
26185            dispatch_observability_context: None,
26186            observability_links: None,
26187            workflow_command_id: None,
26188            workflow_id: Some("wf-rust-failing".to_string()),
26189            run_id: Some("run-rust-failing".to_string()),
26190            workflow_type: "rust.failing".to_string(),
26191            cancel_requested: false,
26192            payload_codec: DEFAULT_CODEC.to_string(),
26193            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26194            history_events: Vec::new(),
26195            total_history_events: Some(0),
26196            history_size_bytes: None,
26197            continue_as_new_recommended: None,
26198            history_budget_pressure: None,
26199            next_history_page_token: None,
26200            workflow_task_attempt: 1,
26201            workflow_signal_id: None,
26202            signal_name: None,
26203            signal_arguments: None,
26204            workflow_update_id: None,
26205            update_name: None,
26206            lease_owner: Some("rust-worker".to_string()),
26207        };
26208
26209        let commands = worker
26210            .execute_workflow_task(task)
26211            .expect("handler failure becomes a workflow command");
26212
26213        assert_eq!(commands.len(), 1);
26214        assert_eq!(commands[0]["type"], "fail_workflow");
26215        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
26216        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
26217        assert_eq!(commands[0]["non_retryable"], false);
26218        assert_eq!(
26219            commands[0]["message"],
26220            "codec error: rust_conformance_failure"
26221        );
26222        assert_eq!(
26223            commands[0]["exception"]["message"],
26224            "codec error: rust_conformance_failure"
26225        );
26226    }
26227
26228    #[test]
26229    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
26230        let client = Client::new("http://127.0.0.1:8080").expect("client");
26231        let mut worker = Worker::new(client, "rust-workers");
26232        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
26233            let _: String = ctx.side_effect(|| "captured".to_string())?;
26234            Err(Error::WorkerLoop("application failure".to_string()))
26235        });
26236
26237        let commands = worker
26238            .execute_workflow_task(workflow_task(
26239                "rust.failing-after-side-effect",
26240                Vec::new(),
26241                DEFAULT_CODEC,
26242            ))
26243            .expect("ordinary failure remains a workflow decision");
26244
26245        assert_eq!(commands.len(), 2);
26246        assert_eq!(commands[0]["type"], "record_side_effect");
26247        assert_eq!(commands[1]["type"], "fail_workflow");
26248    }
26249
26250    #[test]
26251    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
26252        let client = Client::new("http://127.0.0.1:8080").expect("client");
26253        let mut worker = Worker::new(client, "rust-workers");
26254        worker.register_workflow("rust.redrive", |ctx, _input| async move {
26255            ctx.activity("greet", json!([])).await?;
26256            Ok(Value::Null)
26257        });
26258        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
26259            match ctx.activity("greet", json!([])).await {
26260                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
26261                result => result,
26262            }
26263        });
26264
26265        let failed = history_event(
26266            "ActivityFailed",
26267            json!({
26268                "sequence": 1,
26269                "activity_type": "greet",
26270                "activity_execution_id": "activity-1",
26271                "message": "failed"
26272            }),
26273        );
26274        let commands = worker
26275            .execute_workflow_task(workflow_task(
26276                "rust.redrive",
26277                vec![failed.clone()],
26278                DEFAULT_CODEC,
26279            ))
26280            .expect("recorded failure becomes a workflow command");
26281        assert_eq!(commands[0]["type"], "fail_workflow");
26282        assert_eq!(commands[0]["failed_step_sequence"], 1);
26283        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
26284
26285        let translated = worker
26286            .execute_workflow_task(workflow_task(
26287                "rust.redrive-translated",
26288                vec![failed],
26289                DEFAULT_CODEC,
26290            ))
26291            .expect("translated failure becomes a workflow command");
26292        assert_eq!(translated[0]["type"], "fail_workflow");
26293        assert!(translated[0].get("failed_step_sequence").is_none());
26294        assert!(translated[0].get("failed_activity_execution_id").is_none());
26295
26296        let without_identity = worker
26297            .execute_workflow_task(workflow_task(
26298                "rust.redrive",
26299                vec![history_event(
26300                    "ActivityFailed",
26301                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
26302                )],
26303                DEFAULT_CODEC,
26304            ))
26305            .expect("incomplete identity still fails the workflow");
26306        assert!(without_identity[0].get("failed_step_sequence").is_none());
26307
26308        let timed_out = worker
26309            .execute_workflow_task(workflow_task(
26310                "rust.redrive",
26311                vec![history_event(
26312                    "ActivityTimedOut",
26313                    json!({
26314                        "sequence": 1,
26315                        "activity_type": "greet",
26316                        "activity_execution_id": "activity-timeout",
26317                    }),
26318                )],
26319                DEFAULT_CODEC,
26320            ))
26321            .expect("timeout still fails the workflow");
26322        assert!(timed_out[0].get("failed_step_sequence").is_none());
26323    }
26324
26325    #[test]
26326    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
26327        let client = Client::new("http://127.0.0.1:8080").expect("client");
26328        let mut worker = Worker::new(client, "rust-workers");
26329        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
26330            let first = ctx.activity("first", json!([])).await?;
26331            let second = ctx.activity("second", json!([first.clone()])).await?;
26332            Ok(json!({"first": first, "second": second}))
26333        });
26334        let first = history_event(
26335            "ActivityCompleted",
26336            json!({
26337                "sequence": 1,
26338                "activity_type": "first",
26339                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
26340                "payload_codec": DEFAULT_CODEC,
26341                "reused_from_run_id": "failed-run",
26342                "reused_activity_execution_id": "original-first",
26343            }),
26344        );
26345
26346        let retry = worker
26347            .execute_workflow_task(workflow_task(
26348                "rust.redrive-successor",
26349                vec![first.clone()],
26350                DEFAULT_CODEC,
26351            ))
26352            .expect("reused result replays before failed step");
26353        assert_eq!(retry.len(), 1);
26354        assert_eq!(retry[0]["type"], "schedule_activity");
26355        assert_eq!(retry[0]["activity_type"], "second");
26356        assert_eq!(
26357            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
26358            json!(["recorded"]),
26359        );
26360
26361        let second = history_event(
26362            "ActivityCompleted",
26363            json!({
26364                "sequence": 2,
26365                "activity_type": "second",
26366                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
26367                "payload_codec": DEFAULT_CODEC,
26368            }),
26369        );
26370        let completed = worker
26371            .execute_workflow_task(workflow_task(
26372                "rust.redrive-successor",
26373                vec![first, second],
26374                DEFAULT_CODEC,
26375            ))
26376            .expect("retried step completes the successor");
26377        assert_eq!(completed.len(), 1);
26378        assert_eq!(completed[0]["type"], "complete_workflow");
26379        assert_eq!(
26380            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
26381            json!({"first": "recorded", "second": "retried"}),
26382        );
26383    }
26384
26385    #[test]
26386    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
26387        let client = Client::new("http://127.0.0.1:8080").expect("client");
26388        let mut worker = Worker::new(client, "rust-workers");
26389        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
26390            Err(Error::WorkerLoop("application failure".to_string()))
26391        });
26392        let result =
26393            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
26394
26395        let error = worker
26396            .execute_workflow_task(workflow_task(
26397                "rust.removed-side-effect",
26398                vec![history_event(
26399                    "SideEffectRecorded",
26400                    json!({"sequence": 1, "result": result}),
26401                )],
26402                DEFAULT_CODEC,
26403            ))
26404            .expect_err("removed committed history must not become fail_workflow");
26405
26406        let Error::NonDeterministicReplay(failure) = error else {
26407            panic!("expected typed replay failure");
26408        };
26409        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26410        assert_eq!(failure.sequence, Some(1));
26411        assert_eq!(failure.expected.as_deref(), Some("side effect"));
26412    }
26413
26414    #[test]
26415    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
26416        let client = Client::new("http://127.0.0.1:8080").expect("client");
26417        let mut worker = Worker::new(client, "rust-workers");
26418        worker.register_workflow(
26419            "rust.side-effect-before-marker-error",
26420            |ctx, _input| async move {
26421                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
26422                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
26423                ctx.get_version("restart-safe", 2, 2)?;
26424                Ok(Value::Null)
26425            },
26426        );
26427
26428        let error = worker
26429            .execute_workflow_task(workflow_task(
26430                "rust.side-effect-before-marker-error",
26431                vec![history_event(
26432                    "VersionMarkerRecorded",
26433                    json!({
26434                        "sequence": 1,
26435                        "change_id": "restart-safe",
26436                        "version": 1,
26437                        "min_supported": 1,
26438                        "max_supported": 1,
26439                    }),
26440                )],
26441                DEFAULT_CODEC,
26442            ))
26443            .expect_err("replay error must return no queued workflow commands");
26444
26445        let Error::NonDeterministicReplay(failure) = error else {
26446            panic!("expected typed replay failure");
26447        };
26448        assert_eq!(failure.reason, "version_marker_incompatible_range");
26449        assert_eq!(failure.sequence, Some(1));
26450    }
26451
26452    #[test]
26453    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
26454        let client = Client::new("http://127.0.0.1:8080").expect("client");
26455        let mut worker = Worker::new(client, "rust-workers");
26456        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
26457            ctx.sleep(Duration::from_secs(5)).await?;
26458            Ok(json!({"status": "timer fired"}))
26459        });
26460
26461        let task = WorkflowTask {
26462            task_id: "wft-rust-timer-pending".to_string(),
26463            observability_context: None,
26464            dispatch_observability_context: None,
26465            observability_links: None,
26466            workflow_command_id: None,
26467            workflow_id: Some("wf-rust-timer".to_string()),
26468            run_id: Some("run-rust-timer".to_string()),
26469            workflow_type: "rust.timer.pending".to_string(),
26470            cancel_requested: false,
26471            payload_codec: DEFAULT_CODEC.to_string(),
26472            arguments: Some(
26473                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26474            ),
26475            history_events: vec![history_event(
26476                "TimerScheduled",
26477                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26478            )],
26479            total_history_events: Some(1),
26480            history_size_bytes: None,
26481            continue_as_new_recommended: None,
26482            history_budget_pressure: None,
26483            next_history_page_token: None,
26484            workflow_task_attempt: 1,
26485            workflow_signal_id: None,
26486            signal_name: None,
26487            signal_arguments: None,
26488            workflow_update_id: None,
26489            update_name: None,
26490            lease_owner: Some("rust-worker".to_string()),
26491        };
26492
26493        for _redelivery_or_restart in 0..2 {
26494            let commands = worker
26495                .execute_workflow_task(task.clone())
26496                .expect("recorded timer remains pending");
26497            assert!(
26498                commands.is_empty(),
26499                "recorded timer must not be rescheduled"
26500            );
26501        }
26502    }
26503
26504    #[test]
26505    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
26506        let client = Client::new("http://127.0.0.1:8080").expect("client");
26507        let mut worker = Worker::new(client, "rust-workers");
26508        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
26509            Ok(json!({"status": "completed"}))
26510        });
26511        let task = WorkflowTask {
26512            task_id: "wft-rust-timer-removed".to_string(),
26513            observability_context: None,
26514            dispatch_observability_context: None,
26515            observability_links: None,
26516            workflow_command_id: None,
26517            workflow_id: Some("wf-rust-timer".to_string()),
26518            run_id: Some("run-rust-timer".to_string()),
26519            workflow_type: "rust.timer.removed".to_string(),
26520            cancel_requested: false,
26521            payload_codec: DEFAULT_CODEC.to_string(),
26522            arguments: Some(
26523                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26524            ),
26525            history_events: vec![
26526                history_event(
26527                    "TimerScheduled",
26528                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26529                ),
26530                history_event(
26531                    "TimerFired",
26532                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26533                ),
26534            ],
26535            total_history_events: Some(2),
26536            history_size_bytes: None,
26537            continue_as_new_recommended: None,
26538            history_budget_pressure: None,
26539            next_history_page_token: None,
26540            workflow_task_attempt: 1,
26541            workflow_signal_id: None,
26542            signal_name: None,
26543            signal_arguments: None,
26544            workflow_update_id: None,
26545            update_name: None,
26546            lease_owner: Some("rust-worker".to_string()),
26547        };
26548
26549        let Error::NonDeterministicReplay(failure) = worker
26550            .execute_workflow_task(task)
26551            .expect_err("removed timer must fail replay")
26552        else {
26553            panic!("expected typed replay failure");
26554        };
26555        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26556        assert_eq!(failure.sequence, Some(1));
26557    }
26558
26559    #[test]
26560    fn workflow_context_emits_explicit_child_workflow_contract() {
26561        let ctx = WorkflowContext {
26562            cancellation_scope_id: "root".into(),
26563            state: Arc::new(Mutex::new(
26564                WorkflowState::new_with_identity(
26565                    Vec::new(),
26566                    Some("wf-parent".to_string()),
26567                    Some("run-parent".to_string()),
26568                    "parent-workers".to_string(),
26569                    DEFAULT_CODEC.to_string(),
26570                    None,
26571                )
26572                .expect("workflow state"),
26573            )),
26574        };
26575        let options = ChildWorkflowOptions::new("python-workers")
26576            .parent_close_policy(ParentClosePolicy::RequestCancel)
26577            .retry_policy(ChildWorkflowRetryPolicy {
26578                max_attempts: Some(3),
26579                backoff_seconds: vec![1, 5],
26580                non_retryable_error_types: vec!["ValidationError".to_string()],
26581            })
26582            .execution_timeout_seconds(600)
26583            .run_timeout_seconds(120);
26584        let mut call = Box::pin(ctx.start_child_workflow(
26585            "python.fulfil-order",
26586            options,
26587            json!([{"order_id": "order-42"}]),
26588        ));
26589        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26590
26591        assert!(matches!(
26592            call.as_mut().poll(&mut task_context),
26593            Poll::Pending
26594        ));
26595        let commands = ctx.take_commands().expect("commands");
26596        assert_eq!(commands.len(), 1);
26597        let command = &commands[0];
26598        assert_eq!(command["type"], "start_child_workflow");
26599        assert_eq!(command["workflow_type"], "python.fulfil-order");
26600        assert_eq!(command["queue"], "python-workers");
26601        assert_eq!(command["parent_close_policy"], "request_cancel");
26602        assert_eq!(command["retry_policy"]["max_attempts"], 3);
26603        assert_eq!(command["execution_timeout_seconds"], 600);
26604        assert_eq!(command["run_timeout_seconds"], 120);
26605        assert_eq!(
26606            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
26607            json!([{"order_id": "order-42"}])
26608        );
26609    }
26610
26611    fn child_parent_worker() -> Worker {
26612        let client = Client::new("http://127.0.0.1:8080").expect("client");
26613        let mut worker = Worker::new(client, "rust-parent-workers");
26614        worker.register_workflow("rust.parent", |ctx, _input| async move {
26615            let child = ctx
26616                .start_child_workflow(
26617                    "python.child",
26618                    ChildWorkflowOptions::new("python-child-workers")
26619                        .parent_close_policy(ParentClosePolicy::Terminate),
26620                    json!([{"codec_probe": [1, true, "rust"]}]),
26621                )
26622                .await?;
26623            Ok(json!({
26624                "parent_workflow_id": child.parent.workflow_id,
26625                "parent_run_id": child.parent.run_id,
26626                "child_workflow_id": child.child.workflow_id,
26627                "child_run_id": child.child.run_id,
26628                "child_workflow_type": child.child_workflow_type,
26629                "result": child.result,
26630            }))
26631        });
26632        worker
26633    }
26634
26635    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26636        WorkflowTask {
26637            task_id: "wft-child-parent".to_string(),
26638            observability_context: None,
26639            dispatch_observability_context: None,
26640            observability_links: None,
26641            workflow_command_id: None,
26642            workflow_id: Some("wf-parent".to_string()),
26643            run_id: Some("run-parent".to_string()),
26644            workflow_type: "rust.parent".to_string(),
26645            cancel_requested: false,
26646            payload_codec: DEFAULT_CODEC.to_string(),
26647            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26648            history_events: vec![
26649                HistoryEvent {
26650                    event_type: "ChildWorkflowScheduled".to_string(),
26651                    payload: json!({
26652                        "sequence": 1,
26653                        "child_call_id": "call-child",
26654                        "child_workflow_instance_id": "wf-child",
26655                        "child_workflow_run_id": "run-child",
26656                        "child_workflow_type": "python.child",
26657                        "parent_close_policy": "terminate",
26658                    }),
26659                    raw: HashMap::new(),
26660                },
26661                HistoryEvent {
26662                    event_type: event_type.to_string(),
26663                    payload,
26664                    raw: HashMap::new(),
26665                },
26666            ],
26667            total_history_events: Some(2),
26668            history_size_bytes: None,
26669            continue_as_new_recommended: None,
26670            history_budget_pressure: None,
26671            next_history_page_token: None,
26672            workflow_task_attempt: 1,
26673            workflow_signal_id: None,
26674            signal_name: None,
26675            signal_arguments: None,
26676            workflow_update_id: None,
26677            update_name: None,
26678            lease_owner: Some("rust-worker".to_string()),
26679        }
26680    }
26681
26682    #[test]
26683    fn committed_child_result_replays_without_starting_a_duplicate() {
26684        let worker = child_parent_worker();
26685        let task = child_parent_task(
26686            "ChildRunCompleted",
26687            json!({
26688                "sequence": 1,
26689                "child_call_id": "call-child",
26690                "child_workflow_instance_id": "wf-child",
26691                "child_workflow_run_id": "run-child",
26692                "child_workflow_type": "python.child",
26693                "payload_codec": DEFAULT_CODEC,
26694                "result": fixture_envelope(json!({"from":"python","ok":true})),
26695            }),
26696        );
26697
26698        for _restart in 0..2 {
26699            let commands = worker
26700                .execute_workflow_task(task.clone())
26701                .expect("replayed parent task");
26702            assert_eq!(commands.len(), 1);
26703            assert_eq!(commands[0]["type"], "complete_workflow");
26704            assert!(!commands
26705                .iter()
26706                .any(|command| command["type"] == "start_child_workflow"));
26707            let output =
26708                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26709            assert_eq!(output["parent_workflow_id"], "wf-parent");
26710            assert_eq!(output["parent_run_id"], "run-parent");
26711            assert_eq!(output["child_workflow_id"], "wf-child");
26712            assert_eq!(output["child_run_id"], "run-child");
26713            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26714        }
26715    }
26716
26717    #[test]
26718    fn typed_child_arguments_and_results_survive_replay() {
26719        let client = Client::new("http://127.0.0.1:8080").expect("client");
26720        let mut worker = Worker::new(client, "rust-parent-workers");
26721        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26722            let child = ctx
26723                .start_child_workflow_avro_value(
26724                    "python.typed-child",
26725                    ChildWorkflowOptions::new("python-workers"),
26726                    AvroValue::Array(vec![typed_fidelity_probe()]),
26727                )
26728                .await?;
26729            Ok(child.result)
26730        });
26731
26732        let initial = worker
26733            .execute_workflow_task(workflow_task(
26734                "rust.typed-parent",
26735                Vec::new(),
26736                DEFAULT_CODEC,
26737            ))
26738            .expect("typed child start");
26739        assert_eq!(initial[0]["type"], "start_child_workflow");
26740        assert_eq!(
26741            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26742                .expect("typed child arguments"),
26743            AvroValue::Array(vec![typed_fidelity_probe()])
26744        );
26745
26746        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26747            .expect("typed child result");
26748        let task = workflow_task(
26749            "rust.typed-parent",
26750            vec![
26751                history_event(
26752                    "ChildWorkflowScheduled",
26753                    json!({
26754                        "sequence": 1,
26755                        "child_call_id": "call-typed",
26756                        "child_workflow_instance_id": "wf-child",
26757                        "child_workflow_run_id": "run-child",
26758                        "child_workflow_type": "python.typed-child",
26759                    }),
26760                ),
26761                history_event(
26762                    "ChildRunCompleted",
26763                    json!({
26764                        "sequence": 1,
26765                        "child_call_id": "call-typed",
26766                        "child_workflow_instance_id": "wf-child",
26767                        "child_workflow_run_id": "run-child",
26768                        "child_workflow_type": "python.typed-child",
26769                        "payload_codec": DEFAULT_CODEC,
26770                        "result": result,
26771                    }),
26772                ),
26773            ],
26774            DEFAULT_CODEC,
26775        );
26776
26777        let commands = worker
26778            .execute_workflow_task(task)
26779            .expect("typed child replay");
26780        assert_eq!(commands[0]["type"], "complete_workflow");
26781        assert_eq!(
26782            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26783                .expect("typed parent result"),
26784            typed_fidelity_probe()
26785        );
26786    }
26787
26788    #[test]
26789    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26790        let worker = child_parent_worker();
26791        let mut task = child_parent_task("unused", Value::Null);
26792        task.history_events.truncate(1);
26793        task.total_history_events = Some(1);
26794
26795        for _redelivery_or_restart in 0..2 {
26796            let commands = worker
26797                .execute_workflow_task(task.clone())
26798                .expect("recorded child remains pending");
26799            assert!(
26800                commands.is_empty(),
26801                "recorded pending child must not be started again"
26802            );
26803        }
26804    }
26805
26806    #[test]
26807    fn child_cancellation_becomes_stable_parent_failure_command() {
26808        let worker = child_parent_worker();
26809        let task = child_parent_task(
26810            "ChildRunCancelled",
26811            json!({
26812                "sequence": 1,
26813                "child_workflow_instance_id": "wf-child",
26814                "child_workflow_run_id": "run-child",
26815                "child_workflow_type": "python.child",
26816                "failure_id": "failure-child",
26817                "failure_category": "cancelled",
26818                "message": "cancelled by parent-close policy",
26819            }),
26820        );
26821
26822        let commands = worker
26823            .execute_workflow_task(task)
26824            .expect("parent settlement");
26825        assert_eq!(commands.len(), 1);
26826        assert_eq!(commands[0]["type"], "fail_workflow");
26827        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26828        assert_eq!(
26829            commands[0]["exception"]["properties"]["reason"],
26830            "cancelled"
26831        );
26832        assert_eq!(
26833            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26834            "run-child"
26835        );
26836    }
26837
26838    #[test]
26839    fn workflow_can_handle_typed_child_failure() {
26840        let client = Client::new("http://127.0.0.1:8080").expect("client");
26841        let mut worker = Worker::new(client, "rust-parent-workers");
26842        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26843            match ctx
26844                .start_child_workflow(
26845                    "python.child",
26846                    ChildWorkflowOptions::new("python-child-workers"),
26847                    json!([]),
26848                )
26849                .await
26850            {
26851                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26852                    "reason": failure.reason,
26853                    "failure_id": failure.failure_id,
26854                    "exception_class": failure.exception_class,
26855                    "child_run_id": failure.child_workflow_run_id,
26856                })),
26857                Err(error) => Err(error),
26858                Ok(_) => Err(Error::WorkerLoop(
26859                    "child unexpectedly succeeded".to_string(),
26860                )),
26861            }
26862        });
26863        let mut task = child_parent_task(
26864            "ChildRunFailed",
26865            json!({
26866                "sequence": 1,
26867                "child_workflow_instance_id": "wf-child",
26868                "child_workflow_run_id": "run-child",
26869                "child_workflow_type": "python.child",
26870                "failure_id": "failure-child",
26871                "failure_category": "child_workflow",
26872                "message": "payment rejected",
26873                "exception": {
26874                    "type": "PaymentRejected",
26875                    "class": "payments.PaymentRejected",
26876                    "message": "payment rejected"
26877                }
26878            }),
26879        );
26880        task.workflow_type = "rust.handled-parent".to_string();
26881        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26882
26883        let commands = worker.execute_workflow_task(task).expect("handled failure");
26884        assert_eq!(commands[0]["type"], "complete_workflow");
26885        let output =
26886            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26887        assert_eq!(output["reason"], "child_workflow");
26888        assert_eq!(output["failure_id"], "failure-child");
26889        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26890        assert_eq!(output["child_run_id"], "run-child");
26891    }
26892
26893    #[test]
26894    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26895        let client = Client::new("http://127.0.0.1:8080").expect("client");
26896        let mut worker = Worker::new(client, "rust-workers");
26897
26898        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26899            let signal = ctx.wait_signal("start").await?;
26900            let name = signal
26901                .first()
26902                .and_then(|value| value.as_str())
26903                .unwrap_or("world");
26904            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26905            Ok(json!({
26906                "greeting": greeting,
26907                "language": "rust"
26908            }))
26909        });
26910
26911        let signal_arguments =
26912            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26913        let task = WorkflowTask {
26914            task_id: "wft-rust-signal-1".to_string(),
26915            observability_context: None,
26916            dispatch_observability_context: None,
26917            observability_links: None,
26918            workflow_command_id: None,
26919            workflow_id: Some("wf-rust-hello".to_string()),
26920            run_id: Some("run-rust-hello".to_string()),
26921            workflow_type: "rust.hello_workflow".to_string(),
26922            cancel_requested: false,
26923            payload_codec: DEFAULT_CODEC.to_string(),
26924            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26925            history_events: vec![HistoryEvent {
26926                event_type: "SignalReceived".to_string(),
26927                payload: json!({
26928                    "signal_id": "sig-rust-1",
26929                    "signal_name": "start"
26930                }),
26931                raw: HashMap::new(),
26932            }],
26933            total_history_events: Some(1),
26934            history_size_bytes: None,
26935            continue_as_new_recommended: None,
26936            history_budget_pressure: None,
26937            next_history_page_token: None,
26938            workflow_task_attempt: 1,
26939            workflow_signal_id: Some("sig-rust-1".to_string()),
26940            signal_name: Some("start".to_string()),
26941            signal_arguments: Some(signal_arguments),
26942            workflow_update_id: None,
26943            update_name: None,
26944            lease_owner: Some("rust-worker".to_string()),
26945        };
26946
26947        let commands = worker.execute_workflow_task(task).expect("workflow task");
26948
26949        assert_eq!(commands.len(), 1);
26950        assert_eq!(commands[0]["type"], "schedule_activity");
26951        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26952        assert_eq!(
26953            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
26954            json!(["Rust"])
26955        );
26956    }
26957
26958    #[test]
26959    fn workflow_task_appends_paginated_history_events() {
26960        let mut task = WorkflowTask {
26961            task_id: "wft-rust-pages-1".to_string(),
26962            observability_context: None,
26963            dispatch_observability_context: None,
26964            observability_links: None,
26965            workflow_command_id: None,
26966            workflow_id: Some("wf-rust-pages".to_string()),
26967            run_id: Some("run-rust-pages".to_string()),
26968            workflow_type: "rust.hello_workflow".to_string(),
26969            cancel_requested: false,
26970            payload_codec: DEFAULT_CODEC.to_string(),
26971            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26972            history_events: vec![HistoryEvent {
26973                event_type: "WorkflowStarted".to_string(),
26974                payload: json!({}),
26975                raw: HashMap::new(),
26976            }],
26977            total_history_events: Some(3),
26978            history_size_bytes: None,
26979            continue_as_new_recommended: None,
26980            history_budget_pressure: None,
26981            next_history_page_token: Some("MQ==".to_string()),
26982            workflow_task_attempt: 1,
26983            workflow_signal_id: None,
26984            signal_name: None,
26985            signal_arguments: None,
26986            workflow_update_id: None,
26987            update_name: None,
26988            lease_owner: Some("rust-worker".to_string()),
26989        };
26990
26991        task.append_history_page(WorkflowTaskHistoryPage {
26992            history_events: vec![
26993                HistoryEvent {
26994                    event_type: "SignalReceived".to_string(),
26995                    payload: json!({
26996                        "signal_id": "sig-rust-1",
26997                        "signal_name": "start",
26998                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
26999                            .expect("signal arguments")
27000                    }),
27001                    raw: HashMap::new(),
27002                },
27003                HistoryEvent {
27004                    event_type: "MarkerRecorded".to_string(),
27005                    payload: json!({"sequence": 3}),
27006                    raw: HashMap::new(),
27007                },
27008            ],
27009            total_history_events: Some(3),
27010            next_history_page_token: None,
27011        });
27012
27013        assert_eq!(task.history_events.len(), 3);
27014        assert_eq!(task.total_history_events, Some(3));
27015        assert_eq!(task.next_history_page_token, None);
27016
27017        let signal = task
27018            .history_events
27019            .iter()
27020            .find(|event| event.event_type == "SignalReceived")
27021            .expect("signal event");
27022        assert_eq!(
27023            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
27024            vec![AvroValue::String("Rust".to_string())]
27025        );
27026    }
27027
27028    #[tokio::test]
27029    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
27030        let client = Client::new("http://127.0.0.1:8080").expect("client");
27031        let mut worker = Worker::new(client, "rust-workers");
27032        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27033        worker.register_query("counter", "current", |ctx, _args| async move {
27034            let mut count = 0_i64;
27035            for signal in ctx.signal_events() {
27036                let value = signal
27037                    .arguments
27038                    .first()
27039                    .and_then(Value::as_i64)
27040                    .unwrap_or_default();
27041                match signal.name.as_str() {
27042                    "increment" => count += value,
27043                    "set" => count = value,
27044                    _ => {}
27045                }
27046            }
27047            Ok(json!(count))
27048        });
27049
27050        let task = QueryTask {
27051            query_task_id: "query-rust-counter".to_string(),
27052            observability_context: None,
27053            dispatch_observability_context: None,
27054            observability_links: None,
27055            query_task_attempt: 1,
27056            lease_owner: Some("rust-worker".to_string()),
27057            workflow_id: Some("counter-1".to_string()),
27058            run_id: Some("run-counter-1".to_string()),
27059            workflow_type: "counter".to_string(),
27060            query_name: "current".to_string(),
27061            payload_codec: DEFAULT_CODEC.to_string(),
27062            workflow_arguments: Some(
27063                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27064            ),
27065            query_arguments: Some(
27066                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
27067            ),
27068            history_events: vec![
27069                HistoryEvent {
27070                    event_type: "SignalReceived".to_string(),
27071                    payload: json!({
27072                        "signal_id": "php-signal-1",
27073                        "signal_name": "increment",
27074                        "workflow_sequence": 1,
27075                        "payload_codec": DEFAULT_CODEC,
27076                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
27077                    }),
27078                    raw: HashMap::new(),
27079                },
27080                HistoryEvent {
27081                    event_type: "SignalReceived".to_string(),
27082                    payload: json!({
27083                        "signal_id": "python-signal-2",
27084                        "signal_name": "increment",
27085                        "workflow_sequence": 2,
27086                        "payload_codec": DEFAULT_CODEC,
27087                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
27088                    }),
27089                    raw: HashMap::new(),
27090                },
27091                HistoryEvent {
27092                    event_type: "SignalReceived".to_string(),
27093                    payload: json!({
27094                        "signal_id": "rust-signal-3",
27095                        "signal_name": "set",
27096                        "workflow_sequence": 3,
27097                        "payload_codec": DEFAULT_CODEC,
27098                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
27099                    }),
27100                    raw: HashMap::new(),
27101                },
27102            ],
27103            history_export: None,
27104            run_status: Some("completed".to_string()),
27105        };
27106
27107        let result = worker.execute_query_task(task).await.expect("query result");
27108        assert_eq!(result.into_json().expect("query projection"), json!(0));
27109    }
27110
27111    #[tokio::test]
27112    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
27113        let worker = replay_counter_worker();
27114        let running_history = json!([
27115            {
27116                "type": "ActivityCompleted",
27117                "payload": {
27118                    "sequence": 1,
27119                    "activity_type": "load-counter",
27120                    "payload_codec": DEFAULT_CODEC,
27121                    "result": fixture_envelope(json!("loaded"))
27122                }
27123            },
27124            {
27125                "type": "SignalWaitOpened",
27126                "payload": {
27127                    "sequence": 3,
27128                    "signal_name": "increment"
27129                }
27130            },
27131            {
27132                "type": "SignalReceived",
27133                "payload": {
27134                    "signal_id": "signal-3",
27135                    "signal_name": "increment",
27136                    "workflow_sequence": 2,
27137                    "payload_codec": DEFAULT_CODEC,
27138                    "arguments": fixture_envelope(json!([3]))
27139                }
27140            },
27141            {
27142                "type": "SignalApplied",
27143                "payload": {
27144                    "sequence": 3,
27145                    "signal_id": "signal-3",
27146                    "signal_name": "increment",
27147                    "payload_codec": DEFAULT_CODEC,
27148                    "value": fixture_envelope(json!([3]))
27149                }
27150            }
27151        ]);
27152
27153        let running = worker
27154            .execute_query_task(replay_counter_query(
27155                "current",
27156                running_history.clone(),
27157                "running",
27158            ))
27159            .await
27160            .expect("running replay query");
27161        assert_eq!(
27162            running.clone().into_json().expect("query projection"),
27163            json!({"loaded": "loaded", "count": 3, "finished": false})
27164        );
27165
27166        let detached = worker
27167            .execute_query_task(replay_counter_query(
27168                "detached-mutation",
27169                running_history.clone(),
27170                "running",
27171            ))
27172            .await
27173            .expect("query mutates only its detached state clone");
27174        assert_eq!(detached.into_json().expect("query projection"), json!(999));
27175        let failed = worker
27176            .execute_query_task(replay_counter_query(
27177                "failed-mutation",
27178                running_history.clone(),
27179                "running",
27180            ))
27181            .await
27182            .expect_err("failed query");
27183        assert_eq!(failed.reason, "query_rejected");
27184        let unchanged = worker
27185            .execute_query_task(replay_counter_query("current", running_history, "running"))
27186            .await
27187            .expect("later query reconstructs unchanged state");
27188        assert_eq!(unchanged, running);
27189
27190        let restarted_worker = replay_counter_worker();
27191        let empty_arguments = fixture_envelope(json!([]));
27192        let loaded_result = fixture_envelope(json!("loaded"));
27193        let signal_three = fixture_blob(json!([3]));
27194        let signal_five = fixture_blob(json!([5]));
27195        let restarted_task: QueryTask = serde_json::from_value(json!({
27196            "query_task_id": "query-after-restart",
27197            "workflow_id": "counter-1",
27198            "run_id": "run-counter-1",
27199            "workflow_type": "replay-counter",
27200            "query_name": "current",
27201            "payload_codec": DEFAULT_CODEC,
27202            "workflow_arguments": empty_arguments.clone(),
27203            "query_arguments": empty_arguments,
27204            "history_events": [],
27205            "history_export": {
27206                "payloads": {"codec": DEFAULT_CODEC},
27207                "history_events": [
27208                    {
27209                        "type": "ActivityCompleted",
27210                        "payload": {
27211                            "sequence": 1,
27212                            "activity_type": "load-counter",
27213                            "payload_codec": DEFAULT_CODEC,
27214                            "result": null
27215                        }
27216                    },
27217                    {
27218                        "type": "SignalWaitOpened",
27219                        "payload": {
27220                            "sequence": 3,
27221                            "signal_name": "increment"
27222                        }
27223                    },
27224                    {
27225                        "type": "SignalReceived",
27226                        "payload": {
27227                            "signal_id": "signal-3",
27228                            "signal_name": "increment",
27229                            "workflow_sequence": 2
27230                        }
27231                    },
27232                    {
27233                        "type": "SignalApplied",
27234                        "payload": {
27235                            "sequence": 3,
27236                            "signal_id": "signal-3",
27237                            "signal_name": "increment"
27238                        }
27239                    },
27240                    {
27241                        "type": "SignalWaitOpened",
27242                        "payload": {
27243                            "sequence": 5,
27244                            "signal_name": "increment"
27245                        }
27246                    },
27247                    {
27248                        "type": "SignalReceived",
27249                        "payload": {
27250                            "signal_id": "signal-5",
27251                            "signal_name": "increment",
27252                            "workflow_sequence": 4
27253                        }
27254                    },
27255                    {
27256                        "type": "SignalApplied",
27257                        "payload": {
27258                            "sequence": 5,
27259                            "signal_id": "signal-5",
27260                            "signal_name": "increment"
27261                        }
27262                    }
27263                ],
27264                "activities": [{
27265                    "sequence": 1,
27266                    "activity_type": "load-counter",
27267                    "payload_codec": DEFAULT_CODEC,
27268                    "result": loaded_result
27269                }],
27270                "signals": [
27271                    {
27272                        "id": "signal-3",
27273                        "name": "increment",
27274                        "workflow_sequence": 2,
27275                        "payload_codec": DEFAULT_CODEC,
27276                        "arguments": signal_three
27277                    },
27278                    {
27279                        "id": "signal-5",
27280                        "name": "increment",
27281                        "workflow_sequence": 4,
27282                        "payload_codec": DEFAULT_CODEC,
27283                        "arguments": signal_five
27284                    }
27285                ]
27286            },
27287            "run_status": "completed"
27288        }))
27289        .expect("cold replay query task");
27290        let completed = restarted_worker
27291            .execute_query_task(restarted_task)
27292            .await
27293            .expect("completed cold replay query");
27294        assert_eq!(
27295            completed.into_json().expect("query projection"),
27296            json!({"loaded": "loaded", "count": 8, "finished": true})
27297        );
27298    }
27299
27300    #[tokio::test]
27301    async fn replayed_query_replay_failures_are_machine_readable() {
27302        let worker = replay_counter_worker();
27303        let task = replay_counter_query(
27304            "current",
27305            json!([{
27306                "type": "ActivityCompleted",
27307                "payload": {
27308                    "sequence": 1,
27309                    "payload_codec": DEFAULT_CODEC,
27310                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
27311                }
27312            }]),
27313            "running",
27314        );
27315        let failure = worker
27316            .execute_query_task(task)
27317            .await
27318            .expect_err("invalid replay history payload");
27319        assert_eq!(failure.reason, "query_payload_decode_failed");
27320        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
27321        assert!(failure.message.contains("invalid_payload_framing"));
27322    }
27323
27324    #[tokio::test]
27325    async fn query_task_restores_compact_history_from_export() {
27326        let client = Client::new("http://127.0.0.1:8080").expect("client");
27327        let mut worker = Worker::new(client, "rust-workers");
27328        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27329        worker.register_query("counter", "current", |ctx, _args| async move {
27330            Ok(json!(ctx.signals("increment")[0][0]))
27331        });
27332        let empty_arguments = fixture_envelope(json!([]));
27333        let exported_signal = fixture_blob(json!([9]));
27334        let task: QueryTask = serde_json::from_value(json!({
27335            "query_task_id": "query-export",
27336            "workflow_type": "counter",
27337            "query_name": "current",
27338            "payload_codec": DEFAULT_CODEC,
27339            "workflow_arguments": empty_arguments.clone(),
27340            "query_arguments": empty_arguments,
27341            "history_events": [],
27342            "history_export": {
27343                "payloads": {"codec": DEFAULT_CODEC},
27344                "history_events": [{
27345                    "type": "SignalReceived",
27346                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
27347                }],
27348                "signals": [{
27349                    "id": "signal-export",
27350                    "name": "increment",
27351                    "status": "applied",
27352                    "workflow_sequence": 1,
27353                    "payload_codec": DEFAULT_CODEC,
27354                    "arguments": exported_signal
27355                }]
27356            }
27357        }))
27358        .expect("query task");
27359
27360        let result = worker.execute_query_task(task).await.expect("query result");
27361        assert_eq!(result.into_json().expect("query projection"), json!(9));
27362    }
27363
27364    #[tokio::test]
27365    async fn query_task_failures_have_stable_reasons() {
27366        let client = Client::new("http://127.0.0.1:8080").expect("client");
27367        let mut worker = Worker::new(client, "rust-workers");
27368        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27369        worker.register_query(
27370            "counter",
27371            "current",
27372            |_ctx, _args| async move { Ok(json!(0)) },
27373        );
27374
27375        let base_task = QueryTask {
27376            query_task_id: "query-errors".to_string(),
27377            observability_context: None,
27378            dispatch_observability_context: None,
27379            observability_links: None,
27380            query_task_attempt: 1,
27381            lease_owner: None,
27382            workflow_id: Some("counter-errors".to_string()),
27383            run_id: Some("run-errors".to_string()),
27384            workflow_type: "counter".to_string(),
27385            query_name: "missing".to_string(),
27386            payload_codec: DEFAULT_CODEC.to_string(),
27387            workflow_arguments: Some(fixture_envelope(json!([]))),
27388            query_arguments: Some(fixture_envelope(json!([]))),
27389            history_events: Vec::new(),
27390            history_export: None,
27391            run_status: Some("running".to_string()),
27392        };
27393
27394        let unknown = worker
27395            .execute_query_task(base_task.clone())
27396            .await
27397            .expect_err("unknown query");
27398        assert_eq!(unknown.reason, "rejected_unknown_query");
27399
27400        let mut malformed = base_task;
27401        malformed.query_name = "current".to_string();
27402        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
27403        let malformed = worker
27404            .execute_query_task(malformed)
27405            .await
27406            .expect_err("malformed payload");
27407        assert_eq!(malformed.reason, "query_payload_decode_failed");
27408
27409        let client = Client::new("http://127.0.0.1:8080").expect("client");
27410        let mut unavailable_worker = Worker::new(client, "rust-workers");
27411        unavailable_worker
27412            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27413        let empty_arguments = fixture_envelope(json!([]));
27414        let unavailable_task: QueryTask = serde_json::from_value(json!({
27415            "query_task_id": "query-unavailable",
27416            "workflow_type": "counter",
27417            "query_name": "current",
27418            "payload_codec": DEFAULT_CODEC,
27419            "workflow_arguments": empty_arguments.clone(),
27420            "query_arguments": empty_arguments
27421        }))
27422        .expect("query task");
27423        let unavailable = unavailable_worker
27424            .execute_query_task(unavailable_task)
27425            .await
27426            .expect_err("query handler unavailable");
27427        assert_eq!(unavailable.reason, "query_handler_unavailable");
27428    }
27429
27430    #[tokio::test]
27431    async fn client_query_decodes_result_and_typed_failure() {
27432        let server = MockWorkerServer::start();
27433        let client = Client::builder(server.base_url())
27434            .timeout(Duration::from_secs(2))
27435            .build()
27436            .expect("client");
27437
27438        let result = client
27439            .query_workflow("counter-1", "current", json!([]))
27440            .await
27441            .expect("query result");
27442        assert_eq!(result, json!({"count": 8}));
27443
27444        let error = client
27445            .query_workflow("counter-1", "missing", json!([]))
27446            .await
27447            .expect_err("unknown query");
27448        let Error::QueryFailed(failure) = error else {
27449            panic!("expected typed query failure");
27450        };
27451        assert_eq!(failure.status, 404);
27452        assert_eq!(failure.reason, "rejected_unknown_query");
27453    }
27454
27455    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
27456    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
27457    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
27458
27459    #[cfg(feature = "telemetry")]
27460    #[tokio::test]
27461    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
27462        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27463        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
27464        PHASE.store(0, Ordering::SeqCst);
27465        use opentelemetry::{
27466            propagation::TextMapPropagator,
27467            trace::{FutureExt, TracerProvider},
27468        };
27469        use opentelemetry_sdk::propagation::TraceContextPropagator;
27470        struct Restore;
27471        impl Drop for Restore {
27472            fn drop(&mut self) {
27473                opentelemetry::global::set_text_map_propagator(
27474                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27475                );
27476            }
27477        }
27478        let _restore = Restore;
27479        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
27480        let headers = HashMap::from([(
27481            "traceparent".to_string(),
27482            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
27483        )]);
27484        let parent = TraceContextPropagator::new().extract(&headers);
27485        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27486            request_override: Some(|path, body, _number| {
27487                if path == "/api/cluster/info" {
27488                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
27489                        ("503 Service Unavailable", "{}".into())
27490                    } else {
27491                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27492                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
27493                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27494                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27495                        }}}}).to_string())
27496                    });
27497                }
27498                let body: Value = serde_json::from_str(body).ok()?;
27499                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
27500                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
27501                    "result": "original"}).to_string()))
27502            }),
27503            ..MockWorkerBehavior::default()
27504        });
27505        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
27506        let client = Client::new(server.base_url()).unwrap().with_telemetry(
27507            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
27508        );
27509        let input = json!([{"observability_context": {"business": "preserved"}}]);
27510        async {
27511            client
27512                .start_workflow("orders", "orders", "order", &input)
27513                .await
27514                .unwrap();
27515            assert!(server
27516                .request_body("/api/workflows")
27517                .get("observability_context")
27518                .is_none());
27519            client.cluster_info().await.unwrap();
27520            client
27521                .start_workflow("orders", "orders", "order", &input)
27522                .await
27523                .unwrap();
27524            client
27525                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
27526                .await
27527                .unwrap();
27528            client
27529                .update_workflow("order", "status", &input, Some("update-original"))
27530                .await
27531                .unwrap();
27532            client
27533                .cancel_workflow("order", WorkflowCommandOptions::default())
27534                .await
27535                .unwrap();
27536            for path in [
27537                "/api/workflows",
27538                "/api/workflows/order/signal/ready",
27539                "/api/workflows/order/update/status",
27540                "/api/workflows/order/cancel",
27541            ] {
27542                let bodies = server.request_bodies(path);
27543                let body = bodies.last().unwrap();
27544                assert_eq!(
27545                    body["observability_context"]["carrier"]["traceparent"],
27546                    headers["traceparent"]
27547                );
27548                assert!(body["observability_context"]["carrier"]
27549                    .get("baggage")
27550                    .is_none());
27551            }
27552            let starts = server.request_bodies("/api/workflows");
27553            assert_eq!(
27554                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
27555                input
27556            );
27557            assert_eq!(
27558                server.request_body("/api/workflows/order/signal/ready")["request_id"],
27559                "signal-original"
27560            );
27561            assert_eq!(
27562                server.request_body("/api/workflows/order/update/status")["request_id"],
27563                "update-original"
27564            );
27565            PHASE.store(1, Ordering::SeqCst);
27566            client.cluster_info().await.unwrap();
27567            client
27568                .start_workflow("orders", "orders", "order", &input)
27569                .await
27570                .unwrap();
27571            assert!(server
27572                .request_bodies("/api/workflows")
27573                .last()
27574                .unwrap()
27575                .get("observability_context")
27576                .is_none());
27577            PHASE.store(2, Ordering::SeqCst);
27578            assert!(client.cluster_info().await.is_err());
27579            let before = server.captured_paths().len();
27580            client
27581                .start_workflow("orders", "orders", "order", &input)
27582                .await
27583                .unwrap();
27584            assert_eq!(server.captured_paths().len(), before + 1);
27585            assert!(server
27586                .request_bodies("/api/workflows")
27587                .last()
27588                .unwrap()
27589                .get("observability_context")
27590                .is_none());
27591        }
27592        .with_context(parent)
27593        .await;
27594    }
27595
27596    #[cfg(feature = "telemetry")]
27597    fn observability_worker_server(
27598        path: &str,
27599        _body: &str,
27600        _: usize,
27601    ) -> Option<(&'static str, String)> {
27602        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27603            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
27604                        "baggage": "credential=private"}});
27605        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27606            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
27607        if path == "/api/cluster/info" {
27608            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27609                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
27610                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27611                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27612            }}}}).to_string()));
27613        }
27614        if path.ends_with("/complete") {
27615            return Some(("200 OK", json!({"recorded": true}).to_string()));
27616        }
27617        let task_id = match path {
27618            "/api/worker/workflow-tasks/poll" => "workflow-task",
27619            "/api/worker/activity-tasks/poll" => "activity-task",
27620            "/api/worker/query-tasks/poll" => "query-task",
27621            _ => return None,
27622        };
27623        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
27624        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
27625        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
27626        "activity_type": "wire.activity", "activity_execution_id": "activity",
27627        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
27628        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
27629        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
27630        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
27631        "query_arguments": input, "history_events": [], "observability_context": context,
27632        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
27633            "task_id": task_id, "context": link_context},
27634        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
27635            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
27636                {"kind": "command", "command_id": "accepted-command", "context": link_context},
27637                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
27638                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
27639                 "event_type": "WorkflowCancelled", "context": link_context}
27640            ]}});
27641        if task_id == "workflow-task" {
27642            task["arguments"] = encode_value_envelope(
27643                &json!([{"observability_context": {"business": "preserved"}}]),
27644                DEFAULT_CODEC,
27645            )
27646            .unwrap();
27647        }
27648        Some((
27649            "200 OK",
27650            json!({"task": task, "poll_status": "leased"}).to_string(),
27651        ))
27652    }
27653
27654    #[cfg(feature = "telemetry")]
27655    #[tokio::test]
27656    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
27657    {
27658        use opentelemetry::trace::TracerProvider;
27659        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27660        opentelemetry::global::set_text_map_propagator(
27661            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
27662        );
27663        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27664        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27665            .with_simple_exporter(exporter.clone())
27666            .build();
27667        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
27668        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27669            request_override: Some(observability_worker_server),
27670            ..MockWorkerBehavior::default()
27671        });
27672        let client = Client::builder(server.base_url())
27673            .namespace("shipping")
27674            .build()
27675            .unwrap();
27676        client.cluster_info().await.unwrap();
27677        let mut worker = Worker::new(client, "shipping")
27678            .worker_id("test-worker")
27679            .telemetry(telemetry);
27680        worker.register_workflow("wire.workflow", |ctx, input| async move {
27681            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
27682            assert_eq!(
27683                input,
27684                json!([{"observability_context": {"business": "preserved"}}])
27685            );
27686            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
27687                .await?;
27688            Ok(Value::Null)
27689        });
27690        worker.register_activity("wire.activity", |_, _| async {
27691            let fields = telemetry::current_log_context();
27692            assert_eq!(fields["workflow_run_id"], "run");
27693            assert_eq!(fields["activity_id"], "activity");
27694            assert_eq!(fields["activity_attempt_id"], "attempt");
27695            assert_eq!(fields["activity_attempt_number"], "3");
27696            Ok(json!("original-result"))
27697        });
27698        worker.register_query("wire.workflow", "state", |_, _| async {
27699            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
27700            Ok(json!("original-query"))
27701        });
27702        assert_eq!(worker.run_once().await.unwrap(), 3);
27703        let spans = exporter.get_finished_spans().unwrap();
27704        assert_eq!(spans.len(), 4);
27705        let origin_trace = "12345678901234567890123456789012";
27706        for span in spans
27707            .iter()
27708            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
27709        {
27710            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
27711            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
27712            assert_eq!(span.links.len(), 3);
27713            assert!(!format!("{:?}", span.attributes).contains("credential"));
27714        }
27715        let task = spans
27716            .iter()
27717            .find(|span| span.name.as_ref() == "durable.workflow.task")
27718            .unwrap();
27719        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
27720        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
27721        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
27722            .as_str()
27723            .unwrap();
27724        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
27725        assert!(telemetry::current_log_context().is_empty());
27726        opentelemetry::global::set_text_map_propagator(
27727            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27728        );
27729    }
27730
27731    #[cfg(feature = "telemetry")]
27732    #[tokio::test]
27733    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
27734        use opentelemetry::trace::TracerProvider;
27735        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
27736        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
27737            let (status, reply) = observability_worker_server(path, body, count)?;
27738            if path != "/api/worker/query-tasks/poll" {
27739                return Some((status, reply));
27740            }
27741            let mut reply: Value = serde_json::from_str(&reply).unwrap();
27742            match REFUSAL.load(Ordering::SeqCst) {
27743                0 => reply["task"]["lease_owner"] = json!("other-worker"),
27744                1 => reply["task"]["query_task_attempt"] = json!(0),
27745                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
27746            }
27747            Some((status, reply.to_string()))
27748        }
27749        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27750        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27751            .with_simple_exporter(exporter.clone())
27752            .build();
27753        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27754            request_override: Some(refused_query),
27755            ..MockWorkerBehavior::default()
27756        });
27757        let client = Client::builder(server.base_url())
27758            .namespace("shipping")
27759            .build()
27760            .unwrap();
27761        client.cluster_info().await.unwrap();
27762        let mut worker = Worker::new(client, "shipping")
27763            .worker_id("test-worker")
27764            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
27765                provider.tracer("test"),
27766            ));
27767        let calls = Arc::new(AtomicUsize::new(0));
27768        let query_calls = calls.clone();
27769        worker.register_query("wire.workflow", "state", move |_, _| {
27770            query_calls.fetch_add(1, Ordering::SeqCst);
27771            async { Ok(Value::Null) }
27772        });
27773        for refusal in 0..3 {
27774            REFUSAL.store(refusal, Ordering::SeqCst);
27775            assert!(matches!(
27776                worker.poll_query_once().await.unwrap(),
27777                ManagedPollOutcome::Handled
27778            ));
27779            assert_eq!(calls.load(Ordering::SeqCst), 0);
27780            assert!(exporter.get_finished_spans().unwrap().is_empty());
27781            assert!(telemetry::current_log_context().is_empty());
27782        }
27783        assert!(!server
27784            .captured_paths()
27785            .iter()
27786            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
27787    }
27788
27789    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
27790        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
27791            return None;
27792        }
27793        serde_json::from_str(body).ok()
27794    }
27795
27796    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
27797    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27798        let request = keyed_command_request(path, body)?;
27799        let mut receipt = json!({
27800            "outcome": "accepted",
27801            "command_status": "accepted",
27802            "command_id": "cmd-keyed-1",
27803            "request_id": request["request_id"],
27804            "retained": false,
27805            "intent_verified": true,
27806        });
27807        if path == KEYED_UPDATE_PATH {
27808            receipt["update_id"] = json!("upd-keyed-1");
27809            receipt["result_envelope"] =
27810                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
27811        }
27812        Some(("202 Accepted", receipt.to_string()))
27813    }
27814
27815    /// A Server released before #216: accepts the body field but echoes nothing.
27816    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27817        keyed_command_request(path, body)?;
27818        Some((
27819            "202 Accepted",
27820            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
27821                .to_string(),
27822        ))
27823    }
27824
27825    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27826        let request = keyed_command_request(path, body)?;
27827        Some((
27828            "202 Accepted",
27829            json!({
27830                "outcome": "accepted",
27831                "command_status": "accepted",
27832                "command_id": "cmd-first",
27833                "request_id": request["request_id"],
27834                "retained": true,
27835                "intent_verified": true,
27836            })
27837            .to_string(),
27838        ))
27839    }
27840
27841    fn conflicting_command_server(
27842        path: &str,
27843        body: &str,
27844        _: usize,
27845    ) -> Option<(&'static str, String)> {
27846        let request = keyed_command_request(path, body)?;
27847        let retained_type = if path == KEYED_UPDATE_PATH {
27848            "update"
27849        } else {
27850            "signal"
27851        };
27852        Some((
27853            "409 Conflict",
27854            json!({
27855                "reason": "request_id_conflict",
27856                "message": format!("request id is retained for a different {retained_type} intent"),
27857                "request_id": request["request_id"],
27858                "retained_command_id": "cmd-retained-1",
27859                "retained_command_type": retained_type,
27860                "retained_outcome": "accepted",
27861                "conflict": ["arguments", "target"],
27862                "control_plane": {"operation": retained_type},
27863            })
27864            .to_string(),
27865        ))
27866    }
27867
27868    fn closed_run_command_server(
27869        path: &str,
27870        body: &str,
27871        _: usize,
27872    ) -> Option<(&'static str, String)> {
27873        let request = keyed_command_request(path, body)?;
27874        Some((
27875            "409 Conflict",
27876            json!({
27877                "reason": "run_not_active",
27878                "message": "run is closed",
27879                "request_id": request["request_id"],
27880            })
27881            .to_string(),
27882        ))
27883    }
27884
27885    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
27886        path == KEYED_SIGNAL_PATH && request_number == 1
27887    }
27888
27889    fn keyed_client(server: &MockWorkerServer) -> Client {
27890        Client::builder(server.base_url())
27891            .timeout(Duration::from_secs(2))
27892            .build()
27893            .expect("client")
27894    }
27895
27896    fn keyed_handle(client: &Client) -> WorkflowHandle {
27897        WorkflowHandle {
27898            client: client.clone(),
27899            workflow_id: "keyed-1".to_string(),
27900            run_id: Some("run-keyed-1".to_string()),
27901            workflow_type: "keyed".to_string(),
27902        }
27903    }
27904
27905    fn assert_generated_request_id(request_id: &str, prefix: &str) {
27906        let suffix = request_id
27907            .strip_prefix(prefix)
27908            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
27909        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
27910        assert!(
27911            suffix
27912                .bytes()
27913                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
27914            "lowercase hex suffix: {request_id:?}"
27915        );
27916        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
27917    }
27918
27919    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
27920        let headers = server.request_headers(path);
27921        assert!(!headers.is_empty(), "no request captured for {path}");
27922        for headers in headers {
27923            let header_names: Vec<String> = headers
27924                .lines()
27925                .skip(1)
27926                .filter_map(|line| line.split_once(':'))
27927                .map(|(name, _)| name.trim().to_ascii_lowercase())
27928                .collect();
27929            assert!(
27930                !header_names.iter().any(|name| name == "x-request-id"),
27931                "the caller command key is a body field, never an X-Request-Id header: {headers}"
27932            );
27933        }
27934    }
27935
27936    #[tokio::test]
27937    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
27938        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27939            request_override: Some(legacy_command_server),
27940            ..MockWorkerBehavior::default()
27941        });
27942        let client = keyed_client(&server);
27943
27944        let receipt = client
27945            .signal_workflow("keyed-1", "approve", json!(["ok"]))
27946            .await
27947            .expect("signal receipt");
27948
27949        let sent = server.request_body(KEYED_SIGNAL_PATH);
27950        let request_id = sent["request_id"].as_str().expect("generated request_id");
27951        assert_generated_request_id(request_id, "sdk-rust-signal-");
27952        assert_eq!(
27953            receipt,
27954            json!({
27955                "outcome": "accepted",
27956                "command_status": "accepted",
27957                "command_id": "cmd-legacy",
27958                "request_id": request_id,
27959            }),
27960            "the sent key is added when an older Server omits it"
27961        );
27962        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
27963
27964        let receipt = keyed_handle(&client)
27965            .signal_selected_run("approve", json!(["ok"]))
27966            .await
27967            .expect("selected-run signal receipt");
27968        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
27969        let run_request_id = run_sent["request_id"]
27970            .as_str()
27971            .expect("generated request_id");
27972        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
27973        assert_eq!(receipt["request_id"], run_request_id);
27974        assert_ne!(
27975            run_request_id, request_id,
27976            "each logical call gets its own key"
27977        );
27978        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
27979    }
27980
27981    #[tokio::test]
27982    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
27983        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27984            request_override: Some(keyed_command_server),
27985            ..MockWorkerBehavior::default()
27986        });
27987        let client = keyed_client(&server);
27988
27989        let result = client
27990            .update_workflow("keyed-1", "adjust", json!([1]), None)
27991            .await
27992            .expect("update result");
27993        assert_eq!(
27994            result,
27995            json!(42),
27996            "the decoded update result is returned unchanged"
27997        );
27998        let typed = client
27999            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
28000            .await
28001            .expect("typed update result");
28002        assert_eq!(typed, AvroValue::Long(42));
28003        keyed_handle(&client)
28004            .update("adjust", json!([1]), None)
28005            .await
28006            .expect("handle update result");
28007
28008        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
28009        assert_eq!(bodies.len(), 3);
28010        for body in &bodies {
28011            assert_generated_request_id(
28012                body["request_id"].as_str().expect("generated request_id"),
28013                "sdk-rust-update-",
28014            );
28015            assert_eq!(body["wait_for"], "completed");
28016        }
28017        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
28018        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
28019        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
28020    }
28021
28022    #[tokio::test]
28023    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
28024        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28025            request_override: Some(keyed_command_server),
28026            ..MockWorkerBehavior::default()
28027        });
28028        let client = keyed_client(&server);
28029        let handle = keyed_handle(&client);
28030
28031        let receipt = client
28032            .signal_workflow_with_request_id(
28033                "keyed-1",
28034                "approve",
28035                json!(["ok"]),
28036                "Order-42/approve",
28037            )
28038            .await
28039            .expect("signal receipt");
28040        assert_eq!(receipt["request_id"], "Order-42/approve");
28041        assert_eq!(receipt["retained"], false);
28042        assert_eq!(receipt["intent_verified"], true);
28043        handle
28044            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
28045            .await
28046            .expect("handle signal receipt");
28047        client
28048            .signal_workflow_run_with_request_id(
28049                "keyed-1",
28050                "run-keyed-1",
28051                "approve",
28052                json!(["ok"]),
28053                "run-signal-key",
28054            )
28055            .await
28056            .expect("selected-run signal receipt");
28057        handle
28058            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
28059            .await
28060            .expect("handle selected-run signal receipt");
28061        let result = client
28062            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
28063            .await
28064            .expect("update result");
28065        assert_eq!(result, json!(42));
28066        handle
28067            .update("adjust", json!([1]), Some("handle-update-key"))
28068            .await
28069            .expect("handle update result");
28070        handle
28071            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
28072            .await
28073            .expect("handle typed update result");
28074
28075        let signal_keys: Vec<Value> = server
28076            .request_bodies(KEYED_SIGNAL_PATH)
28077            .into_iter()
28078            .map(|body| body["request_id"].clone())
28079            .collect();
28080        assert_eq!(
28081            signal_keys,
28082            [json!("Order-42/approve"), json!("handle-signal-key")]
28083        );
28084        let run_signal_keys: Vec<Value> = server
28085            .request_bodies(KEYED_RUN_SIGNAL_PATH)
28086            .into_iter()
28087            .map(|body| body["request_id"].clone())
28088            .collect();
28089        assert_eq!(
28090            run_signal_keys,
28091            [json!("run-signal-key"), json!("handle-run-signal-key")]
28092        );
28093        let update_keys: Vec<Value> = server
28094            .request_bodies(KEYED_UPDATE_PATH)
28095            .into_iter()
28096            .map(|body| body["request_id"].clone())
28097            .collect();
28098        assert_eq!(
28099            update_keys,
28100            [
28101                json!("update-key"),
28102                json!("handle-update-key"),
28103                json!("handle-typed-update-key")
28104            ]
28105        );
28106        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
28107            assert_key_sent_only_in_body(&server, path);
28108        }
28109    }
28110
28111    #[tokio::test]
28112    async fn retained_receipts_are_returned_unchanged() {
28113        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28114            request_override: Some(retained_command_server),
28115            ..MockWorkerBehavior::default()
28116        });
28117        let client = keyed_client(&server);
28118
28119        let receipt = client
28120            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
28121            .await
28122            .expect("retained receipt");
28123
28124        assert_eq!(
28125            receipt,
28126            json!({
28127                "outcome": "accepted",
28128                "command_status": "accepted",
28129                "command_id": "cmd-first",
28130                "request_id": "retry-key",
28131                "retained": true,
28132                "intent_verified": true,
28133            })
28134        );
28135    }
28136
28137    #[tokio::test]
28138    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
28139        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28140            request_override: Some(conflicting_command_server),
28141            ..MockWorkerBehavior::default()
28142        });
28143        let client = keyed_client(&server);
28144
28145        let error = client
28146            .signal_workflow_with_request_id(
28147                "keyed-1",
28148                "approve",
28149                json!(["changed"]),
28150                "Order-42/approve",
28151            )
28152            .await
28153            .expect_err("different intent under a retained key");
28154        assert!(
28155            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
28156            "existing Error::Http matching keeps working: {error:?}"
28157        );
28158        assert!(error.is_request_id_conflict());
28159        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
28160        let conflict = error.request_id_conflict().expect("conflict details");
28161        assert_eq!(conflict.status, 409);
28162        assert_eq!(conflict.request_id, "Order-42/approve");
28163        assert_eq!(
28164            conflict.message,
28165            "request id is retained for a different signal intent"
28166        );
28167        assert_eq!(
28168            conflict.retained_command_id.as_deref(),
28169            Some("cmd-retained-1")
28170        );
28171        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
28172        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
28173        assert_eq!(conflict.conflict, ["arguments", "target"]);
28174        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
28175
28176        let error = client
28177            .update_workflow("keyed-1", "adjust", json!([2]), None)
28178            .await
28179            .expect_err("different intent under a retained generated key");
28180        let sent = server.request_body(KEYED_UPDATE_PATH);
28181        assert_eq!(
28182            error.request_id(),
28183            sent["request_id"].as_str().map(str::to_string)
28184        );
28185        assert_eq!(
28186            error
28187                .request_id_conflict()
28188                .expect("conflict details")
28189                .retained_command_type
28190                .as_deref(),
28191            Some("update")
28192        );
28193    }
28194
28195    #[tokio::test]
28196    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
28197        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28198            request_override: Some(closed_run_command_server),
28199            ..MockWorkerBehavior::default()
28200        });
28201        let client = keyed_client(&server);
28202
28203        let error = client
28204            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
28205            .await
28206            .expect_err("closed run");
28207
28208        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
28209        assert!(!error.is_request_id_conflict());
28210        assert_eq!(error.request_id_conflict(), None);
28211        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
28212    }
28213
28214    #[tokio::test]
28215    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
28216        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28217            request_override: Some(keyed_command_server),
28218            drop_request: Some(drop_first_keyed_signal),
28219            ..MockWorkerBehavior::default()
28220        });
28221        let client = keyed_client(&server);
28222        let request_id = Client::generate_signal_request_id();
28223
28224        let error = client
28225            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28226            .await
28227            .expect_err("connection closed before any response");
28228        assert!(
28229            matches!(error, Error::Transport(_)),
28230            "the transport variant is unchanged: {error:?}"
28231        );
28232        assert_eq!(
28233            error.request_id(),
28234            None,
28235            "nothing was echoed; the application holds the key it chose"
28236        );
28237
28238        let receipt = client
28239            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28240            .await
28241            .expect("manual retry with the same key");
28242        assert_eq!(receipt["request_id"], request_id);
28243        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
28244        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
28245        assert_eq!(
28246            bodies[0], bodies[1],
28247            "the retry resends the identical key and input"
28248        );
28249        assert_eq!(bodies[0]["request_id"], request_id);
28250    }
28251
28252    #[tokio::test]
28253    async fn invalid_command_keys_are_refused_before_sending() {
28254        let server = MockWorkerServer::start();
28255        let client = keyed_client(&server);
28256        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
28257
28258        for request_id in ["", too_long.as_str()] {
28259            let error = client
28260                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
28261                .await
28262                .expect_err("invalid signal key");
28263            assert!(
28264                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
28265                "{error:?}"
28266            );
28267            let error = client
28268                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
28269                .await
28270                .expect_err("invalid update key");
28271            assert!(matches!(error, Error::Codec(_)), "{error:?}");
28272        }
28273        assert!(server.captured_paths().is_empty(), "nothing was sent");
28274
28275        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
28276        let _ = client
28277            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
28278            .await;
28279        assert_eq!(
28280            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
28281            longest
28282        );
28283    }
28284
28285    #[test]
28286    fn generated_command_keys_are_distinct_and_well_formed() {
28287        let signal = Client::generate_signal_request_id();
28288        let update = Client::generate_update_request_id();
28289        assert_generated_request_id(&signal, "sdk-rust-signal-");
28290        assert_generated_request_id(&update, "sdk-rust-update-");
28291        assert_ne!(Client::generate_signal_request_id(), signal);
28292        assert!(validate_request_id(&signal).is_ok());
28293    }
28294
28295    #[test]
28296    fn command_keys_preserve_the_published_server_unicode_character_limit() {
28297        assert!(validate_request_id(&"é".repeat(255)).is_ok());
28298        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
28299        assert!(validate_request_id(&"é".repeat(256)).is_err());
28300    }
28301
28302    #[test]
28303    fn request_id_accessors_read_only_echoed_refusal_bodies() {
28304        let conflict = Error::Http {
28305            status: reqwest::StatusCode::CONFLICT,
28306            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(),
28307        };
28308        assert!(conflict.is_request_id_conflict());
28309        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
28310        let details = conflict.request_id_conflict().expect("conflict details");
28311        assert_eq!(details.conflict, ["name"]);
28312        assert_eq!(
28313            details.message,
28314            "request id is retained for a different command intent"
28315        );
28316
28317        let echoed = Error::Http {
28318            status: reqwest::StatusCode::CONFLICT,
28319            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
28320        };
28321        assert!(!echoed.is_request_id_conflict());
28322        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
28323
28324        let blank = Error::Http {
28325            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
28326            body: r#"{"request_id":""}"#.to_string(),
28327        };
28328        assert_eq!(blank.request_id(), None);
28329        let text = Error::Http {
28330            status: reqwest::StatusCode::BAD_GATEWAY,
28331            body: "upstream unavailable".to_string(),
28332        };
28333        assert_eq!(text.request_id(), None);
28334        assert!(!text.is_request_id_conflict());
28335
28336        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
28337            command: WorkflowCommandKind::Cancel,
28338            status: 409,
28339            reason: "request_id_conflict".to_string(),
28340            message: "retained".to_string(),
28341            workflow_id: "wf".to_string(),
28342            run_id: None,
28343            target_scope: None,
28344            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
28345        });
28346        assert!(rejection.is_request_id_conflict());
28347        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
28348
28349        assert_eq!(Error::Timeout.request_id(), None);
28350        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
28351    }
28352
28353    #[tokio::test]
28354    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
28355        let server = MockWorkerServer::start();
28356        let client = Client::builder(server.base_url())
28357            .timeout(Duration::from_secs(2))
28358            .build()
28359            .expect("client");
28360        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
28361
28362        client
28363            .start_workflow(
28364                "typed.echo",
28365                "rust-workers",
28366                "typed-start",
28367                arguments.clone(),
28368            )
28369            .await
28370            .expect("typed workflow start");
28371        assert_eq!(
28372            decode_wire_avro_value(
28373                &server.request_body("/api/workflows")["input"],
28374                DEFAULT_CODEC,
28375            )
28376            .expect("typed start input"),
28377            arguments
28378        );
28379
28380        client
28381            .signal_workflow("typed-1", "changed", arguments.clone())
28382            .await
28383            .expect("typed signal");
28384        assert_eq!(
28385            decode_wire_avro_value(
28386                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
28387                DEFAULT_CODEC,
28388            )
28389            .expect("typed signal input"),
28390            arguments
28391        );
28392
28393        assert_eq!(
28394            client
28395                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
28396                .await
28397                .expect("typed query"),
28398            typed_fidelity_probe()
28399        );
28400        assert_eq!(
28401            decode_wire_avro_value(
28402                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
28403                DEFAULT_CODEC,
28404            )
28405            .expect("typed query input"),
28406            arguments
28407        );
28408
28409        assert_eq!(
28410            client
28411                .update_workflow_avro_value(
28412                    "typed-1",
28413                    "replace",
28414                    arguments.clone(),
28415                    Some("typed-request"),
28416                )
28417                .await
28418                .expect("typed update"),
28419            typed_fidelity_probe()
28420        );
28421        let update = server.request_body("/api/workflows/typed-1/update/replace");
28422        assert_eq!(update["request_id"], "typed-request");
28423        assert_eq!(
28424            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
28425            arguments
28426        );
28427
28428        let handle = WorkflowHandle {
28429            client: client.clone(),
28430            workflow_id: "typed-1".to_string(),
28431            run_id: Some("run-typed-1".to_string()),
28432            workflow_type: "typed.echo".to_string(),
28433        };
28434        assert_eq!(
28435            handle
28436                .result_avro_value(WorkflowResultOptions::default())
28437                .await
28438                .expect("typed workflow result"),
28439            typed_fidelity_probe()
28440        );
28441
28442        client
28443            .complete_activity_task(
28444                "activity-typed",
28445                "attempt-typed",
28446                "rust-worker",
28447                typed_fidelity_probe(),
28448                DEFAULT_CODEC,
28449            )
28450            .await
28451            .expect("typed activity completion");
28452        assert_eq!(
28453            decode_wire_avro_value(
28454                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
28455                    ["result"],
28456                DEFAULT_CODEC,
28457            )
28458            .expect("typed activity result"),
28459            typed_fidelity_probe()
28460        );
28461        client
28462            .fail_activity_task(
28463                "activity-typed",
28464                "attempt-typed",
28465                "rust-worker",
28466                "typed failure",
28467                true,
28468            )
28469            .await
28470            .expect("activity failure");
28471    }
28472
28473    #[tokio::test]
28474    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
28475        let server = MockWorkerServer::start();
28476        let client = Client::builder(server.base_url())
28477            .timeout(Duration::from_secs(2))
28478            .build()
28479            .expect("client");
28480
28481        let options = WorkflowCommandOptions::new()
28482            .reason("cleanup requested")
28483            .request_id("cancel-17");
28484        let cancelled = client
28485            .cancel_workflow("wf-lifecycle", options)
28486            .await
28487            .expect("instance cancellation");
28488        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
28489        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
28490        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
28491        assert_eq!(
28492            server.request_body("/api/workflows/wf-lifecycle/cancel"),
28493            json!({"reason":"cleanup requested","request_id":"cancel-17"})
28494        );
28495
28496        let terminated = client
28497            .terminate_workflow(
28498                "wf-lifecycle",
28499                WorkflowCommandOptions::new().reason("forced stop"),
28500            )
28501            .await
28502            .expect("instance termination");
28503        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
28504        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
28505
28506        client
28507            .cancel_workflow_run(
28508                "wf-lifecycle",
28509                "run-current",
28510                WorkflowCommandOptions::default(),
28511            )
28512            .await
28513            .expect("selected run cancellation");
28514        client
28515            .terminate_workflow_run(
28516                "wf-lifecycle",
28517                "run-current",
28518                WorkflowCommandOptions::default(),
28519            )
28520            .await
28521            .expect("selected run termination");
28522
28523        for (command, error) in [
28524            (
28525                WorkflowCommandKind::Cancel,
28526                client
28527                    .cancel_workflow_run(
28528                        "wf-lifecycle",
28529                        "run-stale",
28530                        WorkflowCommandOptions::default(),
28531                    )
28532                    .await
28533                    .expect_err("stale cancellation must be rejected"),
28534            ),
28535            (
28536                WorkflowCommandKind::Terminate,
28537                client
28538                    .terminate_workflow_run(
28539                        "wf-lifecycle",
28540                        "run-stale",
28541                        WorkflowCommandOptions::default(),
28542                    )
28543                    .await
28544                    .expect_err("stale termination must be rejected"),
28545            ),
28546        ] {
28547            let Error::WorkflowCommandRejected(rejection) = error else {
28548                panic!("expected typed command rejection");
28549            };
28550            assert_eq!(rejection.command, command);
28551            assert_eq!(rejection.status, 409);
28552            assert_eq!(rejection.reason, "historical_run_command_rejected");
28553            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
28554            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
28555        }
28556    }
28557
28558    #[tokio::test]
28559    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
28560        let server = MockWorkerServer::start();
28561        let client = Client::builder(server.base_url())
28562            .timeout(Duration::from_secs(2))
28563            .build()
28564            .expect("client");
28565
28566        let result = client
28567            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
28568            .await
28569            .expect("redrive accepted");
28570        assert_eq!(result.workflow_id, "wf-lifecycle");
28571        assert_eq!(result.source_run_id, "run-failed");
28572        assert_eq!(result.run_id, "run-successor");
28573        assert_eq!(result.resume_step_sequence, 2);
28574        assert_eq!(
28575            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
28576            json!({"request_id":"retry-1"})
28577        );
28578
28579        let repeated = client
28580            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
28581            .await
28582            .expect("idempotent redrive response accepted");
28583        assert_eq!(repeated.run_id, "run-successor");
28584
28585        let error = client
28586            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
28587            .await
28588            .expect_err("completed run must be rejected");
28589        let Error::Http { status, body } = error else {
28590            panic!("expected HTTP redrive rejection");
28591        };
28592        assert_eq!(status.as_u16(), 409);
28593        assert!(body.contains("run_not_failed"));
28594        assert_eq!(
28595            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
28596            json!({})
28597        );
28598
28599        let handle = WorkflowHandle {
28600            client: client.clone(),
28601            workflow_id: "wf-lifecycle".to_string(),
28602            run_id: Some("run-failed".to_string()),
28603            workflow_type: "test".to_string(),
28604        };
28605        assert_eq!(
28606            handle.redrive(None).await.expect("handle redrive").run_id,
28607            "run-successor"
28608        );
28609        let missing_run = WorkflowHandle {
28610            run_id: None,
28611            ..handle
28612        };
28613        assert!(matches!(
28614            missing_run.redrive(None).await,
28615            Err(Error::Codec(_))
28616        ));
28617    }
28618
28619    #[tokio::test]
28620    async fn workflow_start_options_send_server_enforced_deadlines() {
28621        let server = MockWorkerServer::start();
28622        let client = Client::builder(server.base_url())
28623            .timeout(Duration::from_secs(2))
28624            .build()
28625            .expect("client");
28626
28627        let handle = client
28628            .start_workflow_with_options(
28629                "rust.timeout",
28630                "rust-timeouts",
28631                "wf-start-options",
28632                WorkflowStartOptions::new()
28633                    .execution_timeout_seconds(30)
28634                    .run_timeout_seconds(1),
28635                json!([]),
28636            )
28637            .await
28638            .expect("workflow start");
28639
28640        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
28641        let body = server.request_body("/api/workflows");
28642        assert_eq!(body["execution_timeout_seconds"], 30);
28643        assert_eq!(body["run_timeout_seconds"], 1);
28644
28645        let invalid = client
28646            .start_workflow_with_options(
28647                "rust.timeout",
28648                "rust-timeouts",
28649                "wf-invalid-options",
28650                WorkflowStartOptions::new()
28651                    .execution_timeout_seconds(1)
28652                    .run_timeout_seconds(2),
28653                json!([]),
28654            )
28655            .await
28656            .expect_err("invalid deadline ordering");
28657        assert!(invalid
28658            .to_string()
28659            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
28660    }
28661
28662    #[tokio::test]
28663    async fn workflow_result_returns_each_typed_terminal_outcome() {
28664        let server = MockWorkerServer::start();
28665        let client = Client::builder(server.base_url())
28666            .timeout(Duration::from_secs(2))
28667            .build()
28668            .expect("client");
28669        let options = WorkflowResultOptions {
28670            poll_interval: Duration::ZERO,
28671            timeout: Duration::from_secs(1),
28672        };
28673
28674        let failed = WorkflowHandle {
28675            client: client.clone(),
28676            workflow_id: "wf-failed".to_string(),
28677            run_id: Some("run-failed".to_string()),
28678            workflow_type: "failure".to_string(),
28679        }
28680        .result(options)
28681        .await
28682        .expect_err("failed outcome");
28683        let Error::WorkflowFailed(failure) = failed else {
28684            panic!("expected WorkflowFailed");
28685        };
28686        assert_eq!(failure.workflow_id, "wf-failed");
28687        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
28688        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
28689        assert_eq!(failure.failure_category.as_deref(), Some("application"));
28690        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
28691        assert_eq!(
28692            failure.exception_class.as_deref(),
28693            Some("billing::PaymentError")
28694        );
28695        assert_eq!(failure.non_retryable, Some(true));
28696
28697        for (workflow_id, expected_kind, expected_reason) in [
28698            (
28699                "wf-cancelled",
28700                WorkflowTerminalKind::Cancelled,
28701                "cleanup requested",
28702            ),
28703            (
28704                "wf-terminated",
28705                WorkflowTerminalKind::Terminated,
28706                "forced stop",
28707            ),
28708            (
28709                "wf-timed-out",
28710                WorkflowTerminalKind::TimedOut,
28711                "run_timeout",
28712            ),
28713        ] {
28714            let error = WorkflowHandle {
28715                client: client.clone(),
28716                workflow_id: workflow_id.to_string(),
28717                run_id: None,
28718                workflow_type: "terminal".to_string(),
28719            }
28720            .result(options)
28721            .await
28722            .expect_err("typed terminal outcome");
28723            let outcome = match error {
28724                Error::WorkflowCancelled(outcome) => outcome,
28725                Error::WorkflowTerminated(outcome) => outcome,
28726                Error::WorkflowTimedOut(outcome) => outcome,
28727                other => panic!("unexpected terminal error: {other}"),
28728            };
28729            assert_eq!(outcome.kind, expected_kind);
28730            assert_eq!(outcome.workflow_id, workflow_id);
28731            assert_eq!(outcome.reason, expected_reason);
28732        }
28733
28734        let wait_timeout = WorkflowHandle {
28735            client,
28736            workflow_id: "wf-waiting".to_string(),
28737            run_id: Some("run-waiting".to_string()),
28738            workflow_type: "waiting".to_string(),
28739        }
28740        .result(WorkflowResultOptions {
28741            poll_interval: Duration::ZERO,
28742            timeout: Duration::ZERO,
28743        })
28744        .await
28745        .expect_err("client wait timeout");
28746        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
28747            panic!("expected typed client timeout");
28748        };
28749        assert_eq!(timeout.reason, "result_wait_timeout");
28750        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
28751        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
28752    }
28753
28754    #[tokio::test]
28755    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
28756        let server = MockWorkerServer::start();
28757        let client = Client::builder(server.base_url())
28758            .timeout(Duration::from_secs(2))
28759            .build()
28760            .expect("client");
28761
28762        let handle = WorkflowHandle {
28763            client,
28764            workflow_id: "wf-selected".to_string(),
28765            run_id: Some("run-selected".to_string()),
28766            workflow_type: "selected".to_string(),
28767        };
28768        let options = WorkflowResultOptions {
28769            poll_interval: Duration::ZERO,
28770            timeout: Duration::from_secs(1),
28771        };
28772
28773        let current = handle
28774            .result(options)
28775            .await
28776            .expect("instance result follows the current run");
28777        assert_eq!(current, json!("current run output"));
28778
28779        let error = handle
28780            .result_selected_run(options)
28781            .await
28782            .expect_err("the selected run is cancelled even though the current run completed");
28783
28784        let Error::WorkflowCancelled(outcome) = error else {
28785            panic!("expected selected run cancellation");
28786        };
28787        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
28788        assert_eq!(outcome.reason, "selected run cancelled");
28789        assert_eq!(
28790            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
28791            1
28792        );
28793        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
28794    }
28795
28796    #[tokio::test]
28797    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
28798        let server = MockWorkerServer::draining_polls();
28799        let client = Client::builder(server.base_url())
28800            .timeout(Duration::from_secs(2))
28801            .build()
28802            .expect("client");
28803
28804        let workflow = client
28805            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
28806            .await
28807            .expect("workflow drain response");
28808        let activity = client
28809            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
28810            .await
28811            .expect("activity drain response");
28812        let query = client
28813            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
28814            .await
28815            .expect("query drain response");
28816
28817        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
28818            assert_eq!(
28819                outcome,
28820                WorkerPollOutcome::Stop {
28821                    poll_status: Some("draining".to_string()),
28822                    reason: Some("worker_draining".to_string()),
28823                }
28824            );
28825        }
28826
28827        assert!(client
28828            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
28829            .await
28830            .expect("compatibility poll")
28831            .is_none());
28832    }
28833
28834    #[tokio::test]
28835    async fn managed_worker_honors_drain_stop_for_every_task_family() {
28836        let server = MockWorkerServer::draining_polls();
28837        let client = Client::builder(server.base_url())
28838            .timeout(Duration::from_secs(2))
28839            .build()
28840            .expect("client");
28841
28842        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
28843            .worker_id("draining-workflow-worker")
28844            .poll_timeout(Duration::ZERO);
28845        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
28846        workflow_worker
28847            .run()
28848            .await
28849            .expect("workflow drain is a clean stop");
28850
28851        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
28852            .worker_id("draining-activity-worker")
28853            .poll_timeout(Duration::ZERO);
28854        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
28855        activity_worker
28856            .run()
28857            .await
28858            .expect("activity drain is a clean stop");
28859
28860        let mut query_worker = Worker::new(client, "rust-workers")
28861            .worker_id("draining-query-worker")
28862            .poll_timeout(Duration::ZERO);
28863        query_worker.register_query("counter", "current", |_ctx, _args| async {
28864            Ok(Value::Null)
28865        });
28866        query_worker
28867            .run()
28868            .await
28869            .expect("query drain is a clean stop");
28870    }
28871
28872    #[tokio::test]
28873    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
28874        let server = MockWorkerServer::start();
28875        let client = Client::builder(server.base_url())
28876            .timeout(Duration::from_secs(2))
28877            .build()
28878            .expect("client");
28879
28880        let details: Value = serde_json::from_str(include_str!(
28881            "../tests/fixtures/activity-heartbeat-progress.json"
28882        ))
28883        .expect("heartbeat progress fixture");
28884        // Every individual field fits Server's progress contract, while the
28885        // obsolete encoded envelope exceeded its 191-character string limit.
28886        assert!(
28887            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
28888                .unwrap()["blob"]
28889                .as_str()
28890                .unwrap()
28891                .len()
28892                > 191
28893        );
28894        let heartbeat = client
28895            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
28896            .await
28897            .expect("cancellation heartbeat");
28898        assert!(heartbeat.cancel_requested);
28899        assert!(heartbeat.should_stop());
28900        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
28901        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
28902        let heartbeat_body =
28903            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
28904        assert_eq!(heartbeat_body["details"], details);
28905        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
28906        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
28907
28908        let error = client
28909            .complete_activity_task(
28910                "activity-cancel",
28911                "attempt-cancel",
28912                "rust-worker",
28913                json!({"late":true}),
28914                DEFAULT_CODEC,
28915            )
28916            .await
28917            .expect_err("late completion must be refused");
28918        assert!(activity_task_rejection_is_final(&error));
28919        let Error::ActivityTaskRejected(rejection) = error else {
28920            panic!("expected typed activity rejection");
28921        };
28922        assert_eq!(rejection.status, 409);
28923        assert_eq!(rejection.reason, "run_cancelled");
28924        assert!(rejection.cancel_requested);
28925        assert_eq!(rejection.can_continue, Some(false));
28926    }
28927
28928    #[tokio::test]
28929    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
28930        let server = MockWorkerServer::cancelled_activity();
28931        let client = Client::builder(server.base_url())
28932            .timeout(Duration::from_secs(2))
28933            .build()
28934            .expect("client");
28935        let cancellation_observed = Arc::new(AtomicBool::new(false));
28936        let observed = Arc::clone(&cancellation_observed);
28937        let mut worker = Worker::new(client.clone(), "rust-workers")
28938            .worker_id("rust-cancel-worker")
28939            .poll_timeout(Duration::from_millis(10));
28940        worker.register_activity("cancel-aware", move |ctx, _args| {
28941            let observed = Arc::clone(&observed);
28942            async move {
28943                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
28944                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
28945                Ok(json!({"late":"completion"}))
28946            }
28947        });
28948
28949        assert_eq!(
28950            worker.run_once().await.expect("cancelled attempt handled"),
28951            1
28952        );
28953        assert!(cancellation_observed.load(Ordering::SeqCst));
28954        assert_eq!(
28955            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
28956            1
28957        );
28958
28959        let mut restarted = Worker::new(client, "rust-workers")
28960            .worker_id("rust-cancel-worker-restarted")
28961            .poll_timeout(Duration::from_millis(10));
28962        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
28963        assert_eq!(
28964            restarted
28965                .run_once()
28966                .await
28967                .expect("replacement worker continues polling"),
28968            0
28969        );
28970    }
28971
28972    #[tokio::test]
28973    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
28974        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"}"#;
28975        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
28976        let client = Client::builder(server.base_url())
28977            .timeout(Duration::from_secs(2))
28978            .build()
28979            .expect("client");
28980
28981        let direct_error = client
28982            .complete_workflow_task(
28983                "workflow-timeout-task",
28984                "timeout-worker",
28985                3,
28986                vec![json!({
28987                    "type": "complete_workflow",
28988                    "result": fixture_envelope(Value::Null)
28989                })],
28990            )
28991            .await
28992            .expect_err("the low-level client preserves the completion rejection");
28993        let Error::Http { status, body } = direct_error else {
28994            panic!("expected the original HTTP completion rejection");
28995        };
28996        assert_eq!(status, reqwest::StatusCode::CONFLICT);
28997        assert_eq!(
28998            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
28999            "run_timed_out"
29000        );
29001
29002        let mut worker = Worker::new(client, "rust-workers")
29003            .worker_id("timeout-worker")
29004            .poll_timeout(Duration::from_millis(10));
29005        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29006            Ok(json!({"late": "result"}))
29007        });
29008
29009        assert_eq!(
29010            worker
29011                .run_once()
29012                .await
29013                .expect("authoritative selected-run timeout settles the tick"),
29014            1
29015        );
29016        assert_eq!(
29017            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
29018            2,
29019            "both the direct client proof and managed worker must see the rejection"
29020        );
29021    }
29022
29023    #[tokio::test]
29024    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
29025        for (name, status, response) in [
29026            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
29027            (
29028                "command was recorded",
29029                "409 Conflict",
29030                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29031            ),
29032            (
29033                "lease conflict",
29034                "409 Conflict",
29035                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
29036            ),
29037            (
29038                "nonterminal run",
29039                "409 Conflict",
29040                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
29041            ),
29042            (
29043                "different selected run",
29044                "409 Conflict",
29045                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"}"#,
29046            ),
29047            (
29048                "different task attempt",
29049                "409 Conflict",
29050                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29051            ),
29052            (
29053                "authentication failure",
29054                "401 Unauthorized",
29055                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29056            ),
29057            (
29058                "authorization failure",
29059                "403 Forbidden",
29060                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29061            ),
29062            (
29063                "protocol failure",
29064                "400 Bad Request",
29065                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
29066            ),
29067            (
29068                "malformed command",
29069                "422 Unprocessable Entity",
29070                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29071            ),
29072            (
29073                "transient server failure",
29074                "503 Service Unavailable",
29075                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29076            ),
29077        ] {
29078            let server = MockWorkerServer::workflow_completion(status, response);
29079            let client = Client::builder(server.base_url())
29080                .timeout(Duration::from_secs(2))
29081                .build()
29082                .expect("client");
29083            let mut worker = Worker::new(client, "rust-workers")
29084                .worker_id("timeout-worker")
29085                .poll_timeout(Duration::from_millis(10));
29086            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29087                Ok(json!({"late": "result"}))
29088            });
29089
29090            let error = worker
29091                .run_once()
29092                .await
29093                .expect_err(&format!("{name} must remain an error"));
29094            assert!(
29095                matches!(error, Error::Http { .. } | Error::Protocol(_)),
29096                "{name} returned an unexpected error variant: {error}"
29097            );
29098        }
29099    }
29100
29101    #[tokio::test]
29102    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
29103        let server = MockWorkerServer::start();
29104        let client = Client::builder(server.base_url())
29105            .worker_token(Some("worker-secret".to_string()))
29106            .namespace("orders")
29107            .timeout(Duration::from_secs(2))
29108            .build()
29109            .expect("client");
29110        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
29111
29112        let result = client
29113            .deregister_worker_registration("worker/α space")
29114            .await
29115            .expect("deregister worker registration");
29116
29117        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
29118        assert_eq!(
29119            server.worker_protocol_for(path).as_deref(),
29120            Some(WORKER_PROTOCOL_VERSION)
29121        );
29122        assert_eq!(server.control_protocol_for(path), None);
29123        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
29124        assert_eq!(
29125            server.authorization_for(path).as_deref(),
29126            Some("Bearer worker-secret")
29127        );
29128        assert_eq!(
29129            result,
29130            WorkerDeregistrationEnvelope {
29131                worker_id: "deregistered-worker".to_string(),
29132                outcome: "deregistered".to_string(),
29133                recovered_workflow_task_count: 2,
29134            }
29135        );
29136    }
29137
29138    #[tokio::test]
29139    async fn low_level_registration_rejects_update_validators_before_transport() {
29140        let server = MockWorkerServer::start();
29141        let client = Client::builder(server.base_url())
29142            .timeout(Duration::from_secs(2))
29143            .build()
29144            .expect("client");
29145
29146        for update_validators in [json!(["approve"]), json!("approve")] {
29147            let error = client
29148                .register_worker_with_command_contracts(
29149                    "validator-claiming-worker",
29150                    "rust-workers",
29151                    vec!["orders".to_string()],
29152                    vec![],
29153                    1,
29154                    1,
29155                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29156                    json!({
29157                        "orders": {
29158                            "queries": ["current"],
29159                            "updates": ["approve"],
29160                            "update_validators": update_validators,
29161                        },
29162                    }),
29163                )
29164                .await
29165                .expect_err("unsupported validator claims must fail before registration");
29166
29167            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
29168                panic!("expected typed unsupported-validator failure");
29169            };
29170            assert_eq!(workflow_type, "orders");
29171        }
29172        assert_eq!(server.request_count("/api/worker/register"), 0);
29173    }
29174
29175    #[tokio::test]
29176    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
29177        let server = MockWorkerServer::start();
29178        let client = Client::builder(server.base_url())
29179            .timeout(Duration::from_secs(2))
29180            .build()
29181            .expect("client");
29182        let mut worker = Worker::new(client, "rust-workers");
29183        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
29184        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
29185        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29186        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
29187        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29188        worker
29189            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
29190            .expect("declare workflow signals");
29191
29192        worker.register().await.expect("register handler contracts");
29193
29194        let declaration =
29195            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
29196        let expected_contracts = json!([
29197            {
29198                "name": "a-avro",
29199                "parameters": [{
29200                    "name": "args", "position": 0, "required": false,
29201                    "variadic": true, "type": null, "allows_null": true,
29202                    "default_available": false, "default": null,
29203                }],
29204            },
29205            {
29206                "name": "z-json",
29207                "parameters": [{
29208                    "name": "args", "position": 0, "required": false,
29209                    "variadic": true, "type": null, "allows_null": true,
29210                    "default_available": false, "default": null,
29211                }],
29212            },
29213        ]);
29214        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
29215        assert_eq!(declaration["query_contracts"], expected_contracts);
29216        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
29217        assert_eq!(declaration["update_contracts"], expected_contracts);
29218        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
29219        assert_eq!(declaration["signal_contracts"], expected_contracts);
29220        assert_eq!(declaration["update_validators"], json!([]));
29221    }
29222
29223    #[tokio::test]
29224    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
29225        let server = MockWorkerServer::start();
29226        let client = Client::new(server.base_url()).expect("client");
29227        let mut worker = Worker::new(client, "rust-workers");
29228        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
29229        assert!(worker
29230            .declare_workflow_signals("missing", &["finish"])
29231            .is_err());
29232        worker
29233            .declare_workflow_signals("orders", &["finish"])
29234            .unwrap();
29235        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
29236            assert!(worker.declare_workflow_signals("orders", names).is_err());
29237        }
29238        worker.register().await.unwrap();
29239        assert_eq!(
29240            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
29241                ["signals"],
29242            json!(["finish"])
29243        );
29244        worker.declare_workflow_signals("orders", &[]).unwrap();
29245        worker.register().await.unwrap();
29246        let registrations = server.request_bodies("/api/worker/register");
29247        assert_eq!(
29248            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
29249            json!([])
29250        );
29251        assert_eq!(
29252            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
29253            json!([])
29254        );
29255    }
29256
29257    #[tokio::test]
29258    async fn low_level_registration_preserves_query_and_update_contracts() {
29259        let server = MockWorkerServer::start();
29260        let client = Client::builder(server.base_url())
29261            .timeout(Duration::from_secs(2))
29262            .build()
29263            .expect("client");
29264        let contracts = json!({
29265            "orders": {
29266                "queries": ["current"],
29267                "updates": ["approve"],
29268                "update_validators": [],
29269            },
29270            "payments": {
29271                "queries": ["status"],
29272                "updates": ["capture"],
29273            },
29274        });
29275
29276        client
29277            .register_worker_with_command_contracts(
29278                "command-worker",
29279                "rust-workers",
29280                vec!["orders".to_string(), "payments".to_string()],
29281                vec![],
29282                1,
29283                1,
29284                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29285                contracts.clone(),
29286            )
29287            .await
29288            .expect("query and update contracts must remain supported");
29289
29290        assert_eq!(
29291            server.request_body("/api/worker/register")["workflow_command_contracts"],
29292            contracts
29293        );
29294        assert!(server
29295            .request_body("/api/worker/register")
29296            .get("workflow_definition_fingerprints")
29297            .is_none());
29298    }
29299
29300    #[tokio::test]
29301    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
29302        let server = MockWorkerServer::start();
29303        let client = Client::builder(server.base_url())
29304            .timeout(Duration::from_secs(2))
29305            .build()
29306            .expect("client");
29307        let mut worker = Worker::new(client.clone(), "rust-workers");
29308        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29309
29310        assert!(worker
29311            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
29312            .is_err());
29313        assert!(worker
29314            .set_workflow_definition_sources("orders", &[])
29315            .is_err());
29316        worker
29317            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
29318            .expect("embed workflow source");
29319        worker.register().await.expect("register worker");
29320        let first = server.request_bodies("/api/worker/register")[0]
29321            ["workflow_definition_fingerprints"]["orders"]
29322            .as_str()
29323            .expect("source-backed fingerprint")
29324            .to_string();
29325        assert!(first.starts_with("sha256:"));
29326
29327        worker
29328            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
29329            .expect("change embedded helper source");
29330        worker.register().await.expect("register changed source");
29331        let changed = server.request_bodies("/api/worker/register")[1]
29332            ["workflow_definition_fingerprints"]["orders"]
29333            .as_str()
29334            .expect("changed fingerprint")
29335            .to_string();
29336        assert_ne!(first, changed);
29337
29338        let mut replacement =
29339            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
29340        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29341        replacement
29342            .register()
29343            .await
29344            .expect("register replacement handler");
29345        assert_eq!(
29346            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
29347            json!({})
29348        );
29349    }
29350
29351    #[tokio::test]
29352    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
29353        let server = MockWorkerServer::start();
29354        let control_only = Client::builder(server.base_url())
29355            .control_token(Some("control-secret".to_string()))
29356            .build()
29357            .expect("control client");
29358
29359        let error = control_only
29360            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29361            .await
29362            .expect_err("control token must not authorize a worker request");
29363        assert!(matches!(
29364            error,
29365            Error::MissingRoleCredentials { role: "worker", .. }
29366        ));
29367        assert_eq!(server.request_count("/api/worker/register"), 0);
29368
29369        let worker_only = Client::builder(server.base_url())
29370            .worker_token(Some("worker-secret".to_string()))
29371            .build()
29372            .expect("worker client");
29373        let error = worker_only
29374            .health()
29375            .await
29376            .expect_err("worker token must not authorize a control request");
29377        assert!(matches!(
29378            error,
29379            Error::MissingRoleCredentials {
29380                role: "control",
29381                ..
29382            }
29383        ));
29384        assert_eq!(server.request_count("/api/health"), 0);
29385    }
29386
29387    #[tokio::test]
29388    async fn shared_token_supports_worker_and_control_planes() {
29389        let server = MockWorkerServer::start();
29390        let client = Client::builder(server.base_url())
29391            .token(Some("shared-secret".to_string()))
29392            .build()
29393            .expect("client");
29394
29395        client.health().await.expect("control request");
29396        client
29397            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29398            .await
29399            .expect("worker request");
29400
29401        assert_eq!(
29402            server.authorization_for("/api/health").as_deref(),
29403            Some("Bearer shared-secret")
29404        );
29405        assert_eq!(
29406            server.control_protocol_for("/api/health").as_deref(),
29407            Some(CONTROL_PLANE_VERSION)
29408        );
29409        assert_eq!(
29410            server.authorization_for("/api/worker/register").as_deref(),
29411            Some("Bearer shared-secret")
29412        );
29413        assert_eq!(
29414            server
29415                .worker_protocol_for("/api/worker/register")
29416                .as_deref(),
29417            Some(WORKER_PROTOCOL_VERSION)
29418        );
29419    }
29420
29421    #[tokio::test]
29422    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
29423        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
29424        let server = MockWorkerServer::start();
29425        let client = Client::builder(server.base_url())
29426            .timeout(Duration::from_secs(2))
29427            .build()
29428            .expect("client");
29429
29430        client
29431            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
29432            .await
29433            .expect("register");
29434        client
29435            .heartbeat_worker("capture-worker", 1, 1)
29436            .await
29437            .expect("heartbeat");
29438        client
29439            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29440            .await
29441            .expect("workflow poll");
29442        client
29443            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29444            .await
29445            .expect("activity poll");
29446
29447        for path in [
29448            "/api/worker/register",
29449            "/api/worker/heartbeat",
29450            "/api/worker/workflow-tasks/poll",
29451            "/api/worker/activity-tasks/poll",
29452        ] {
29453            assert_eq!(
29454                server.worker_protocol_for(path).as_deref(),
29455                Some(WORKER_PROTOCOL_VERSION),
29456                "unexpected protocol for {path}"
29457            );
29458        }
29459
29460        assert_eq!(
29461            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
29462            1
29463        );
29464        assert_eq!(
29465            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
29466            500
29467        );
29468        assert_eq!(
29469            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
29470            1
29471        );
29472        assert!(
29473            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
29474                .as_str()
29475                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
29476        );
29477        assert!(
29478            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
29479                .as_str()
29480                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
29481        );
29482        let registration = server.request_body("/api/worker/register");
29483        for optional in [
29484            "cooperative_cancellation",
29485            "local_activities",
29486            "worker_sessions",
29487            "sticky_execution",
29488        ] {
29489            assert!(!registration["capabilities"]
29490                .as_array()
29491                .is_some_and(|capabilities| capabilities
29492                    .iter()
29493                    .any(|capability| capability.as_str() == Some(optional))));
29494        }
29495    }
29496
29497    #[tokio::test]
29498    async fn explicit_previous_worker_protocol_preserves_headers() {
29499        let server = MockWorkerServer::start();
29500        let client = Client::builder(server.base_url())
29501            .worker_protocol_version(WorkerProtocolVersion::V119)
29502            .timeout(Duration::from_secs(2))
29503            .build()
29504            .expect("client");
29505        client
29506            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
29507            .await
29508            .expect("register");
29509        client
29510            .heartbeat_worker("legacy-worker", 1, 1)
29511            .await
29512            .expect("heartbeat");
29513        client
29514            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
29515            .await
29516            .expect("workflow poll");
29517        client
29518            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
29519            .await
29520            .expect("activity poll");
29521        client
29522            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
29523            .await
29524            .expect("query poll");
29525        client
29526            .deregister_worker_registration("legacy-worker")
29527            .await
29528            .expect("deregister");
29529        for path in [
29530            "/api/worker/register",
29531            "/api/worker/heartbeat",
29532            "/api/worker/workflow-tasks/poll",
29533            "/api/worker/activity-tasks/poll",
29534            "/api/worker/query-tasks/poll",
29535            "/api/worker/registrations/legacy-worker",
29536        ] {
29537            assert_eq!(
29538                server.worker_protocol_for(path).as_deref(),
29539                Some("1.19"),
29540                "{path}"
29541            );
29542            assert_eq!(server.control_protocol_for(path), None, "{path}");
29543        }
29544    }
29545
29546    #[tokio::test]
29547    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
29548        let server = MockWorkerServer::start();
29549        let client = Client::builder(server.base_url())
29550            .worker_protocol_version(WorkerProtocolVersion::V119)
29551            .timeout(Duration::from_secs(2))
29552            .build()
29553            .expect("client");
29554        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
29555        let error = worker
29556            .register()
29557            .await
29558            .expect_err("legacy cooperation must be refused");
29559        assert!(matches!(
29560            error,
29561            Error::CooperativeCancellationUnavailable(_)
29562        ));
29563        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
29564    }
29565
29566    #[tokio::test]
29567    async fn query_task_endpoints_send_the_selected_worker_protocol() {
29568        let server = MockWorkerServer::start();
29569        let client = Client::builder(server.base_url())
29570            .timeout(Duration::from_secs(2))
29571            .build()
29572            .expect("client");
29573
29574        client
29575            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29576            .await
29577            .expect("query poll");
29578        client
29579            .complete_query_task(
29580                "query-capture",
29581                "capture-worker",
29582                1,
29583                json!(8),
29584                DEFAULT_CODEC,
29585            )
29586            .await
29587            .expect("query complete");
29588        client
29589            .fail_query_task(
29590                "query-capture",
29591                "capture-worker",
29592                1,
29593                "failed",
29594                "query_rejected",
29595                "QueryFailed",
29596            )
29597            .await
29598            .expect("query fail");
29599
29600        for path in [
29601            "/api/worker/query-tasks/poll",
29602            "/api/worker/query-tasks/query-capture/complete",
29603            "/api/worker/query-tasks/query-capture/fail",
29604        ] {
29605            assert_eq!(
29606                server.worker_protocol_for(path).as_deref(),
29607                Some(WORKER_PROTOCOL_VERSION),
29608                "unexpected protocol for {path}"
29609            );
29610        }
29611
29612        assert_eq!(
29613            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
29614            1
29615        );
29616        assert!(
29617            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
29618                .as_str()
29619                .is_some_and(|id| id.starts_with("rust-query-poll-"))
29620        );
29621    }
29622
29623    #[tokio::test]
29624    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
29625        let server = MockWorkerServer::transient_worker_failures();
29626        let client = Client::builder(server.base_url())
29627            .timeout(Duration::from_secs(2))
29628            .build()
29629            .expect("client");
29630
29631        client
29632            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29633            .await
29634            .expect("workflow poll retry");
29635        client
29636            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29637            .await
29638            .expect("activity poll retry");
29639        client
29640            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29641            .await
29642            .expect("query poll retry");
29643
29644        for path in [
29645            "/api/worker/workflow-tasks/poll",
29646            "/api/worker/activity-tasks/poll",
29647            "/api/worker/query-tasks/poll",
29648        ] {
29649            let bodies = server.request_bodies(path);
29650            assert_eq!(bodies.len(), 2, "{path} must be retried once");
29651            assert_eq!(
29652                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
29653                "{path} must preserve the request binding across retry"
29654            );
29655        }
29656    }
29657
29658    #[tokio::test]
29659    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
29660        let server = MockWorkerServer::consecutive_poll_failures(2);
29661        let client = Client::builder(server.base_url())
29662            .timeout(Duration::from_secs(2))
29663            .build()
29664            .expect("client");
29665        let mut worker = Worker::new(client, "capture")
29666            .worker_id("capture-worker")
29667            .poll_timeout(Duration::from_millis(10))
29668            .retry_policy(WorkerRetryPolicy {
29669                max_retries: 2,
29670                initial_backoff: Duration::from_millis(1),
29671                max_backoff: Duration::from_millis(1),
29672            });
29673        worker.register_workflow(
29674            "capture.workflow",
29675            |_ctx, _input| async move { Ok(Value::Null) },
29676        );
29677        worker.register_activity(
29678            "capture.activity",
29679            |_ctx, _input| async move { Ok(Value::Null) },
29680        );
29681        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
29682            Ok(Value::Null)
29683        });
29684
29685        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
29686
29687        for path in [
29688            "/api/worker/workflow-tasks/poll",
29689            "/api/worker/activity-tasks/poll",
29690            "/api/worker/query-tasks/poll",
29691        ] {
29692            let bodies = server.request_bodies(path);
29693            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
29694            assert!(
29695                bodies
29696                    .iter()
29697                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
29698                "{path} must preserve one request binding across every retry"
29699            );
29700        }
29701    }
29702
29703    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
29704        let reason = if unavailable {
29705            "storage_admission_unavailable"
29706        } else {
29707            "storage_pressure"
29708        };
29709        let mut body = json!({
29710            "reason": reason,
29711            "storage_state": if unavailable { "fenced" } else { "draining" },
29712            "retryable": true,
29713            "retry_after_seconds": 1,
29714        });
29715        if !mid_poll {
29716            body["request_admitted"] = json!(false);
29717        }
29718        if let Some(id) = poll_id {
29719            body["task"] = Value::Null;
29720            body["poll_status"] = json!(reason);
29721            body["poll_request_id"] = json!(id);
29722            body["retry_same_poll_request_id"] = json!(true);
29723            body["claim_admitted"] = json!(false);
29724        }
29725        body
29726    }
29727
29728    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
29729        let operation = match path {
29730            "/api/worker/register" => "register_worker",
29731            "/api/worker/heartbeat" => "heartbeat_worker",
29732            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
29733            "/api/worker/activity-tasks/poll" => "poll_activity_task",
29734            "/api/worker/query-tasks/poll" => "poll_query_task",
29735            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
29736            _ => return None,
29737        };
29738        let request: Value = serde_json::from_str(request).ok()?;
29739        let mut response = json!({
29740            "reason": "backend_unavailable",
29741            "operation": operation,
29742            "outcome": "unknown",
29743            "retryable": true,
29744            "retry_after_seconds": 1,
29745            "worker_id": request["worker_id"],
29746            "task_queue": request.get("task_queue"),
29747        });
29748        if path.ends_with("/poll") {
29749            response["task"] = Value::Null;
29750            response["poll_status"] = json!("backend_unavailable");
29751            response["poll_request_id"] = request["poll_request_id"].clone();
29752            response["retry_same_poll_request_id"] = json!(true);
29753        }
29754        Some(response)
29755    }
29756
29757    fn backend_retry_override(
29758        path: &str,
29759        request: &str,
29760        number: usize,
29761    ) -> Option<(&'static str, String)> {
29762        if number > 8 {
29763            return None;
29764        }
29765        Some((
29766            "503 Service Unavailable",
29767            backend_refusal(path, request)?.to_string(),
29768        ))
29769    }
29770
29771    fn backend_unavailable_override(
29772        path: &str,
29773        request: &str,
29774        _number: usize,
29775    ) -> Option<(&'static str, String)> {
29776        Some((
29777            "503 Service Unavailable",
29778            backend_refusal(path, request)?.to_string(),
29779        ))
29780    }
29781
29782    fn storage_worker(server: &MockWorkerServer) -> Worker {
29783        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
29784            .worker_id("storage-worker")
29785            .retry_policy(WorkerRetryPolicy {
29786                max_retries: 1,
29787                initial_backoff: Duration::from_millis(1),
29788                max_backoff: Duration::from_millis(1),
29789            })
29790    }
29791
29792    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
29793        let requests = server.requests.lock().expect("requests");
29794        let bodies: Vec<_> = requests
29795            .iter()
29796            .filter(|request| request.path == path)
29797            .map(|request| &request.body)
29798            .collect();
29799        assert_eq!(bodies.len(), count, "{path}");
29800        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
29801    }
29802
29803    #[test]
29804    fn backend_recovery_requires_the_explicit_worker_contract() {
29805        for (path, operation) in [
29806            ("/worker/register", "register_worker"),
29807            ("/worker/heartbeat", "heartbeat_worker"),
29808            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
29809            ("/worker/activity-tasks/poll", "poll_activity_task"),
29810            ("/worker/query-tasks/poll", "poll_query_task"),
29811            (
29812                "/worker/update-validation-tasks/poll",
29813                "poll_update_validation_task",
29814            ),
29815        ] {
29816            let poll_id = path.ends_with("/poll").then_some("same-poll");
29817            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
29818            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
29819                .expect("worker operation");
29820            assert_eq!(body["operation"], operation);
29821            let error = Error::Http {
29822                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29823                body: body.to_string(),
29824            };
29825            assert_eq!(
29826                worker_backend_unavailable_retry_after(&error, path, poll_id),
29827                Some(Duration::from_secs(1))
29828            );
29829            assert!(!worker_operation_is_retryable(&error));
29830            for (field, value) in [
29831                ("operation", json!("wrong_operation")),
29832                ("outcome", json!("completed")),
29833                ("retryable", json!(false)),
29834                ("retry_after_seconds", json!(0)),
29835                ("worker_id", json!("")),
29836            ] {
29837                let mut invalid = body.clone();
29838                invalid[field] = value;
29839                let error = Error::Http {
29840                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29841                    body: invalid.to_string(),
29842                };
29843                assert!(
29844                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
29845                    "{path}: {field}"
29846                );
29847                assert!(!worker_operation_is_retryable(&error));
29848            }
29849            if let Some(poll_id) = poll_id {
29850                for (field, value) in [
29851                    ("poll_request_id", json!("wrong-poll")),
29852                    ("poll_status", json!("empty")),
29853                    ("task", json!({"task_id":"claimed"})),
29854                    ("retry_same_poll_request_id", json!(false)),
29855                ] {
29856                    let mut invalid = body.clone();
29857                    invalid[field] = value;
29858                    let error = Error::Http {
29859                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29860                        body: invalid.to_string(),
29861                    };
29862                    assert!(
29863                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
29864                            .is_none(),
29865                        "{path}: {field}"
29866                    );
29867                }
29868            }
29869            let error = Error::Http {
29870                status: reqwest::StatusCode::UNAUTHORIZED,
29871                body: body.to_string(),
29872            };
29873            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
29874            assert!(!worker_operation_is_retryable(&error));
29875        }
29876    }
29877
29878    #[tokio::test]
29879    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
29880        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29881            request_override: Some(backend_retry_override),
29882            ..MockWorkerBehavior::default()
29883        });
29884        let mut worker =
29885            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
29886        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29887        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
29888        worker.register_query("backend.workflow", "state", |_, _| async {
29889            Ok(Value::Null)
29890        });
29891        worker.register().await.expect("registration recovery");
29892        worker
29893            .client
29894            .heartbeat_worker("storage-worker", 1, 1)
29895            .await
29896            .expect("heartbeat recovery");
29897        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
29898        for path in [
29899            "/api/worker/register",
29900            "/api/worker/heartbeat",
29901            "/api/worker/workflow-tasks/poll",
29902            "/api/worker/activity-tasks/poll",
29903            "/api/worker/query-tasks/poll",
29904        ] {
29905            assert_identical_requests(&server, path, 9);
29906        }
29907    }
29908
29909    #[tokio::test]
29910    async fn backend_recovery_wait_stops_with_worker() {
29911        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29912            request_override: Some(backend_unavailable_override),
29913            ..MockWorkerBehavior::default()
29914        });
29915        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
29916            max_retries: 1,
29917            initial_backoff: Duration::from_secs(2),
29918            max_backoff: Duration::from_secs(2),
29919        });
29920        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29921        let started = tokio::time::Instant::now();
29922        let _ = tokio::time::timeout(
29923            Duration::from_secs(1),
29924            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
29925        )
29926        .await
29927        .expect("shutdown interrupts backend wait");
29928        assert!(started.elapsed() < Duration::from_secs(1));
29929        assert!(server.request_count("/api/worker/register") >= 1);
29930    }
29931
29932    #[test]
29933    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
29934        for unavailable in [false, true] {
29935            for mid_poll in [false, true] {
29936                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
29937                let error = Error::Http {
29938                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29939                    body: body.to_string(),
29940                };
29941                assert_eq!(
29942                    worker_storage_admission_retry_after(&error, Some("same-poll")),
29943                    Some(Duration::from_secs(1))
29944                );
29945                assert!(
29946                    !worker_operation_is_retryable(&error),
29947                    "storage is not a bounded generic retry"
29948                );
29949                for (field, value) in [
29950                    ("poll_request_id", json!("wrong-poll")),
29951                    ("task", json!({"task_id":"claimed"})),
29952                    ("retryable", json!(false)),
29953                    ("retry_after_seconds", json!(0)),
29954                    ("retry_after_seconds", json!(true)),
29955                    ("retry_after_seconds", json!(1.0)),
29956                    ("storage_state", json!("normal")),
29957                    ("poll_status", json!("empty")),
29958                    ("claim_admitted", json!(true)),
29959                    ("retry_same_poll_request_id", json!(false)),
29960                    ("request_admitted", json!(true)),
29961                ] {
29962                    let mut invalid = body.clone();
29963                    invalid[field] = value;
29964                    let error = Error::Http {
29965                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29966                        body: invalid.to_string(),
29967                    };
29968                    assert!(
29969                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
29970                        "{field}"
29971                    );
29972                }
29973            }
29974        }
29975        let body = storage_refusal(None, false, false);
29976        let error = Error::Http {
29977            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29978            body: body.to_string(),
29979        };
29980        assert!(worker_storage_admission_retry_after(&error, None).is_some());
29981        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
29982        let error = Error::Http {
29983            status: reqwest::StatusCode::FORBIDDEN,
29984            body: body.to_string(),
29985        };
29986        assert!(worker_storage_admission_retry_after(&error, None).is_none());
29987        let body = storage_refusal(None, false, true);
29988        let error = Error::Http {
29989            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29990            body: body.to_string(),
29991        };
29992        assert!(worker_storage_admission_retry_after(&error, None).is_none());
29993    }
29994
29995    #[tokio::test]
29996    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
29997        for unavailable in [false, true] {
29998            for mid_poll in [false, true] {
29999                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30000                    poll_failures_per_path: 1,
30001                    storage_refusals: 7,
30002                    storage_path: Some("/poll"),
30003                    storage_unavailable: unavailable,
30004                    storage_mid_poll: mid_poll,
30005                    ..MockWorkerBehavior::default()
30006                });
30007                let mut worker = storage_worker(&server);
30008                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
30009                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
30010                for path in [
30011                    "/api/worker/workflow-tasks/poll",
30012                    "/api/worker/activity-tasks/poll",
30013                    "/api/worker/query-tasks/poll",
30014                ] {
30015                    assert_identical_requests(&server, path, 9);
30016                }
30017            }
30018        }
30019    }
30020
30021    #[tokio::test]
30022    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
30023        struct CountedBody(Arc<AtomicUsize>);
30024        impl Serialize for CountedBody {
30025            fn serialize<S: Serializer>(
30026                &self,
30027                serializer: S,
30028            ) -> std::result::Result<S::Ok, S::Error> {
30029                let count = self.0.fetch_add(1, Ordering::SeqCst);
30030                json!({"serialization":count,"lease_owner":"worker","attempt":7})
30031                    .serialize(serializer)
30032            }
30033        }
30034        for path in [
30035            "/api/worker/register",
30036            "/api/worker/heartbeat",
30037            "/api/worker/workflow-tasks/storage-task/complete",
30038            "/api/worker/workflow-tasks/storage-task/fail",
30039            "/api/worker/activity-tasks/storage-task/complete",
30040            "/api/worker/activity-tasks/storage-task/fail",
30041            "/api/worker/activity-tasks/storage-task/heartbeat",
30042            "/api/worker/query-tasks/storage-task/complete",
30043            "/api/worker/query-tasks/storage-task/fail",
30044        ] {
30045            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30046                storage_refusals: 7,
30047                storage_path: Some(path),
30048                ..MockWorkerBehavior::default()
30049            });
30050            let worker =
30051                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30052            let calls = Arc::new(AtomicUsize::new(0));
30053            let _: Value = worker
30054                .client
30055                .request_json(
30056                    reqwest::Method::POST,
30057                    &path[4..],
30058                    RequestProtocol::DefaultWorker,
30059                    Some(&CountedBody(Arc::clone(&calls))),
30060                )
30061                .await
30062                .expect("prepared request recovery");
30063            assert_eq!(calls.load(Ordering::SeqCst), 1);
30064            assert_identical_requests(&server, path, 8);
30065        }
30066        for worker_scope in [false, true] {
30067            let path = if worker_scope {
30068                "/api/health"
30069            } else {
30070                "/api/worker/register"
30071            };
30072            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30073                storage_refusals: usize::MAX,
30074                storage_path: Some(path),
30075                ..MockWorkerBehavior::default()
30076            });
30077            let worker = storage_worker(&server);
30078            let client = worker.client.clone();
30079            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
30080            let error = if worker_scope {
30081                worker
30082                    .client
30083                    .health()
30084                    .await
30085                    .expect_err("control plane is not retried")
30086            } else {
30087                client
30088                    .request_json::<Value, Value>(
30089                        reqwest::Method::POST,
30090                        "/worker/register",
30091                        RequestProtocol::DefaultWorker,
30092                        Some(&json!({})),
30093                    )
30094                    .await
30095                    .expect_err("direct client is not retried")
30096            };
30097            assert!(worker_storage_admission_body(&error).is_some());
30098            assert_eq!(server.request_count(path), 1);
30099        }
30100    }
30101
30102    #[tokio::test]
30103    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
30104        for fail in [false, true] {
30105            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30106                storage_activity: true,
30107                storage_refusals: 7,
30108                storage_path: Some("/storage-activity/"),
30109                ..MockWorkerBehavior::default()
30110            });
30111            let mut worker = storage_worker(&server);
30112            let calls = Arc::new(AtomicUsize::new(0));
30113            let observed = Arc::clone(&calls);
30114            worker.register_activity("storage.activity", move |ctx, _| {
30115                let calls = Arc::clone(&observed);
30116                async move {
30117                    calls.fetch_add(1, Ordering::SeqCst);
30118                    ctx.heartbeat(json!({"step":2})).await?;
30119                    if fail {
30120                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
30121                    } else {
30122                        Ok(json!({"receipt":true}))
30123                    }
30124                }
30125            });
30126            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30127            assert_eq!(calls.load(Ordering::SeqCst), 1);
30128            assert_identical_requests(
30129                &server,
30130                "/api/worker/activity-tasks/storage-activity/heartbeat",
30131                8,
30132            );
30133            let suffix = if fail { "fail" } else { "complete" };
30134            assert_identical_requests(
30135                &server,
30136                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
30137                8,
30138            );
30139            let other = if fail { "complete" } else { "fail" };
30140            assert_eq!(
30141                server.request_count(&format!(
30142                    "/api/worker/activity-tasks/storage-activity/{other}"
30143                )),
30144                0
30145            );
30146        }
30147    }
30148
30149    #[tokio::test]
30150    async fn storage_waits_are_interruptible_without_false_activity_failure() {
30151        for path in [
30152            "/api/worker/register",
30153            "/api/worker/heartbeat",
30154            "/api/worker/activity-tasks/poll",
30155            "/api/worker/activity-tasks/storage-activity/heartbeat",
30156            "/api/worker/activity-tasks/storage-activity/complete",
30157        ] {
30158            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30159                storage_activity: true,
30160                storage_refusals: usize::MAX,
30161                storage_path: Some(path),
30162                ..MockWorkerBehavior::default()
30163            });
30164            let mut worker = storage_worker(&server)
30165                .max_concurrent_workflow_tasks(1)
30166                .max_concurrent_activity_tasks(1)
30167                .retry_policy(WorkerRetryPolicy::default());
30168            worker.register_activity("storage.activity", |ctx, _| async move {
30169                ctx.heartbeat(json!({"step":2})).await?;
30170                Ok(json!({"receipt":true}))
30171            });
30172            let shutdown = async {
30173                while server.request_count(path) == 0 {
30174                    tokio::time::sleep(Duration::from_millis(1)).await;
30175                }
30176            };
30177            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
30178                .await
30179                .expect("shutdown interrupts admission");
30180            assert!(
30181                result.is_err(),
30182                "a refused operation must not appear acknowledged: {path}, {result:?}"
30183            );
30184            assert_eq!(server.request_count(path), 1);
30185            assert_eq!(
30186                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
30187                0
30188            );
30189            assert_eq!(
30190                server.request_count("/api/worker/registrations/mock-worker"),
30191                usize::from(!path.ends_with("/register"))
30192            );
30193        }
30194    }
30195
30196    #[tokio::test]
30197    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
30198        for fail in [false, true] {
30199            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30200                storage_query: true,
30201                storage_refusals: 7,
30202                storage_path: Some("/storage-query/"),
30203                ..MockWorkerBehavior::default()
30204            });
30205            let mut worker = storage_worker(&server);
30206            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
30207            let calls = Arc::new(AtomicUsize::new(0));
30208            let observed = Arc::clone(&calls);
30209            worker.register_query("storage.workflow", "state", move |_, _| {
30210                let calls = Arc::clone(&observed);
30211                async move {
30212                    calls.fetch_add(1, Ordering::SeqCst);
30213                    if fail {
30214                        Err(Error::WorkerLoop("intentional query failure".to_string()))
30215                    } else {
30216                        Ok(json!({"state":"waiting"}))
30217                    }
30218                }
30219            });
30220            assert_eq!(worker.run_once().await.expect("query settled"), 1);
30221            assert_eq!(calls.load(Ordering::SeqCst), 1);
30222            let suffix = if fail { "fail" } else { "complete" };
30223            assert_identical_requests(
30224                &server,
30225                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
30226                8,
30227            );
30228            let other = if fail { "complete" } else { "fail" };
30229            assert_eq!(
30230                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
30231                0
30232            );
30233        }
30234    }
30235
30236    #[tokio::test]
30237    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
30238        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30239            storage_refusals: 7,
30240            storage_path: Some("/poll"),
30241            unauthorized_polls: true,
30242            ..MockWorkerBehavior::default()
30243        });
30244        let error = storage_worker(&server)
30245            .run_once()
30246            .await
30247            .expect_err("auth remains terminal");
30248        assert!(matches!(
30249            error,
30250            Error::Http {
30251                status: reqwest::StatusCode::UNAUTHORIZED,
30252                ..
30253            }
30254        ));
30255        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
30256
30257        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30258            storage_refusals: 7,
30259            storage_path: Some("/activity-cancel/complete"),
30260            ..MockWorkerBehavior::default()
30261        });
30262        let worker =
30263            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30264        let error = worker
30265            .client
30266            .complete_activity_task(
30267                "activity-cancel",
30268                "attempt-cancel",
30269                "worker",
30270                json!({}),
30271                DEFAULT_CODEC,
30272            )
30273            .await
30274            .expect_err("cancellation remains terminal");
30275        assert!(activity_task_rejection_is_final(&error));
30276        assert_identical_requests(
30277            &server,
30278            "/api/worker/activity-tasks/activity-cancel/complete",
30279            8,
30280        );
30281
30282        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30283            storage_refusals: usize::MAX,
30284            storage_path: Some("/poll"),
30285            storage_wrong_poll_id: true,
30286            ..MockWorkerBehavior::default()
30287        });
30288        assert!(storage_worker(&server).run_once().await.is_err());
30289        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
30290    }
30291
30292    #[tokio::test]
30293    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
30294        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30295            storage_refusals: usize::MAX,
30296            storage_path: Some("/poll"),
30297            ..MockWorkerBehavior::default()
30298        });
30299        let mut worker = storage_worker(&server)
30300            .max_concurrent_workflow_tasks(1)
30301            .max_concurrent_activity_tasks(1)
30302            .retry_policy(WorkerRetryPolicy::default());
30303        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
30304        let run = tokio::spawn(async move { worker.run().await });
30305        tokio::time::timeout(Duration::from_secs(2), async {
30306            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
30307                tokio::time::sleep(Duration::from_millis(1)).await;
30308            }
30309        })
30310        .await
30311        .expect("poll started");
30312        run.abort();
30313        assert!(run.await.expect_err("cancelled run").is_cancelled());
30314        tokio::time::sleep(Duration::from_millis(250)).await;
30315        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
30316    }
30317
30318    #[tokio::test]
30319    async fn query_protocol_rejection_from_older_server_is_typed() {
30320        let server = MockWorkerServer::reject_query_protocol();
30321        let client = Client::builder(server.base_url())
30322            .timeout(Duration::from_secs(2))
30323            .build()
30324            .expect("client");
30325
30326        let error = client
30327            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
30328            .await
30329            .expect_err("server below query protocol floor must reject");
30330        let Error::Protocol(failure) = error else {
30331            panic!("expected typed protocol failure");
30332        };
30333
30334        assert_eq!(failure.status, 400);
30335        assert_eq!(failure.reason, "unsupported_protocol_version");
30336        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
30337        assert_eq!(
30338            failure.requested_version.as_deref(),
30339            Some(WORKER_PROTOCOL_VERSION)
30340        );
30341        assert_eq!(
30342            server
30343                .worker_protocol_for("/api/worker/query-tasks/poll")
30344                .as_deref(),
30345            Some(WORKER_PROTOCOL_VERSION)
30346        );
30347    }
30348
30349    #[tokio::test]
30350    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
30351        let server = MockWorkerServer::reject_query_protocol();
30352        let client = Client::builder(server.base_url())
30353            .timeout(Duration::from_secs(2))
30354            .build()
30355            .expect("client");
30356        let mut worker = Worker::new(client, "rust-workers")
30357            .worker_id("baseline-worker")
30358            .poll_timeout(Duration::from_millis(10));
30359
30360        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
30361            Ok(Value::Null)
30362        });
30363
30364        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
30365        assert_eq!(
30366            server
30367                .worker_protocol_for("/api/worker/workflow-tasks/poll")
30368                .as_deref(),
30369            Some(WORKER_PROTOCOL_VERSION)
30370        );
30371        assert_eq!(
30372            server.worker_protocol_for("/api/worker/query-tasks/poll"),
30373            None,
30374            "a worker without query handlers must not use the query-task endpoint"
30375        );
30376    }
30377
30378    #[tokio::test]
30379    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
30380        let server = MockWorkerServer::reject_query_completion();
30381        let client = Client::builder(server.base_url())
30382            .timeout(Duration::from_secs(2))
30383            .build()
30384            .expect("client");
30385
30386        let error = client
30387            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
30388            .await
30389            .expect_err("expired completion must be rejected");
30390        let Error::QueryFailed(failure) = error else {
30391            panic!("expected typed query failure");
30392        };
30393        assert_eq!(failure.status, 409);
30394        assert_eq!(failure.reason, "query_task_timed_out");
30395
30396        let mut worker = Worker::new(client, "rust-workers")
30397            .worker_id("late-worker")
30398            .poll_timeout(Duration::from_millis(10));
30399        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30400        worker.register_query(
30401            "counter",
30402            "current",
30403            |_ctx, _args| async move { Ok(json!(8)) },
30404        );
30405
30406        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
30407        assert_eq!(
30408            worker
30409                .run_once()
30410                .await
30411                .expect("worker continues after late completion"),
30412            0
30413        );
30414        assert_eq!(
30415            server.request_count("/api/worker/query-tasks/query-late/complete"),
30416            2
30417        );
30418        assert_eq!(
30419            server.request_count("/api/worker/query-tasks/query-late/fail"),
30420            0,
30421            "a server completion rejection must not be reported as an encoding failure"
30422        );
30423    }
30424
30425    #[tokio::test]
30426    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
30427        let server = MockWorkerServer::start();
30428        let client = Client::builder(server.base_url())
30429            .timeout(Duration::from_secs(2))
30430            .build()
30431            .expect("client");
30432        let mut worker = Worker::new(client, "rust-workers")
30433            .worker_id("joined-worker")
30434            .poll_timeout(Duration::from_millis(10));
30435        worker.register_workflow(
30436            "joined.workflow",
30437            |_ctx, _input| async move { Ok(Value::Null) },
30438        );
30439        worker.register_activity(
30440            "joined.activity",
30441            |_ctx, _input| async move { Ok(Value::Null) },
30442        );
30443        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
30444            Ok(Value::Null)
30445        });
30446
30447        worker
30448            .run_until(tokio::time::sleep(Duration::from_millis(20)))
30449            .await
30450            .expect("normal shutdown");
30451
30452        let deregistration_path = "/api/worker/registrations/mock-worker";
30453        assert_eq!(server.request_count(deregistration_path), 1);
30454        for poll_path in [
30455            "/api/worker/workflow-tasks/poll",
30456            "/api/worker/activity-tasks/poll",
30457            "/api/worker/query-tasks/poll",
30458        ] {
30459            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
30460        }
30461        assert_eq!(
30462            server.captured_paths().last().map(String::as_str),
30463            Some(deregistration_path),
30464            "deregistration must start only after every poller has joined"
30465        );
30466    }
30467
30468    #[tokio::test]
30469    async fn registration_failure_does_not_deregister() {
30470        let server = MockWorkerServer::rejected_registration();
30471        let client = Client::builder(server.base_url())
30472            .timeout(Duration::from_secs(2))
30473            .build()
30474            .expect("client");
30475        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
30476
30477        let error = worker
30478            .run_until(async {})
30479            .await
30480            .expect_err("registration must fail");
30481        assert!(matches!(
30482            error,
30483            Error::Http {
30484                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30485                ..
30486            }
30487        ));
30488        assert!(server
30489            .captured_paths()
30490            .iter()
30491            .all(|path| !path.starts_with("/api/worker/registrations/")));
30492    }
30493
30494    #[tokio::test]
30495    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
30496        let server = MockWorkerServer::rejected_registration_protocol();
30497        let client = Client::builder(server.base_url())
30498            .timeout(Duration::from_secs(2))
30499            .build()
30500            .expect("client");
30501        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
30502
30503        let error = worker
30504            .run_until(async {})
30505            .await
30506            .expect_err("a protocol 1.16 server must reject this worker");
30507        let Error::Protocol(failure) = error else {
30508            panic!("expected typed protocol rejection");
30509        };
30510        assert_eq!(failure.reason, "unsupported_protocol_version");
30511        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
30512        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
30513        assert_eq!(
30514            server
30515                .worker_protocol_for("/api/worker/register")
30516                .as_deref(),
30517            Some(WORKER_PROTOCOL_VERSION)
30518        );
30519    }
30520
30521    #[tokio::test]
30522    async fn declined_registration_does_not_deregister() {
30523        let server = MockWorkerServer::declined_registration();
30524        let client = Client::builder(server.base_url())
30525            .timeout(Duration::from_secs(2))
30526            .build()
30527            .expect("client");
30528        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
30529
30530        let error = worker
30531            .run_until(async {})
30532            .await
30533            .expect_err("declined registration must fail");
30534        assert!(matches!(error, Error::WorkerLoop(_)));
30535        assert!(error.to_string().contains("was not accepted"));
30536        assert!(server
30537            .captured_paths()
30538            .iter()
30539            .all(|path| !path.starts_with("/api/worker/registrations/")));
30540    }
30541
30542    #[tokio::test]
30543    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
30544        let server = MockWorkerServer::rejected_deregistration();
30545        let client = Client::builder(server.base_url())
30546            .timeout(Duration::from_secs(2))
30547            .build()
30548            .expect("client");
30549        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
30550
30551        let error = worker
30552            .run_until(async {})
30553            .await
30554            .expect_err("deregistration must fail");
30555        assert!(matches!(
30556            error,
30557            Error::Http {
30558                status: reqwest::StatusCode::FORBIDDEN,
30559                ..
30560            }
30561        ));
30562        assert_eq!(
30563            server.request_count("/api/worker/registrations/mock-worker"),
30564            1
30565        );
30566    }
30567
30568    #[tokio::test]
30569    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
30570        let server = MockWorkerServer::rejected_deregistration_protocol();
30571        let client = Client::builder(server.base_url())
30572            .timeout(Duration::from_secs(2))
30573            .build()
30574            .expect("client");
30575        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
30576
30577        let error = worker
30578            .run_until(async {})
30579            .await
30580            .expect_err("protocol rejection must fail shutdown");
30581        let Error::Protocol(failure) = error else {
30582            panic!("expected typed protocol failure");
30583        };
30584        assert_eq!(failure.reason, "unsupported_protocol_version");
30585        assert_eq!(
30586            failure.requested_version.as_deref(),
30587            Some(WORKER_PROTOCOL_VERSION)
30588        );
30589        assert_eq!(
30590            server.request_count("/api/worker/registrations/mock-worker"),
30591            1
30592        );
30593    }
30594
30595    #[tokio::test]
30596    async fn primary_poller_error_retains_deregistration_failure_context() {
30597        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
30598        let client = Client::builder(server.base_url())
30599            .timeout(Duration::from_secs(2))
30600            .build()
30601            .expect("client");
30602        let mut worker = Worker::new(client, "rust-workers")
30603            .worker_id("combined-failure")
30604            .poll_timeout(Duration::from_millis(10));
30605        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
30606            Ok(Value::Null)
30607        });
30608
30609        let error = worker
30610            .run()
30611            .await
30612            .expect_err("worker and cleanup must fail");
30613        let summary = error.to_string();
30614        assert!(summary.contains("authentication_failed"));
30615        assert!(summary.contains("worker cannot deregister"));
30616        let Error::WorkerShutdown {
30617            primary,
30618            deregistration,
30619        } = error
30620        else {
30621            panic!("expected combined worker shutdown error");
30622        };
30623        assert!(matches!(
30624            *primary,
30625            Error::Http {
30626                status: reqwest::StatusCode::UNAUTHORIZED,
30627                ..
30628            }
30629        ));
30630        assert!(matches!(
30631            *deregistration,
30632            Error::Http {
30633                status: reqwest::StatusCode::FORBIDDEN,
30634                ..
30635            }
30636        ));
30637        assert_eq!(
30638            server.request_count("/api/worker/registrations/mock-worker"),
30639            1
30640        );
30641    }
30642
30643    #[tokio::test]
30644    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
30645        let server = MockWorkerServer::start();
30646        let client = Client::builder(server.base_url())
30647            .timeout(Duration::from_secs(2))
30648            .build()
30649            .expect("client");
30650        let mut worker = Worker::new(client, "rust-workers")
30651            .worker_id("activity-only-worker")
30652            .poll_timeout(Duration::from_millis(10));
30653
30654        worker.register_activity(
30655            "activity.only",
30656            |_ctx, _args| async move { Ok(Value::Null) },
30657        );
30658
30659        worker.run_until(async {}).await.expect("run worker");
30660    }
30661
30662    #[tokio::test]
30663    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
30664        let server = MockWorkerServer::start();
30665        let client = Client::builder(server.base_url())
30666            .timeout(Duration::from_secs(2))
30667            .build()
30668            .expect("client");
30669        let mut worker = Worker::new(client, "rust-workers")
30670            .worker_id("workflow-only-worker")
30671            .poll_timeout(Duration::from_millis(10));
30672
30673        worker.register_workflow(
30674            "workflow.only",
30675            |_ctx, _input| async move { Ok(Value::Null) },
30676        );
30677
30678        worker.run_until(async {}).await.expect("run worker");
30679    }
30680
30681    #[tokio::test]
30682    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
30683        let server = MockWorkerServer::start();
30684        let client = Client::builder(server.base_url())
30685            .timeout(Duration::from_secs(2))
30686            .build()
30687            .expect("client");
30688        let observations = Arc::new(Mutex::new(Vec::new()));
30689        let observed = Arc::clone(&observations);
30690        let mut worker = Worker::new(client, "rust-workers")
30691            .worker_id("observed-heartbeat-worker")
30692            .poll_timeout(Duration::from_millis(10))
30693            .on_worker_heartbeat(move |observation| {
30694                observed
30695                    .lock()
30696                    .expect("heartbeat observations")
30697                    .push(observation.clone());
30698            });
30699
30700        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
30701            Ok(Value::Null)
30702        });
30703        let acknowledged = Arc::clone(&observations);
30704        worker
30705            .run_until(async move {
30706                tokio::time::timeout(Duration::from_secs(2), async move {
30707                    loop {
30708                        if !acknowledged
30709                            .lock()
30710                            .expect("heartbeat observations")
30711                            .is_empty()
30712                        {
30713                            break;
30714                        }
30715                        tokio::time::sleep(Duration::from_millis(1)).await;
30716                    }
30717                })
30718                .await
30719                .expect("heartbeat acknowledgement within timeout");
30720            })
30721            .await
30722            .expect("run worker");
30723
30724        let observations = observations.lock().expect("heartbeat observations");
30725        let first = observations.first().expect("heartbeat acknowledgement");
30726        assert_eq!(first.worker_id, "observed-heartbeat-worker");
30727        assert_eq!(first.task_queue, "rust-workers");
30728        assert!(first.acknowledged_at_unix_millis > 0);
30729        assert_eq!(first.acknowledgement, json!({}));
30730    }
30731
30732    #[tokio::test]
30733    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
30734        let server = MockWorkerServer::delayed_heartbeat_worker();
30735        let client = Client::builder(server.base_url())
30736            .timeout(Duration::from_secs(3))
30737            .build()
30738            .expect("client");
30739        let observations = Arc::new(Mutex::new(Vec::new()));
30740        let observed = Arc::clone(&observations);
30741        let mut worker = Worker::new(client, "rust-snapshot-workers")
30742            .max_concurrent_workflow_tasks(1)
30743            .max_concurrent_activity_tasks(1)
30744            .worker_id("rust-snapshot-worker")
30745            .poll_timeout(Duration::from_millis(10))
30746            .on_worker_heartbeat(move |observation| {
30747                observed
30748                    .lock()
30749                    .expect("heartbeat observations")
30750                    .push(observation.clone());
30751            });
30752
30753        worker.register_workflow("snapshot", |ctx, _input| async move {
30754            ctx.wait_signal("finish").await?;
30755            Ok(json!({"status": "finished"}))
30756        });
30757        worker.register_query("snapshot", "current", |ctx, _args| async move {
30758            Ok(json!(ctx
30759                .signals("increment")
30760                .iter()
30761                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30762                .sum::<i64>()))
30763        });
30764        worker.register_activity("cancel-aware", |_ctx, _args| async move {
30765            Ok(json!({"late": "completion"}))
30766        });
30767
30768        worker
30769            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
30770            .await
30771            .expect("delayed heartbeat must allow a clean worker shutdown");
30772
30773        let observations = observations.lock().expect("heartbeat observations");
30774        assert!(
30775            observations.len() >= 3,
30776            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
30777        );
30778        assert!(
30779            observations.windows(2).all(|pair| {
30780                pair[1].acknowledged_at_unix_millis
30781                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30782                    >= 850
30783            }),
30784            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
30785        );
30786        drop(observations);
30787
30788        let heartbeat_times = server.request_times("/api/worker/heartbeat");
30789        let delayed_request_at = *heartbeat_times
30790            .get(1)
30791            .expect("intentionally delayed heartbeat request");
30792        let delay_window_start = delayed_request_at + Duration::from_millis(100);
30793        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
30794        for path in [
30795            "/api/worker/workflow-tasks/poll",
30796            "/api/worker/activity-tasks/poll",
30797            "/api/worker/query-tasks/poll",
30798        ] {
30799            assert!(
30800                server
30801                    .request_times(path)
30802                    .iter()
30803                    .any(|received_at| *received_at >= delay_window_start
30804                        && *received_at <= delay_window_end),
30805                "{path} must keep polling while a heartbeat acknowledgement is delayed"
30806            );
30807        }
30808        assert!(
30809            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
30810            "workflow work must be settled"
30811        );
30812        assert!(
30813            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
30814            "activity work must be settled"
30815        );
30816        assert!(
30817            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
30818            "query work must be settled"
30819        );
30820    }
30821
30822    #[tokio::test]
30823    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
30824        let server = MockWorkerServer::heartbeat_retry_worker();
30825        let client = Client::builder(server.base_url())
30826            .timeout(Duration::from_secs(2))
30827            .build()
30828            .expect("client");
30829        let observations = Arc::new(Mutex::new(Vec::new()));
30830        let observed = Arc::clone(&observations);
30831        let worker = Worker::new(client, "rust-workers")
30832            .worker_id("heartbeat-retry-worker")
30833            .retry_policy(WorkerRetryPolicy {
30834                max_retries: 1,
30835                initial_backoff: Duration::from_millis(300),
30836                max_backoff: Duration::from_millis(300),
30837            })
30838            .on_worker_heartbeat(move |observation| {
30839                observed
30840                    .lock()
30841                    .expect("heartbeat observations")
30842                    .push(observation.clone());
30843            });
30844
30845        worker
30846            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
30847            .await
30848            .expect("retryable heartbeat failure must remain bounded and recover");
30849
30850        let observations = observations.lock().expect("heartbeat observations");
30851        assert!(observations.len() >= 3, "heartbeat retry must recover");
30852        assert!(
30853            observations.windows(2).all(|pair| {
30854                pair[1]
30855                    .acknowledged_at_unix_millis
30856                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30857                    >= 850
30858            }),
30859            "a successful retry must start a fresh advertised cadence: {observations:?}"
30860        );
30861        assert_eq!(
30862            server.request_count("/api/worker/heartbeat"),
30863            observations.len() + 1,
30864            "one retryable failure must add exactly one bounded request"
30865        );
30866    }
30867
30868    #[tokio::test]
30869    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
30870        let server = MockWorkerServer::waiting_query_worker();
30871        let client = Client::builder(server.base_url())
30872            .timeout(Duration::from_secs(2))
30873            .build()
30874            .expect("client");
30875        let observations = Arc::new(Mutex::new(Vec::new()));
30876        let observed = Arc::clone(&observations);
30877        let mut worker = Worker::new(client, "rust-snapshot-workers")
30878            .worker_id("rust-snapshot-worker")
30879            .poll_timeout(Duration::from_millis(10))
30880            .on_worker_heartbeat(move |observation| {
30881                observed
30882                    .lock()
30883                    .expect("heartbeat observations")
30884                    .push(observation.clone());
30885            });
30886
30887        worker.register_workflow("snapshot", |ctx, _input| async move {
30888            ctx.wait_signal("finish").await?;
30889            Ok(json!({"status": "finished"}))
30890        });
30891        worker.register_query("snapshot", "current", |ctx, _args| async move {
30892            let current = ctx
30893                .signals("increment")
30894                .iter()
30895                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30896                .sum::<i64>();
30897            Ok(json!(current))
30898        });
30899        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
30900        worker
30901            .declare_workflow_signals("snapshot", &["finish"])
30902            .expect("declare finish signal");
30903
30904        worker
30905            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
30906            .await
30907            .expect("pending workflow and query poller must remain live until shutdown");
30908
30909        assert!(
30910            observations.lock().expect("heartbeat observations").len() >= 4,
30911            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
30912        );
30913        assert!(
30914            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
30915            "workflow polling must continue after empty replay acknowledgements"
30916        );
30917        assert!(
30918            server.request_count("/api/worker/query-tasks/poll") >= 2,
30919            "query polling must continue after serving the current query"
30920        );
30921        assert_eq!(
30922            server.request_body("/api/worker/register")["capabilities"],
30923            json!([
30924                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
30925                "workflow_entry_arguments_validation",
30926                DURABLE_SELECTION_CAPABILITY,
30927                MEMO_UPSERTS_CAPABILITY,
30928                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
30929                QUERY_TASKS_CAPABILITY,
30930                WORKFLOW_UPDATES_CAPABILITY,
30931                MESSAGE_STREAMS_CAPABILITY
30932            ])
30933        );
30934        assert_eq!(
30935            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
30936            json!({
30937                "queries": ["current"],
30938                "query_contracts": [{
30939                    "name": "current",
30940                    "parameters": [{
30941                        "name": "args", "position": 0, "required": false,
30942                        "variadic": true, "type": null, "allows_null": true,
30943                        "default_available": false, "default": null,
30944                    }],
30945                }],
30946                "signals": ["finish"],
30947                "signal_contracts": [{
30948                    "name": "finish",
30949                    "parameters": [{
30950                        "name": "args", "position": 0, "required": false,
30951                        "variadic": true, "type": null, "allows_null": true,
30952                        "default_available": false, "default": null,
30953                    }],
30954                }],
30955                "updates": ["replace"],
30956                "update_contracts": [{
30957                    "name": "replace",
30958                    "parameters": [{
30959                        "name": "args", "position": 0, "required": false,
30960                        "variadic": true, "type": null, "allows_null": true,
30961                        "default_available": false, "default": null,
30962                    }],
30963                }],
30964                "update_validators": [],
30965            })
30966        );
30967
30968        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
30969        assert_eq!(
30970            opened["commands"],
30971            json!([{
30972                "type": "open_signal_wait",
30973                "signal_name": "finish",
30974            }])
30975        );
30976
30977        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
30978            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
30979            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
30980            let failure = server.request_body(&fail_path);
30981            assert_eq!(
30982                failure["failure"]["type"],
30983                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
30984            );
30985            assert_eq!(server.request_count(&completion_path), 0);
30986        }
30987
30988        let query_completion =
30989            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
30990        assert_eq!(query_completion["result"], json!(8));
30991
30992        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
30993        assert_eq!(
30994            server.request_count(terminal_path),
30995            1,
30996            "the matching signal must settle the workflow exactly once"
30997        );
30998        let terminal = server.request_body(terminal_path);
30999        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
31000        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
31001        assert_eq!(
31002            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
31003                .expect("terminal workflow result"),
31004            json!({"status": "finished"})
31005        );
31006    }
31007
31008    #[tokio::test]
31009    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
31010        let server = MockWorkerServer::transient_worker_failures();
31011        let client = Client::builder(server.base_url())
31012            .timeout(Duration::from_secs(2))
31013            .build()
31014            .expect("client");
31015        let mut worker = Worker::new(client, "rust-workers")
31016            .max_concurrent_workflow_tasks(1)
31017            .max_concurrent_activity_tasks(1)
31018            .worker_id("retry-worker")
31019            .poll_timeout(Duration::from_millis(10))
31020            .retry_policy(WorkerRetryPolicy {
31021                max_retries: 2,
31022                initial_backoff: Duration::from_millis(1),
31023                max_backoff: Duration::from_millis(1),
31024            });
31025        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31026        worker.register_activity(
31027            "counter.activity",
31028            |_ctx, _input| async move { Ok(Value::Null) },
31029        );
31030        worker.register_query(
31031            "counter",
31032            "current",
31033            |_ctx, _args| async move { Ok(json!(8)) },
31034        );
31035
31036        worker
31037            .run_until(tokio::time::sleep(Duration::from_millis(75)))
31038            .await
31039            .expect("transient failures must not stop the worker");
31040
31041        for path in [
31042            "/api/worker/heartbeat",
31043            "/api/worker/workflow-tasks/poll",
31044            "/api/worker/activity-tasks/poll",
31045            "/api/worker/query-tasks/poll",
31046        ] {
31047            assert!(
31048                server.request_count(path) >= 2,
31049                "{path} must continue after its transient failure"
31050            );
31051        }
31052    }
31053
31054    #[tokio::test]
31055    async fn worker_continues_after_long_poll_capacity_backpressure() {
31056        let server = MockWorkerServer::capacity_limited_activity_poll();
31057        let client = Client::builder(server.base_url())
31058            .timeout(Duration::from_secs(2))
31059            .build()
31060            .expect("client");
31061        let mut worker = Worker::new(client, "rust-workers")
31062            .worker_id("capacity-worker")
31063            .poll_timeout(Duration::from_millis(10))
31064            .retry_policy(WorkerRetryPolicy {
31065                max_retries: 0,
31066                initial_backoff: Duration::from_millis(1),
31067                max_backoff: Duration::from_millis(1),
31068            });
31069        worker.register_activity("capacity.activity", |_ctx, _input| async move {
31070            Ok(json!({"handled": true}))
31071        });
31072
31073        worker
31074            .run_until(tokio::time::sleep(Duration::from_millis(50)))
31075            .await
31076            .expect("capacity backpressure must not stop the worker");
31077
31078        assert!(
31079            server.request_count("/api/worker/activity-tasks/poll") >= 2,
31080            "the activity poller must continue after capacity backpressure"
31081        );
31082        assert_eq!(
31083            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
31084            1,
31085            "the worker must complete work returned after capacity recovers"
31086        );
31087    }
31088
31089    #[test]
31090    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
31091        let capacity = Error::Http {
31092            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31093            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
31094        };
31095        assert_eq!(
31096            worker_poll_capacity_retry_after(&capacity),
31097            Some(Duration::from_secs(3))
31098        );
31099
31100        let rejected_capacity = Error::Http {
31101            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31102            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
31103        };
31104        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
31105        assert!(!worker_operation_is_retryable(&rejected_capacity));
31106
31107        let ordinary_rate_limit = Error::Http {
31108            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31109            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
31110                .to_string(),
31111        };
31112        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
31113        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
31114    }
31115
31116    #[tokio::test]
31117    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
31118        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31119            poll_failures_per_path: 8,
31120            heartbeat_failures: 8,
31121            ..MockWorkerBehavior::default()
31122        });
31123        let client = Client::builder(server.base_url())
31124            .timeout(Duration::from_secs(2))
31125            .build()
31126            .expect("client");
31127        let acknowledgements = Arc::new(AtomicUsize::new(0));
31128        let observed = Arc::clone(&acknowledgements);
31129        let mut worker = Worker::new(client, "rust-workers")
31130            .max_concurrent_workflow_tasks(1)
31131            .max_concurrent_activity_tasks(1)
31132            .recover_transient_outages(true)
31133            .poll_timeout(Duration::from_millis(10))
31134            .retry_policy(WorkerRetryPolicy {
31135                max_retries: 2,
31136                initial_backoff: Duration::from_millis(2),
31137                max_backoff: Duration::from_millis(5),
31138            })
31139            .on_worker_heartbeat(move |_| {
31140                observed.fetch_add(1, Ordering::SeqCst);
31141            });
31142        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31143        worker.register_activity(
31144            "counter.activity",
31145            |_ctx, _input| async move { Ok(Value::Null) },
31146        );
31147        worker.register_query("counter", "current", |_ctx, _args| async move {
31148            Ok(Value::Null)
31149        });
31150
31151        worker
31152            .run_until(tokio::time::sleep(Duration::from_millis(500)))
31153            .await
31154            .expect("a recoverable outage must not stop the service worker");
31155
31156        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
31157        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
31158        for path in [
31159            "/api/worker/workflow-tasks/poll",
31160            "/api/worker/activity-tasks/poll",
31161            "/api/worker/query-tasks/poll",
31162        ] {
31163            let bodies = server.request_bodies(path);
31164            assert!(bodies.len() >= 10, "{path} must resume after recovery");
31165            let first = &bodies[0]["poll_request_id"];
31166            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
31167            for body in &bodies[..9] {
31168                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
31169            }
31170            assert_ne!(&bodies[9]["poll_request_id"], first);
31171            let times = server.request_times(path);
31172            for pair in times[..9].windows(2) {
31173                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
31174            }
31175        }
31176    }
31177
31178    #[tokio::test]
31179    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
31180        for heartbeat_outage in [false, true] {
31181            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31182                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
31183                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
31184                ..MockWorkerBehavior::default()
31185            });
31186            let client = Client::builder(server.base_url()).build().expect("client");
31187            let mut worker = Worker::new(client, "rust-workers")
31188                .max_concurrent_workflow_tasks(1)
31189                .max_concurrent_activity_tasks(1)
31190                .recover_transient_outages(true)
31191                .retry_policy(WorkerRetryPolicy {
31192                    max_retries: 1,
31193                    initial_backoff: Duration::from_secs(5),
31194                    max_backoff: Duration::from_secs(5),
31195                });
31196            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31197            let started = Instant::now();
31198            worker
31199                .run_until(tokio::time::sleep(Duration::from_millis(200)))
31200                .await
31201                .expect("shutdown during an outage is a normal stop");
31202            assert!(started.elapsed() < Duration::from_secs(1));
31203            let path = if heartbeat_outage {
31204                "/api/worker/heartbeat"
31205            } else {
31206                "/api/worker/workflow-tasks/poll"
31207            };
31208            assert_eq!(server.request_count(path), 1);
31209            assert_eq!(
31210                server.request_count("/api/worker/registrations/mock-worker"),
31211                1
31212            );
31213        }
31214    }
31215
31216    #[tokio::test]
31217    async fn worker_outage_recovery_keeps_run_once_bounded() {
31218        let server = MockWorkerServer::unavailable_polls();
31219        let client = Client::builder(server.base_url()).build().expect("client");
31220        let mut worker = Worker::new(client, "rust-workers")
31221            .recover_transient_outages(true)
31222            .retry_policy(WorkerRetryPolicy {
31223                max_retries: 2,
31224                initial_backoff: Duration::from_millis(1),
31225                max_backoff: Duration::from_millis(1),
31226            });
31227        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31228        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
31229        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
31230    }
31231
31232    #[tokio::test]
31233    async fn worker_outage_recovery_respects_disabled_retries() {
31234        let server = MockWorkerServer::unavailable_polls();
31235        let client = Client::builder(server.base_url()).build().expect("client");
31236        let mut worker = Worker::new(client, "rust-workers")
31237            .max_concurrent_workflow_tasks(1)
31238            .max_concurrent_activity_tasks(1)
31239            .recover_transient_outages(true)
31240            .retry_policy(WorkerRetryPolicy {
31241                max_retries: 0,
31242                ..WorkerRetryPolicy::default()
31243            });
31244        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31245        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
31246        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31247    }
31248
31249    #[tokio::test]
31250    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
31251        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31252            heartbeat_failures: usize::MAX,
31253            unauthorized_polls: true,
31254            ..MockWorkerBehavior::default()
31255        });
31256        let client = Client::builder(server.base_url()).build().expect("client");
31257        let mut worker = Worker::new(client, "rust-workers")
31258            .max_concurrent_workflow_tasks(1)
31259            .max_concurrent_activity_tasks(1)
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            .max_concurrent_workflow_tasks(1)
31286            .max_concurrent_activity_tasks(1)
31287            .worker_id("bounded-retry-worker")
31288            .poll_timeout(Duration::from_millis(10))
31289            .retry_policy(WorkerRetryPolicy {
31290                max_retries: 2,
31291                initial_backoff: Duration::from_millis(1),
31292                max_backoff: Duration::from_millis(1),
31293            });
31294        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31295
31296        let error = worker.run().await.expect_err("retry bound must terminate");
31297        assert!(matches!(error, Error::Transport(_)));
31298        assert_eq!(
31299            server.request_count("/api/worker/workflow-tasks/poll"),
31300            3,
31301            "one initial request plus exactly two retries"
31302        );
31303    }
31304
31305    #[tokio::test]
31306    async fn worker_retry_policy_can_disable_poll_retries() {
31307        let server = MockWorkerServer::unavailable_polls();
31308        let client = Client::builder(server.base_url())
31309            .timeout(Duration::from_secs(2))
31310            .build()
31311            .expect("client");
31312        let mut worker = Worker::new(client, "rust-workers")
31313            .worker_id("no-retry-worker")
31314            .poll_timeout(Duration::from_millis(10))
31315            .retry_policy(WorkerRetryPolicy {
31316                max_retries: 0,
31317                initial_backoff: Duration::from_millis(1),
31318                max_backoff: Duration::from_millis(1),
31319            });
31320        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31321
31322        let error = worker
31323            .run_once()
31324            .await
31325            .expect_err("disabled retries must return the first transport failure");
31326        assert!(matches!(error, Error::Transport(_)));
31327        assert_eq!(
31328            server.request_count("/api/worker/workflow-tasks/poll"),
31329            1,
31330            "max_retries=0 must send only the initial request"
31331        );
31332    }
31333
31334    #[tokio::test]
31335    async fn worker_does_not_retry_authentication_failures() {
31336        let server = MockWorkerServer::unauthorized_polls();
31337        let client = Client::builder(server.base_url())
31338            .timeout(Duration::from_secs(2))
31339            .build()
31340            .expect("client");
31341        let mut worker = Worker::new(client, "rust-workers")
31342            .max_concurrent_workflow_tasks(1)
31343            .max_concurrent_activity_tasks(1)
31344            .worker_id("unauthorized-worker")
31345            .recover_transient_outages(true)
31346            .poll_timeout(Duration::from_millis(10));
31347        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31348
31349        let error = worker
31350            .run()
31351            .await
31352            .expect_err("authentication must terminate");
31353        let Error::Http { status, body } = error else {
31354            panic!("expected stable HTTP authentication error");
31355        };
31356        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
31357        assert!(body.contains("authentication_failed"));
31358        assert_eq!(
31359            server.request_count("/api/worker/workflow-tasks/poll"),
31360            1,
31361            "authentication failures must not be retried"
31362        );
31363    }
31364
31365    #[test]
31366    fn duplicate_registration_keeps_the_original_workflow() {
31367        let client = Client::new("http://127.0.0.1:9").expect("client");
31368        let mut worker = Worker::new(client, "registration-tests");
31369        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31370        let original = Arc::clone(&worker.workflows["same"].execute);
31371        worker
31372            .set_workflow_definition_sources("same", &["first workflow source"])
31373            .expect("source identity");
31374        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
31375        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
31376        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
31377        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
31378    }
31379
31380    #[test]
31381    fn duplicate_registration_keeps_the_original_activity() {
31382        let client = Client::new("http://127.0.0.1:9").expect("client");
31383        let mut worker = Worker::new(client, "registration-tests");
31384        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
31385        let original = Arc::clone(&worker.activities["same"]);
31386        worker.register_activity_avro_value("same", |_ctx, _input| async {
31387            Ok(AvroValue::String("second".into()))
31388        });
31389        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
31390    }
31391
31392    #[test]
31393    fn duplicate_registration_keeps_original_query_and_update_handlers() {
31394        let client = Client::new("http://127.0.0.1:9").expect("client");
31395        let mut worker = Worker::new(client, "registration-tests");
31396        worker.register_query("orders", "same", |_ctx, _input| async {
31397            Ok(json!("first"))
31398        });
31399        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
31400            panic!("snapshot query");
31401        };
31402        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
31403            Ok(json!("second"))
31404        });
31405        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
31406            panic!("duplicate replaced the query adapter");
31407        };
31408        assert!(Arc::ptr_eq(&original, retained));
31409        worker.register_update("orders", "same", |_ctx, _input| async {
31410            Ok(json!("first"))
31411        });
31412        let original = Arc::clone(&worker.updates["orders"]["same"]);
31413        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
31414            Ok(AvroValue::Null)
31415        });
31416        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
31417    }
31418
31419    #[tokio::test]
31420    async fn duplicate_registration_fails_before_server_contact() {
31421        let server = MockWorkerServer::start();
31422        let client = Client::builder(server.base_url()).build().expect("client");
31423        let mut worker =
31424            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
31425        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31426        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
31427        let error = worker
31428            .run_once()
31429            .await
31430            .expect_err("ambiguous worker must not poll");
31431        assert!(
31432            error.to_string().contains("duplicate_registration"),
31433            "{error}"
31434        );
31435        assert!(server.requests.lock().expect("requests").is_empty());
31436    }
31437
31438    #[derive(Clone, Debug)]
31439    struct CapturedRequest {
31440        headers: String,
31441        method: String,
31442        path: String,
31443        authorization: Option<String>,
31444        namespace: Option<String>,
31445        worker_protocol: Option<String>,
31446        control_protocol: Option<String>,
31447        body: String,
31448        received_at: Instant,
31449    }
31450
31451    struct MockWorkerServer {
31452        addr: SocketAddr,
31453        stop: Arc<AtomicBool>,
31454        requests: Arc<Mutex<Vec<CapturedRequest>>>,
31455        thread: Option<thread::JoinHandle<()>>,
31456    }
31457
31458    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
31459
31460    #[derive(Clone, Copy, Default)]
31461    struct MockWorkerBehavior {
31462        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
31463        request_override: Option<RequestOverride>,
31464        /// Close the connection after reading the request, without any response.
31465        drop_request: Option<fn(&str, usize) -> bool>,
31466        storage_refusals: usize,
31467        storage_path: Option<&'static str>,
31468        storage_unavailable: bool,
31469        storage_mid_poll: bool,
31470        storage_activity: bool,
31471        storage_query: bool,
31472        storage_wrong_poll_id: bool,
31473        reject_query_protocol: bool,
31474        reject_query_completion: bool,
31475        waiting_query_worker: bool,
31476        decline_registration: bool,
31477        complete_named_signal: bool,
31478        poll_failures_per_path: usize,
31479        long_poll_capacity_responses_per_path: usize,
31480        heartbeat_failures: usize,
31481        heartbeat_failure_request: Option<usize>,
31482        delayed_heartbeat_request: Option<usize>,
31483        heartbeat_response_delay: Duration,
31484        concurrent_requests: bool,
31485        unauthorized_polls: bool,
31486        reject_registration: bool,
31487        reject_registration_protocol: bool,
31488        reject_deregistration: bool,
31489        reject_deregistration_protocol: bool,
31490        cancelled_activity: bool,
31491        draining_polls: bool,
31492        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
31493        workflow_completion_status: Option<&'static str>,
31494        workflow_completion_body: Option<&'static str>,
31495    }
31496
31497    impl MockWorkerServer {
31498        fn start() -> Self {
31499            Self::start_with_behavior(MockWorkerBehavior::default())
31500        }
31501
31502        fn reject_query_protocol() -> Self {
31503            Self::start_with_behavior(MockWorkerBehavior {
31504                reject_query_protocol: true,
31505                ..MockWorkerBehavior::default()
31506            })
31507        }
31508
31509        fn reject_query_completion() -> Self {
31510            Self::start_with_behavior(MockWorkerBehavior {
31511                reject_query_completion: true,
31512                ..MockWorkerBehavior::default()
31513            })
31514        }
31515
31516        fn waiting_query_worker() -> Self {
31517            Self::start_with_behavior(MockWorkerBehavior {
31518                waiting_query_worker: true,
31519                complete_named_signal: true,
31520                ..MockWorkerBehavior::default()
31521            })
31522        }
31523
31524        fn transient_worker_failures() -> Self {
31525            Self::start_with_behavior(MockWorkerBehavior {
31526                poll_failures_per_path: 1,
31527                heartbeat_failures: 1,
31528                ..MockWorkerBehavior::default()
31529            })
31530        }
31531
31532        fn consecutive_poll_failures(count: usize) -> Self {
31533            Self::start_with_behavior(MockWorkerBehavior {
31534                poll_failures_per_path: count,
31535                ..MockWorkerBehavior::default()
31536            })
31537        }
31538
31539        fn capacity_limited_activity_poll() -> Self {
31540            Self::start_with_behavior(MockWorkerBehavior {
31541                long_poll_capacity_responses_per_path: 1,
31542                ..MockWorkerBehavior::default()
31543            })
31544        }
31545
31546        fn delayed_heartbeat_worker() -> Self {
31547            Self::start_with_behavior(MockWorkerBehavior {
31548                waiting_query_worker: true,
31549                delayed_heartbeat_request: Some(2),
31550                heartbeat_response_delay: Duration::from_millis(1_500),
31551                concurrent_requests: true,
31552                cancelled_activity: true,
31553                ..MockWorkerBehavior::default()
31554            })
31555        }
31556
31557        fn heartbeat_retry_worker() -> Self {
31558            Self::start_with_behavior(MockWorkerBehavior {
31559                waiting_query_worker: true,
31560                heartbeat_failure_request: Some(2),
31561                concurrent_requests: true,
31562                ..MockWorkerBehavior::default()
31563            })
31564        }
31565
31566        fn unavailable_polls() -> Self {
31567            Self::start_with_behavior(MockWorkerBehavior {
31568                poll_failures_per_path: usize::MAX,
31569                ..MockWorkerBehavior::default()
31570            })
31571        }
31572
31573        fn unauthorized_polls() -> Self {
31574            Self::start_with_behavior(MockWorkerBehavior {
31575                unauthorized_polls: true,
31576                ..MockWorkerBehavior::default()
31577            })
31578        }
31579
31580        fn rejected_registration() -> Self {
31581            Self::start_with_behavior(MockWorkerBehavior {
31582                reject_registration: true,
31583                ..MockWorkerBehavior::default()
31584            })
31585        }
31586
31587        fn rejected_registration_protocol() -> Self {
31588            Self::start_with_behavior(MockWorkerBehavior {
31589                reject_registration_protocol: true,
31590                ..MockWorkerBehavior::default()
31591            })
31592        }
31593
31594        fn declined_registration() -> Self {
31595            Self::start_with_behavior(MockWorkerBehavior {
31596                decline_registration: true,
31597                ..MockWorkerBehavior::default()
31598            })
31599        }
31600
31601        fn rejected_deregistration() -> Self {
31602            Self::start_with_behavior(MockWorkerBehavior {
31603                reject_deregistration: true,
31604                ..MockWorkerBehavior::default()
31605            })
31606        }
31607
31608        fn rejected_deregistration_protocol() -> Self {
31609            Self::start_with_behavior(MockWorkerBehavior {
31610                reject_deregistration_protocol: true,
31611                ..MockWorkerBehavior::default()
31612            })
31613        }
31614
31615        fn unauthorized_polls_and_rejected_deregistration() -> Self {
31616            Self::start_with_behavior(MockWorkerBehavior {
31617                unauthorized_polls: true,
31618                reject_deregistration: true,
31619                ..MockWorkerBehavior::default()
31620            })
31621        }
31622
31623        fn cancelled_activity() -> Self {
31624            Self::start_with_behavior(MockWorkerBehavior {
31625                cancelled_activity: true,
31626                ..MockWorkerBehavior::default()
31627            })
31628        }
31629
31630        fn draining_polls() -> Self {
31631            Self::start_with_behavior(MockWorkerBehavior {
31632                draining_polls: true,
31633                ..MockWorkerBehavior::default()
31634            })
31635        }
31636
31637        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
31638            Self::start_with_behavior(MockWorkerBehavior {
31639                invalid_task_payload_codec: Some(codec),
31640                ..MockWorkerBehavior::default()
31641            })
31642        }
31643
31644        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
31645            Self::start_with_behavior(MockWorkerBehavior {
31646                workflow_completion_status: Some(status),
31647                workflow_completion_body: Some(body),
31648                ..MockWorkerBehavior::default()
31649            })
31650        }
31651
31652        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
31653            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
31654            listener
31655                .set_nonblocking(true)
31656                .expect("configure mock listener");
31657            let addr = listener.local_addr().expect("mock server address");
31658            let stop = Arc::new(AtomicBool::new(false));
31659            let server_stop = Arc::clone(&stop);
31660            let requests = Arc::new(Mutex::new(Vec::new()));
31661            let server_requests = Arc::clone(&requests);
31662            let thread = thread::spawn(move || {
31663                let mut request_threads = Vec::new();
31664                while !server_stop.load(Ordering::SeqCst) {
31665                    match listener.accept() {
31666                        Ok((mut stream, _)) => {
31667                            if behavior.concurrent_requests {
31668                                let requests = Arc::clone(&server_requests);
31669                                request_threads.push(thread::spawn(move || {
31670                                    handle_mock_worker_request(&mut stream, &requests, behavior)
31671                                }));
31672                            } else {
31673                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
31674                            }
31675                        }
31676                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
31677                            let mut index = 0;
31678                            while index < request_threads.len() {
31679                                if request_threads[index].is_finished() {
31680                                    request_threads
31681                                        .swap_remove(index)
31682                                        .join()
31683                                        .expect("join mock request");
31684                                } else {
31685                                    index += 1;
31686                                }
31687                            }
31688                            thread::sleep(Duration::from_millis(5));
31689                        }
31690                        Err(_) => break,
31691                    }
31692                }
31693                for request_thread in request_threads {
31694                    request_thread.join().expect("join mock request");
31695                }
31696            });
31697
31698            Self {
31699                addr,
31700                stop,
31701                requests,
31702                thread: Some(thread),
31703            }
31704        }
31705
31706        fn base_url(&self) -> String {
31707            format!("http://{}", self.addr)
31708        }
31709
31710        fn worker_protocol_for(&self, path: &str) -> Option<String> {
31711            self.requests
31712                .lock()
31713                .expect("captured requests")
31714                .iter()
31715                .find(|request| request.path == path)
31716                .and_then(|request| request.worker_protocol.clone())
31717        }
31718
31719        fn control_protocol_for(&self, path: &str) -> Option<String> {
31720            self.requests
31721                .lock()
31722                .expect("captured requests")
31723                .iter()
31724                .find(|request| request.path == path)
31725                .and_then(|request| request.control_protocol.clone())
31726        }
31727
31728        fn method_for(&self, path: &str) -> Option<String> {
31729            self.requests
31730                .lock()
31731                .expect("captured requests")
31732                .iter()
31733                .find(|request| request.path == path)
31734                .map(|request| request.method.clone())
31735        }
31736
31737        fn authorization_for(&self, path: &str) -> Option<String> {
31738            self.requests
31739                .lock()
31740                .expect("captured requests")
31741                .iter()
31742                .find(|request| request.path == path)
31743                .and_then(|request| request.authorization.clone())
31744        }
31745
31746        fn namespace_for(&self, path: &str) -> Option<String> {
31747            self.requests
31748                .lock()
31749                .expect("captured requests")
31750                .iter()
31751                .find(|request| request.path == path)
31752                .and_then(|request| request.namespace.clone())
31753        }
31754
31755        fn request_count(&self, path: &str) -> usize {
31756            self.requests
31757                .lock()
31758                .expect("captured requests")
31759                .iter()
31760                .filter(|request| request.path == path)
31761                .count()
31762        }
31763
31764        fn captured_paths(&self) -> Vec<String> {
31765            self.requests
31766                .lock()
31767                .expect("captured requests")
31768                .iter()
31769                .map(|request| request.path.clone())
31770                .collect()
31771        }
31772
31773        fn request_times(&self, path: &str) -> Vec<Instant> {
31774            self.requests
31775                .lock()
31776                .expect("captured requests")
31777                .iter()
31778                .filter(|request| request.path == path)
31779                .map(|request| request.received_at)
31780                .collect()
31781        }
31782
31783        fn request_body(&self, path: &str) -> Value {
31784            let requests = self.requests.lock().expect("captured requests");
31785            let body = &requests
31786                .iter()
31787                .find(|request| request.path == path)
31788                .unwrap_or_else(|| panic!("missing request for {path}"))
31789                .body;
31790            serde_json::from_str(body).unwrap_or_else(|error| {
31791                panic!("invalid JSON request body for {path}: {error}: {body:?}")
31792            })
31793        }
31794
31795        fn request_bodies(&self, path: &str) -> Vec<Value> {
31796            self.requests
31797                .lock()
31798                .expect("captured requests")
31799                .iter()
31800                .filter(|request| request.path == path)
31801                .map(|request| {
31802                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
31803                        panic!(
31804                            "invalid JSON request body for {path}: {error}: {:?}",
31805                            request.body
31806                        )
31807                    })
31808                })
31809                .collect()
31810        }
31811
31812        fn request_headers(&self, path: &str) -> Vec<String> {
31813            self.requests
31814                .lock()
31815                .expect("captured requests")
31816                .iter()
31817                .filter(|request| request.path == path)
31818                .map(|request| request.headers.clone())
31819                .collect()
31820        }
31821    }
31822
31823    impl Drop for MockWorkerServer {
31824        fn drop(&mut self) {
31825            self.stop.store(true, Ordering::SeqCst);
31826            let _ = TcpStream::connect(self.addr);
31827
31828            if let Some(thread) = self.thread.take() {
31829                thread.join().expect("join mock server");
31830            }
31831        }
31832    }
31833
31834    #[test]
31835    fn closed_mock_connection_is_not_a_worker_request() {
31836        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
31837        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
31838        let (mut stream, _) = listener.accept().unwrap();
31839        drop(client);
31840        let requests = Arc::new(Mutex::new(Vec::new()));
31841        handle_mock_worker_request(
31842            &mut stream,
31843            &requests,
31844            MockWorkerBehavior {
31845                request_override: Some(|_, _, _| {
31846                    panic!("closed connection cannot invoke an HTTP handler")
31847                }),
31848                ..MockWorkerBehavior::default()
31849            },
31850        );
31851        assert!(requests.lock().unwrap().is_empty());
31852    }
31853
31854    fn handle_mock_worker_request(
31855        stream: &mut TcpStream,
31856        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
31857        behavior: MockWorkerBehavior,
31858    ) {
31859        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
31860        let mut buffer = [0_u8; 8192];
31861        let mut request = Vec::new();
31862
31863        loop {
31864            match stream.read(&mut buffer) {
31865                Ok(0) => break,
31866                Ok(read) => {
31867                    request.extend_from_slice(&buffer[..read]);
31868                    if mock_request_is_complete(&request) {
31869                        break;
31870                    }
31871                }
31872                Err(error)
31873                    if matches!(
31874                        error.kind(),
31875                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
31876                    ) =>
31877                {
31878                    break;
31879                }
31880                Err(_) => return,
31881            }
31882        }
31883
31884        if !mock_request_is_complete(&request) {
31885            return;
31886        }
31887
31888        let request = String::from_utf8_lossy(&request);
31889        let body = request
31890            .split_once("\r\n\r\n")
31891            .map(|(_, body)| body)
31892            .unwrap_or_default();
31893        let path = request
31894            .lines()
31895            .next()
31896            .and_then(|line| line.split_whitespace().nth(1))
31897            .unwrap_or_default();
31898        let method = request
31899            .lines()
31900            .next()
31901            .and_then(|line| line.split_whitespace().next())
31902            .unwrap_or_default();
31903        let authorization = request.lines().find_map(|line| {
31904            let (name, value) = line.split_once(':')?;
31905            name.eq_ignore_ascii_case("Authorization")
31906                .then(|| value.trim().to_string())
31907        });
31908        let namespace = request.lines().find_map(|line| {
31909            let (name, value) = line.split_once(':')?;
31910            name.eq_ignore_ascii_case("X-Namespace")
31911                .then(|| value.trim().to_string())
31912        });
31913        let worker_protocol = request.lines().find_map(|line| {
31914            let (name, value) = line.split_once(':')?;
31915            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
31916                .then(|| value.trim().to_string())
31917        });
31918        let control_protocol = request.lines().find_map(|line| {
31919            let (name, value) = line.split_once(':')?;
31920            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
31921                .then(|| value.trim().to_string())
31922        });
31923        let request_number = {
31924            let mut requests = requests.lock().expect("captured requests");
31925            requests.push(CapturedRequest {
31926                headers: request
31927                    .split_once("\r\n\r\n")
31928                    .map_or("", |(headers, _)| headers)
31929                    .to_owned(),
31930                method: method.to_string(),
31931                path: path.to_string(),
31932                authorization,
31933                namespace,
31934                worker_protocol: worker_protocol.clone(),
31935                control_protocol,
31936                body: body.to_string(),
31937                received_at: Instant::now(),
31938            });
31939            requests
31940                .iter()
31941                .filter(|request| request.path == path)
31942                .count()
31943        };
31944
31945        if behavior
31946            .drop_request
31947            .is_some_and(|dropped| dropped(path, request_number))
31948        {
31949            return;
31950        }
31951        if let Some(response) = behavior
31952            .request_override
31953            .and_then(|handler| handler(path, body, request_number))
31954        {
31955            write_mock_response(stream, response.0, &response.1);
31956            return;
31957        }
31958        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
31959            write_mock_response(stream, response.0, &response.1);
31960            return;
31961        }
31962        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
31963            return;
31964        }
31965        let pressure_path = behavior
31966            .storage_path
31967            .is_some_and(|part| path.contains(part));
31968        let prior_failures = if path.ends_with("/poll") {
31969            behavior.poll_failures_per_path
31970        } else {
31971            0
31972        };
31973        if pressure_path
31974            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
31975        {
31976            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
31977            let poll_id = path
31978                .ends_with("/poll")
31979                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
31980            let mut refusal = storage_refusal(
31981                poll_id,
31982                behavior.storage_unavailable,
31983                behavior.storage_mid_poll,
31984            );
31985            if behavior.storage_wrong_poll_id {
31986                refusal["poll_request_id"] = json!("wrong-poll");
31987            }
31988            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
31989            return;
31990        }
31991        if path.contains("/storage-task/")
31992            || path.contains("/storage-activity/")
31993            || path.contains("/storage-query/")
31994        {
31995            write_mock_response(stream, "200 OK", "{}");
31996            return;
31997        }
31998        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
31999            write_mock_response(stream, "200 OK", &json!({"task":{
32000                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
32001                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
32002                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32003                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32004                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
32005            }}).to_string());
32006            return;
32007        }
32008        if behavior.storage_activity
32009            && path == "/api/worker/activity-tasks/poll"
32010            && request_number == 1
32011        {
32012            write_mock_response(stream, "200 OK", &json!({"task":{
32013                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
32014                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32015                "attempt_number":7, "lease_owner":"storage-worker"
32016            }}).to_string());
32017            return;
32018        }
32019
32020        if path == "/api/worker/register" {
32021            if behavior.reject_registration_protocol {
32022                write_mock_response(
32023                    stream,
32024                    "400 Bad Request",
32025                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
32026                );
32027                return;
32028            }
32029            if behavior.reject_registration {
32030                write_mock_response(
32031                    stream,
32032                    "503 Service Unavailable",
32033                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
32034                );
32035                return;
32036            }
32037        }
32038
32039        if path.starts_with("/api/worker/registrations/") {
32040            if behavior.reject_deregistration_protocol {
32041                write_mock_response(
32042                    stream,
32043                    "400 Bad Request",
32044                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
32045                );
32046            } else if behavior.reject_deregistration {
32047                write_mock_response(
32048                    stream,
32049                    "403 Forbidden",
32050                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
32051                );
32052            } else {
32053                write_mock_response(
32054                    stream,
32055                    "200 OK",
32056                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
32057                );
32058            }
32059            return;
32060        }
32061
32062        let is_poll = matches!(
32063            path,
32064            "/api/worker/workflow-tasks/poll"
32065                | "/api/worker/activity-tasks/poll"
32066                | "/api/worker/query-tasks/poll"
32067        );
32068        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
32069            write_mock_response(
32070                stream,
32071                "429 Too Many Requests",
32072                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
32073            );
32074            return;
32075        }
32076        if is_poll && request_number <= behavior.poll_failures_per_path {
32077            return;
32078        }
32079        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
32080            return;
32081        }
32082        if path == "/api/worker/heartbeat"
32083            && behavior.heartbeat_failure_request == Some(request_number)
32084        {
32085            return;
32086        }
32087        if path == "/api/worker/heartbeat"
32088            && behavior.delayed_heartbeat_request == Some(request_number)
32089        {
32090            thread::sleep(behavior.heartbeat_response_delay);
32091        }
32092        if behavior.unauthorized_polls && is_poll {
32093            write_mock_response(
32094                stream,
32095                "401 Unauthorized",
32096                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
32097            );
32098            return;
32099        }
32100        if behavior.draining_polls && is_poll {
32101            write_mock_response(
32102                stream,
32103                "409 Conflict",
32104                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
32105            );
32106            return;
32107        }
32108
32109        if let Some(codec_case) = behavior.invalid_task_payload_codec {
32110            if is_poll && request_number == 1 {
32111                let mut task = match path {
32112                    "/api/worker/workflow-tasks/poll" => json!({
32113                        "task_id": "codec-workflow",
32114                        "workflow_type": "codec.workflow",
32115                        "payload_codec": DEFAULT_CODEC,
32116                        "workflow_task_attempt": 1,
32117                        "lease_owner": "codec-worker"
32118                    }),
32119                    "/api/worker/activity-tasks/poll" => json!({
32120                        "task_id": "codec-activity",
32121                        "activity_attempt_id": "codec-activity-attempt",
32122                        "activity_type": "codec.activity",
32123                        "payload_codec": DEFAULT_CODEC,
32124                        "attempt_number": 1,
32125                        "lease_owner": "codec-worker"
32126                    }),
32127                    "/api/worker/query-tasks/poll" => json!({
32128                        "query_task_id": "codec-query",
32129                        "query_task_attempt": 1,
32130                        "workflow_type": "codec.workflow",
32131                        "query_name": "known",
32132                        "payload_codec": DEFAULT_CODEC,
32133                        "lease_owner": "codec-worker"
32134                    }),
32135                    _ => unreachable!("is_poll limits task codec probe paths"),
32136                };
32137                codec_case.apply(&mut task);
32138                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
32139                return;
32140            }
32141
32142            if matches!(
32143                path,
32144                "/api/worker/workflow-tasks/codec-workflow/fail"
32145                    | "/api/worker/activity-tasks/codec-activity/fail"
32146                    | "/api/worker/query-tasks/codec-query/fail"
32147            ) {
32148                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
32149                return;
32150            }
32151        }
32152
32153        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
32154            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
32155            let body = format!(
32156                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
32157            );
32158            write_mock_response(stream, "400 Bad Request", &body);
32159            return;
32160        }
32161
32162        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
32163        {
32164            write_mock_response(
32165                stream,
32166                "409 Conflict",
32167                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
32168            );
32169            return;
32170        }
32171
32172        if behavior.workflow_completion_status.is_some()
32173            && path == "/api/worker/workflow-tasks/poll"
32174            && request_number == 1
32175        {
32176            write_mock_response(
32177                stream,
32178                "200 OK",
32179                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"}}"#,
32180            );
32181            return;
32182        }
32183
32184        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
32185            if let (Some(status), Some(body)) = (
32186                behavior.workflow_completion_status,
32187                behavior.workflow_completion_body,
32188            ) {
32189                write_mock_response(stream, status, body);
32190                return;
32191            }
32192        }
32193
32194        if behavior.waiting_query_worker {
32195            if behavior.complete_named_signal
32196                && path == "/api/worker/workflow-tasks/poll"
32197                && request_number == 1
32198            {
32199                let body = json!({
32200                    "task": {
32201                        "task_id": "snapshot-open",
32202                        "workflow_id": "snapshot-1",
32203                        "run_id": "snapshot-run-1",
32204                        "workflow_type": "snapshot",
32205                        "payload_codec": DEFAULT_CODEC,
32206                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32207                            .expect("Avro workflow arguments"),
32208                        "history_events": [],
32209                        "workflow_task_attempt": 1,
32210                        "lease_owner": "rust-snapshot-worker"
32211                    }
32212                })
32213                .to_string();
32214                write_mock_response(stream, "200 OK", &body);
32215                return;
32216            }
32217
32218            let signal_request = request_number - usize::from(behavior.complete_named_signal);
32219            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
32220            if path == "/api/worker/workflow-tasks/poll"
32221                && signal_request >= 1
32222                && signal_request <= signal_request_limit
32223            {
32224                let finish = behavior.complete_named_signal && signal_request == 3;
32225                let amounts = if signal_request == 1 {
32226                    vec![3]
32227                } else {
32228                    vec![3, 5]
32229                };
32230                let task_id = if signal_request == 1 {
32231                    "snapshot-wait-3"
32232                } else if finish {
32233                    "snapshot-finish"
32234                } else {
32235                    "snapshot-wait-5"
32236                };
32237                let mut history_events = std::iter::once(json!({
32238                    "event_type": "SignalWaitOpened",
32239                    "payload": {"sequence": 1, "signal_name": "finish"}
32240                }))
32241                .chain(amounts.iter().enumerate().map(|(index, amount)| {
32242                    json!({
32243                        "event_type": "SignalReceived",
32244                        "payload": {
32245                            "signal_id": format!("increment-{amount}"),
32246                            "signal_name": "increment",
32247                            "workflow_sequence": index + 2,
32248                            "payload_codec": DEFAULT_CODEC,
32249                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32250                                .expect("Avro signal envelope")
32251                        }
32252                    })
32253                }))
32254                .collect::<Vec<_>>();
32255                let (resume_id, resume_name, resume_arguments) = if finish {
32256                    history_events.push(json!({
32257                        "event_type": "SignalReceived",
32258                        "payload": {
32259                            "signal_id": "finish",
32260                            "signal_name": "finish",
32261                            "workflow_sequence": 4,
32262                            "payload_codec": DEFAULT_CODEC,
32263                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32264                                .expect("Avro finish signal envelope")
32265                        }
32266                    }));
32267                    (
32268                        "finish".to_string(),
32269                        "finish".to_string(),
32270                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
32271                            .expect("Avro finish resume signal"),
32272                    )
32273                } else {
32274                    let amount = amounts.last().expect("amount");
32275                    (
32276                        format!("increment-{amount}"),
32277                        "increment".to_string(),
32278                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32279                            .expect("Avro increment resume signal"),
32280                    )
32281                };
32282                let body = json!({
32283                    "task": {
32284                        "task_id": task_id,
32285                        "workflow_id": "snapshot-1",
32286                        "run_id": "snapshot-run-1",
32287                        "workflow_type": "snapshot",
32288                        "payload_codec": DEFAULT_CODEC,
32289                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32290                            .expect("Avro workflow arguments"),
32291                        "history_events": history_events,
32292                        "workflow_task_attempt": 1,
32293                        "workflow_signal_id": resume_id,
32294                        "signal_name": resume_name,
32295                        "signal_arguments": resume_arguments,
32296                        "lease_owner": "rust-snapshot-worker"
32297                    }
32298                })
32299                .to_string();
32300                write_mock_response(stream, "200 OK", &body);
32301                return;
32302            }
32303
32304            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
32305                let history_events = [3, 5]
32306                    .into_iter()
32307                    .enumerate()
32308                    .map(|(index, amount)| {
32309                        json!({
32310                            "event_type": "SignalReceived",
32311                            "payload": {
32312                                "signal_id": format!("increment-{amount}"),
32313                                "signal_name": "increment",
32314                                "workflow_sequence": index + 2,
32315                                "payload_codec": DEFAULT_CODEC,
32316                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32317                                    .expect("Avro query signal envelope")
32318                            }
32319                        })
32320                    })
32321                    .collect::<Vec<_>>();
32322                let body = json!({
32323                    "task": {
32324                        "query_task_id": "snapshot-current",
32325                        "query_task_attempt": 1,
32326                        "lease_owner": "rust-snapshot-worker",
32327                        "workflow_id": "snapshot-1",
32328                        "run_id": "snapshot-run-1",
32329                        "workflow_type": "snapshot",
32330                        "query_name": "current",
32331                        "payload_codec": DEFAULT_CODEC,
32332                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32333                            .expect("Avro workflow arguments"),
32334                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32335                            .expect("Avro query arguments"),
32336                        "history_events": history_events,
32337                        "run_status": "waiting"
32338                    }
32339                })
32340                .to_string();
32341                write_mock_response(stream, "200 OK", &body);
32342                return;
32343            }
32344
32345            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
32346                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
32347            {
32348                write_mock_response(
32349                    stream,
32350                    "200 OK",
32351                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
32352                );
32353                return;
32354            }
32355
32356            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
32357                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
32358                return;
32359            }
32360
32361            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
32362                write_mock_response(
32363                    stream,
32364                    "200 OK",
32365                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
32366                );
32367                return;
32368            }
32369
32370            if path == "/api/worker/query-tasks/snapshot-current/complete" {
32371                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
32372                return;
32373            }
32374        }
32375
32376        if matches!(
32377            path,
32378            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
32379        ) {
32380            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32381                .expect("typed mock result");
32382            let body = json!({
32383                "result": typed_fidelity_probe().into_json().expect("result projection"),
32384                "result_envelope": result,
32385            })
32386            .to_string();
32387            write_mock_response(stream, "200 OK", &body);
32388            return;
32389        }
32390
32391        if path == "/api/workflows/typed-1" {
32392            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32393                .expect("typed mock result");
32394            let body = json!({
32395                "workflow_id": "typed-1",
32396                "run_id": "run-typed-1",
32397                "workflow_type": "typed.echo",
32398                "status": "completed",
32399                "output": typed_fidelity_probe().into_json().expect("output projection"),
32400                "output_envelope": result,
32401            })
32402            .to_string();
32403            write_mock_response(stream, "200 OK", &body);
32404            return;
32405        }
32406
32407        let (status, body) = match path {
32408            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
32409            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
32410            "/api/workflows" => (
32411                "201 Created",
32412                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
32413            ),
32414            "/api/worker/register" if behavior.decline_registration => (
32415                "200 OK",
32416                r#"{"worker_id":"declined-worker","registered":false}"#,
32417            ),
32418            "/api/worker/register" if behavior.waiting_query_worker => (
32419                "200 OK",
32420                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
32421            ),
32422            "/api/worker/register" => (
32423                "200 OK",
32424                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
32425            ),
32426            "/api/worker/heartbeat" => ("200 OK", "{}"),
32427            "/api/worker/activity-tasks/poll"
32428                if behavior.cancelled_activity && request_number == 1 =>
32429            {
32430                (
32431                    "200 OK",
32432                    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"}}"#,
32433                )
32434            }
32435            "/api/worker/activity-tasks/poll"
32436                if behavior.long_poll_capacity_responses_per_path > 0
32437                    && request_number
32438                        == behavior
32439                            .long_poll_capacity_responses_per_path
32440                            .saturating_add(1) =>
32441            {
32442                (
32443                    "200 OK",
32444                    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"}}"#,
32445                )
32446            }
32447            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
32448                ("200 OK", r#"{"task":null}"#)
32449            }
32450            "/api/worker/query-tasks/poll"
32451                if behavior.reject_query_completion && request_number == 1 =>
32452            {
32453                (
32454                    "200 OK",
32455                    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"}}"#,
32456                )
32457            }
32458            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
32459            "/api/worker/query-tasks/query-capture/complete"
32460            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
32461            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
32462                "200 OK",
32463                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
32464            ),
32465            "/api/worker/activity-tasks/activity-cancel/complete" => (
32466                "409 Conflict",
32467                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
32468            ),
32469            "/api/worker/activity-tasks/activity-typed/complete"
32470            | "/api/worker/activity-tasks/activity-typed/fail"
32471            | "/api/worker/activity-tasks/capacity-activity/complete"
32472            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
32473            "/api/workflows/counter-1/query/current" => (
32474                "200 OK",
32475                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
32476            ),
32477            "/api/workflows/counter-1/query/missing" => (
32478                "404 Not Found",
32479                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
32480            ),
32481            "/api/workflows/wf-lifecycle/cancel" => (
32482                "200 OK",
32483                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
32484            ),
32485            "/api/workflows/wf-lifecycle/terminate" => (
32486                "200 OK",
32487                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
32488            ),
32489            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
32490                "200 OK",
32491                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
32492            ),
32493            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
32494                "200 OK",
32495                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
32496            ),
32497            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
32498                "202 Accepted",
32499                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
32500            ),
32501            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
32502                "200 OK",
32503                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}"#,
32504            ),
32505            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
32506                "409 Conflict",
32507                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
32508            ),
32509            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
32510            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
32511                "409 Conflict",
32512                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
32513            ),
32514            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
32515                "200 OK",
32516                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"}]}}"#,
32517            ),
32518            "/api/workflows/wf-cancelled" => (
32519                "200 OK",
32520                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
32521            ),
32522            "/api/workflows/wf-terminated" => (
32523                "200 OK",
32524                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
32525            ),
32526            "/api/workflows/wf-timed-out" => (
32527                "200 OK",
32528                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
32529            ),
32530            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
32531                "200 OK",
32532                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
32533            ),
32534            "/api/workflows/wf-selected" => (
32535                "200 OK",
32536                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
32537            ),
32538            "/api/workflows/wf-selected/runs/run-selected" => (
32539                "200 OK",
32540                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
32541            ),
32542            _ => ("404 Not Found", r#"{"message":"not found"}"#),
32543        };
32544        write_mock_response(stream, status, body);
32545    }
32546
32547    fn mock_request_is_complete(request: &[u8]) -> bool {
32548        let Some(header_end) = request
32549            .windows(4)
32550            .position(|window| window == b"\r\n\r\n")
32551            .map(|position| position + 4)
32552        else {
32553            return false;
32554        };
32555        let headers = String::from_utf8_lossy(&request[..header_end]);
32556        let content_length = headers.lines().find_map(|line| {
32557            let (name, value) = line.split_once(':')?;
32558            name.eq_ignore_ascii_case("content-length")
32559                .then(|| value.trim().parse::<usize>().ok())
32560                .flatten()
32561        });
32562
32563        request.len() >= header_end + content_length.unwrap_or(0)
32564    }
32565
32566    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
32567        let response = format!(
32568            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
32569            body.len()
32570        );
32571
32572        let _ = stream.write_all(response.as_bytes());
32573        let _ = stream.flush();
32574    }
32575
32576    fn typed_activity_failure_server(
32577        path: &str,
32578        _body: &str,
32579        request_number: usize,
32580    ) -> Option<(&'static str, String)> {
32581        match path {
32582            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32583                "200 OK",
32584                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(),
32585            )),
32586            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
32587            _ => None,
32588        }
32589    }
32590
32591    #[tokio::test]
32592    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
32593        for non_retryable in [false, true] {
32594            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32595                request_override: Some(typed_activity_failure_server),
32596                ..MockWorkerBehavior::default()
32597            });
32598            let client = Client::builder(server.base_url()).build().unwrap();
32599            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
32600            worker.register_activity("typed.failure", move |_, _| async move {
32601                Err(ActivityError::new("PaymentDeclined", "card declined")
32602                    .non_retryable(non_retryable)
32603                    .into())
32604            });
32605            assert_eq!(worker.run_once().await.unwrap(), 1);
32606            assert_eq!(
32607                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
32608                json!({
32609                    "activity_attempt_id": "typed-attempt",
32610                    "lease_owner": "typed-worker",
32611                    "failure": {"type": "PaymentDeclined", "message": "card declined",
32612                                "non_retryable": non_retryable}
32613                })
32614            );
32615        }
32616    }
32617
32618    fn activity_completion_backend_recovery(
32619        path: &str,
32620        _body: &str,
32621        request_number: usize,
32622    ) -> Option<(&'static str, String)> {
32623        match path {
32624            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32625                "200 OK",
32626                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(),
32627            )),
32628            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
32629                "503 Service Unavailable",
32630                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(),
32631            )),
32632            "/api/worker/activity-tasks/recover-activity/complete" => Some((
32633                "200 OK",
32634                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32635            )),
32636            _ => None,
32637        }
32638    }
32639
32640    fn workflow_completion_backend_recovery(
32641        path: &str,
32642        _body: &str,
32643        request_number: usize,
32644    ) -> Option<(&'static str, String)> {
32645        match path {
32646            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
32647                "200 OK",
32648                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
32649            )),
32650            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
32651                "503 Service Unavailable",
32652                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(),
32653            )),
32654            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
32655                "200 OK",
32656                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32657            )),
32658            _ => None,
32659        }
32660    }
32661
32662    fn workflow_completion_lock_pressure(
32663        path: &str,
32664        body: &str,
32665        request_number: usize,
32666    ) -> Option<(&'static str, String)> {
32667        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
32668            return Some((
32669                "503 Service Unavailable",
32670                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32671                    "outcome":"deferred", "recorded":false, "retryable":true,
32672                    "retry_after_seconds":1, "task_id":"recover-workflow",
32673                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
32674                    "backend":{"driver":"sqlite", "lock_pressure":true}})
32675                .to_string(),
32676            ));
32677        }
32678        workflow_completion_backend_recovery(path, body, request_number)
32679    }
32680
32681    fn workflow_completion_lock_pressure_forever(
32682        path: &str,
32683        body: &str,
32684        request_number: usize,
32685    ) -> Option<(&'static str, String)> {
32686        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
32687            return workflow_completion_lock_pressure(path, body, 1);
32688        }
32689        workflow_completion_lock_pressure(path, body, request_number)
32690    }
32691
32692    fn workflow_completion_lock_pressure_then_expired(
32693        path: &str,
32694        body: &str,
32695        request_number: usize,
32696    ) -> Option<(&'static str, String)> {
32697        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32698            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
32699                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
32700        }
32701        workflow_completion_lock_pressure(path, body, request_number)
32702    }
32703
32704    fn workflow_completion_lock_pressure_then_slow(
32705        path: &str,
32706        body: &str,
32707        request_number: usize,
32708    ) -> Option<(&'static str, String)> {
32709        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32710            thread::sleep(Duration::from_secs(2));
32711        }
32712        workflow_completion_lock_pressure(path, body, request_number)
32713    }
32714
32715    fn workflow_completion_pressure_then_backend_loss(
32716        path: &str,
32717        body: &str,
32718        request_number: usize,
32719    ) -> Option<(&'static str, String)> {
32720        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32721            return Some((
32722                "503 Service Unavailable",
32723                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
32724                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
32725                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
32726                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
32727                .to_string(),
32728            ));
32729        }
32730        workflow_completion_lock_pressure(path, body, request_number)
32731    }
32732
32733    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
32734        let client = Client::builder(server.base_url())
32735            .timeout(Duration::from_secs(4))
32736            .build()
32737            .unwrap();
32738        let mut worker = Worker::new(client, "recover-queue")
32739            .worker_id("recover-worker")
32740            .poll_timeout(Duration::from_millis(10));
32741        worker.register_workflow("recover.workflow", move |_ctx, _args| {
32742            let calls = Arc::clone(&calls);
32743            async move {
32744                calls.fetch_add(1, Ordering::SeqCst);
32745                Ok(json!("done"))
32746            }
32747        });
32748        worker
32749    }
32750
32751    #[tokio::test]
32752    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
32753        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32754            request_override: Some(workflow_completion_lock_pressure_forever),
32755            ..MockWorkerBehavior::default()
32756        });
32757        let calls = Arc::new(AtomicUsize::new(0));
32758        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32759            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32760        worker
32761            .client
32762            .worker_storage_admission
32763            .as_mut()
32764            .unwrap()
32765            .workflow_completion_retry_deadline =
32766            Some(tokio::time::Instant::now() + Duration::from_millis(250));
32767        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
32768            .await
32769            .unwrap();
32770        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32771        assert_eq!(calls.load(Ordering::SeqCst), 1);
32772        assert_eq!(
32773            server
32774                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32775                .len(),
32776            1
32777        );
32778    }
32779
32780    #[tokio::test]
32781    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
32782        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32783            request_override: Some(workflow_completion_lock_pressure_then_slow),
32784            ..MockWorkerBehavior::default()
32785        });
32786        let calls = Arc::new(AtomicUsize::new(0));
32787        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32788            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32789        let start = tokio::time::Instant::now();
32790        worker
32791            .client
32792            .worker_storage_admission
32793            .as_mut()
32794            .unwrap()
32795            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32796        assert!(matches!(
32797            worker.poll_workflow_once().await,
32798            Err(Error::Timeout)
32799        ));
32800        assert!(start.elapsed() < Duration::from_secs(2));
32801        assert_eq!(calls.load(Ordering::SeqCst), 1);
32802        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32803        assert_eq!(bodies.len(), 2);
32804        assert_eq!(bodies[0], bodies[1]);
32805    }
32806
32807    #[tokio::test]
32808    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
32809        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32810            request_override: Some(workflow_completion_pressure_then_backend_loss),
32811            ..MockWorkerBehavior::default()
32812        });
32813        let calls = Arc::new(AtomicUsize::new(0));
32814        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32815            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32816        let start = tokio::time::Instant::now();
32817        worker
32818            .client
32819            .worker_storage_admission
32820            .as_mut()
32821            .unwrap()
32822            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32823        let result = worker.poll_workflow_once().await;
32824        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32825        assert!(start.elapsed() < Duration::from_secs(2));
32826        assert_eq!(calls.load(Ordering::SeqCst), 1);
32827        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32828        assert_eq!(bodies.len(), 2);
32829        assert_eq!(bodies[0], bodies[1]);
32830    }
32831
32832    #[tokio::test]
32833    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
32834        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32835            request_override: Some(workflow_completion_lock_pressure_forever),
32836            ..MockWorkerBehavior::default()
32837        });
32838        let calls = Arc::new(AtomicUsize::new(0));
32839        let stop = Arc::new(AtomicBool::new(false));
32840        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
32841            .with_storage_admission(Arc::clone(&stop));
32842        let shutdown = async {
32843            while server
32844                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32845                .is_empty()
32846            {
32847                tokio::time::sleep(Duration::from_millis(10)).await;
32848            }
32849            stop.store(true, Ordering::SeqCst);
32850        };
32851        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
32852            tokio::join!(worker.poll_workflow_once(), shutdown)
32853        })
32854        .await
32855        .unwrap();
32856        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32857        assert_eq!(calls.load(Ordering::SeqCst), 1);
32858        assert_eq!(
32859            server
32860                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32861                .len(),
32862            1
32863        );
32864    }
32865
32866    #[tokio::test]
32867    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
32868        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32869            request_override: Some(workflow_completion_lock_pressure_then_expired),
32870            ..MockWorkerBehavior::default()
32871        });
32872        let calls = Arc::new(AtomicUsize::new(0));
32873        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
32874        let result = worker.run_once().await;
32875        assert!(
32876            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
32877        );
32878        assert_eq!(calls.load(Ordering::SeqCst), 1);
32879        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32880        assert_eq!(bodies.len(), 2);
32881        assert_eq!(bodies[0], bodies[1]);
32882        assert!(server
32883            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
32884            .is_empty());
32885    }
32886
32887    #[tokio::test]
32888    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
32889        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32890            request_override: Some(workflow_completion_lock_pressure),
32891            ..MockWorkerBehavior::default()
32892        });
32893        let client = Client::builder(server.base_url())
32894            .timeout(Duration::from_secs(2))
32895            .build()
32896            .unwrap();
32897        let calls = Arc::new(AtomicUsize::new(0));
32898        let mut worker = Worker::new(client, "recover-queue")
32899            .worker_id("recover-worker")
32900            .recover_transient_outages(true)
32901            .poll_timeout(Duration::from_millis(10))
32902            .retry_policy(WorkerRetryPolicy {
32903                max_retries: 1,
32904                initial_backoff: Duration::from_millis(10),
32905                max_backoff: Duration::from_millis(10),
32906            });
32907        worker.register_workflow("recover.workflow", {
32908            let calls = Arc::clone(&calls);
32909            move |_ctx, _args| {
32910                let calls = Arc::clone(&calls);
32911                async move {
32912                    calls.fetch_add(1, Ordering::SeqCst);
32913                    Ok(json!("done"))
32914                }
32915            }
32916        });
32917        let start = tokio::time::Instant::now();
32918        assert_eq!(worker.run_once().await.unwrap(), 1);
32919        assert!(start.elapsed() >= Duration::from_secs(1));
32920        assert_eq!(calls.load(Ordering::SeqCst), 1);
32921        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32922        assert_eq!(bodies.len(), 2);
32923        assert_eq!(bodies[0], bodies[1]);
32924    }
32925
32926    #[test]
32927    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
32928        let path = "/worker/workflow-tasks/recover-workflow/complete";
32929        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
32930        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32931            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
32932            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
32933            "backend":{"driver":"sqlite", "lock_pressure":true}});
32934        let error = |body: Value| Error::Http {
32935            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
32936            body: body.to_string(),
32937        };
32938        assert_eq!(
32939            worker_deferred_workflow_completion_retry_after(
32940                &error(response.clone()),
32941                path,
32942                Some(&request)
32943            ),
32944            Some(Duration::from_secs(1))
32945        );
32946        for (field, value) in [
32947            ("reason", json!("backend_unavailable")),
32948            ("operation", json!("complete_activity_task")),
32949            ("task_id", json!("other-task")),
32950            ("lease_owner", json!("other-owner")),
32951            ("workflow_task_attempt", json!(4)),
32952            ("recorded", json!(true)),
32953            ("recorded", Value::Null),
32954            ("recorded", json!("false")),
32955            ("retryable", json!(false)),
32956            ("retry_after_seconds", json!(0)),
32957            ("retry_after_seconds", json!(-1)),
32958            ("retry_after_seconds", json!(1.0)),
32959            ("retry_after_seconds", json!("1")),
32960            ("retry_after_seconds", json!(6)),
32961            ("backend", json!({"lock_pressure":false})),
32962        ] {
32963            let mut invalid = response.clone();
32964            invalid[field] = value;
32965            assert_eq!(
32966                worker_deferred_workflow_completion_retry_after(
32967                    &error(invalid),
32968                    path,
32969                    Some(&request)
32970                ),
32971                None,
32972                "invalid {field}"
32973            );
32974        }
32975        for field in [
32976            "reason",
32977            "operation",
32978            "task_id",
32979            "lease_owner",
32980            "workflow_task_attempt",
32981            "recorded",
32982            "retryable",
32983            "retry_after_seconds",
32984            "backend",
32985        ] {
32986            let mut missing = response.clone();
32987            missing.as_object_mut().unwrap().remove(field);
32988            assert_eq!(
32989                worker_deferred_workflow_completion_retry_after(
32990                    &error(missing),
32991                    path,
32992                    Some(&request)
32993                ),
32994                None,
32995                "missing {field}"
32996            );
32997        }
32998        assert_eq!(
32999            worker_deferred_workflow_completion_retry_after(
33000                &error(response.clone()),
33001                "/worker/activity-tasks/recover-workflow/complete",
33002                Some(&request)
33003            ),
33004            None
33005        );
33006        assert_eq!(
33007            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
33008            None
33009        );
33010        let wrong_status = Error::Http {
33011            status: reqwest::StatusCode::CONFLICT,
33012            body: response.to_string(),
33013        };
33014        assert_eq!(
33015            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
33016            None
33017        );
33018    }
33019
33020    fn activity_completion_stale_after_backend_recovery(
33021        path: &str,
33022        body: &str,
33023        request_number: usize,
33024    ) -> Option<(&'static str, String)> {
33025        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
33026            return Some((
33027                "409 Conflict",
33028                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(),
33029            ));
33030        }
33031        activity_completion_backend_recovery(path, body, request_number)
33032    }
33033
33034    fn activity_completion_remains_unavailable(
33035        path: &str,
33036        body: &str,
33037        request_number: usize,
33038    ) -> Option<(&'static str, String)> {
33039        if path == "/api/worker/activity-tasks/recover-activity/complete" {
33040            return activity_completion_backend_recovery(path, body, 1);
33041        }
33042        activity_completion_backend_recovery(path, body, request_number)
33043    }
33044
33045    #[tokio::test]
33046    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
33047        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33048            request_override: Some(activity_completion_backend_recovery),
33049            ..MockWorkerBehavior::default()
33050        });
33051        let client = Client::builder(server.base_url())
33052            .timeout(Duration::from_secs(2))
33053            .build()
33054            .expect("client");
33055        let handler_calls = Arc::new(AtomicUsize::new(0));
33056        let mut worker = Worker::new(client, "recover-queue")
33057            .worker_id("recover-worker")
33058            .poll_timeout(Duration::from_millis(10));
33059        worker.register_activity("recover.activity", {
33060            let handler_calls = Arc::clone(&handler_calls);
33061            move |_ctx, _args| {
33062                let handler_calls = Arc::clone(&handler_calls);
33063                async move {
33064                    handler_calls.fetch_add(1, Ordering::SeqCst);
33065                    Ok(json!("done"))
33066                }
33067            }
33068        });
33069
33070        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33071        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33072        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33073        assert_eq!(bodies.len(), 2);
33074        assert_eq!(bodies[0], bodies[1]);
33075    }
33076
33077    #[tokio::test]
33078    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
33079        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33080            request_override: Some(workflow_completion_backend_recovery),
33081            ..MockWorkerBehavior::default()
33082        });
33083        let client = Client::builder(server.base_url())
33084            .timeout(Duration::from_secs(2))
33085            .build()
33086            .expect("client");
33087        let handler_calls = Arc::new(AtomicUsize::new(0));
33088        let mut worker = Worker::new(client, "recover-queue")
33089            .worker_id("recover-worker")
33090            .poll_timeout(Duration::from_millis(10));
33091        worker.register_workflow("recover.workflow", {
33092            let handler_calls = Arc::clone(&handler_calls);
33093            move |_ctx, _args| {
33094                let handler_calls = Arc::clone(&handler_calls);
33095                async move {
33096                    handler_calls.fetch_add(1, Ordering::SeqCst);
33097                    Ok(json!("done"))
33098                }
33099            }
33100        });
33101
33102        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
33103        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33104        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
33105        assert_eq!(bodies.len(), 2);
33106        assert_eq!(bodies[0], bodies[1]);
33107    }
33108
33109    #[tokio::test]
33110    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
33111        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33112            request_override: Some(activity_completion_stale_after_backend_recovery),
33113            ..MockWorkerBehavior::default()
33114        });
33115        let client = Client::builder(server.base_url())
33116            .timeout(Duration::from_secs(2))
33117            .build()
33118            .expect("client");
33119        let handler_calls = Arc::new(AtomicUsize::new(0));
33120        let mut worker = Worker::new(client, "recover-queue")
33121            .worker_id("recover-worker")
33122            .poll_timeout(Duration::from_millis(10));
33123        worker.register_activity("recover.activity", {
33124            let handler_calls = Arc::clone(&handler_calls);
33125            move |_ctx, _args| {
33126                let handler_calls = Arc::clone(&handler_calls);
33127                async move {
33128                    handler_calls.fetch_add(1, Ordering::SeqCst);
33129                    Ok(json!("done"))
33130                }
33131            }
33132        });
33133
33134        assert_eq!(
33135            worker
33136                .run_once()
33137                .await
33138                .expect("authoritative stale outcome"),
33139            1
33140        );
33141        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33142        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33143        assert_eq!(bodies.len(), 2);
33144        assert_eq!(bodies[0], bodies[1]);
33145    }
33146
33147    #[test]
33148    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
33149        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
33150        let response = json!({
33151            "reason":"backend_unavailable", "operation":"complete_activity_task",
33152            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
33153            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
33154            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
33155        });
33156        let path = "/worker/activity-tasks/recover-activity/complete";
33157        let error = |body: Value| Error::Http {
33158            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33159            body: body.to_string(),
33160        };
33161        assert_eq!(
33162            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
33163            Some(Duration::from_secs(1))
33164        );
33165
33166        for (field, invalid) in [
33167            ("operation", json!("poll_activity_task")),
33168            ("outcome", json!("rejected")),
33169            ("worker_id", json!("another-worker")),
33170            ("task_queue", json!("recover-queue")),
33171            ("retryable", json!(false)),
33172            ("retry_after_seconds", json!(0)),
33173            ("task_id", json!("another-task")),
33174            ("lease_owner", json!("another-worker")),
33175            ("activity_attempt_id", json!("another-attempt")),
33176        ] {
33177            let mut invalid_response = response.clone();
33178            invalid_response[field] = invalid;
33179            assert_eq!(
33180                worker_fenced_completion_retry_after(
33181                    &error(invalid_response),
33182                    path,
33183                    Some(&request)
33184                ),
33185                None,
33186                "must not retry mismatched {field}"
33187            );
33188        }
33189        assert_eq!(
33190            worker_fenced_completion_retry_after(&error(response), path, None),
33191            None
33192        );
33193    }
33194
33195    #[tokio::test]
33196    async fn shutdown_interrupts_fenced_completion_backend_wait() {
33197        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33198            request_override: Some(activity_completion_remains_unavailable),
33199            ..MockWorkerBehavior::default()
33200        });
33201        let client = Client::builder(server.base_url())
33202            .timeout(Duration::from_secs(2))
33203            .build()
33204            .expect("client");
33205        let stop = Arc::new(AtomicBool::new(false));
33206        let worker = Worker::new(client, "recover-queue")
33207            .worker_id("recover-worker")
33208            .with_storage_admission(Arc::clone(&stop));
33209        let completion = tokio::spawn(async move {
33210            worker
33211                .client
33212                .complete_activity_task(
33213                    "recover-activity",
33214                    "recover-attempt",
33215                    "recover-worker",
33216                    json!("done"),
33217                    DEFAULT_CODEC,
33218                )
33219                .await
33220        });
33221        let path = "/api/worker/activity-tasks/recover-activity/complete";
33222        tokio::time::timeout(Duration::from_secs(2), async {
33223            while server.request_count(path) == 0 {
33224                tokio::time::sleep(Duration::from_millis(10)).await;
33225            }
33226        })
33227        .await
33228        .expect("first completion request");
33229        stop.store(true, Ordering::SeqCst);
33230        let error = tokio::time::timeout(Duration::from_secs(1), completion)
33231            .await
33232            .expect("shutdown must interrupt retry wait")
33233            .expect("completion task")
33234            .expect_err("backend is still unavailable");
33235        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
33236        assert_eq!(server.request_count(path), 1);
33237    }
33238}